fold.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. // Copyright 2020 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package json
  5. import (
  6. "unicode"
  7. "unicode/utf8"
  8. )
  9. // foldName returns a folded string such that foldName(x) == foldName(y)
  10. // is similar to strings.EqualFold(x, y), but ignores underscore and dashes.
  11. // This allows foldName to match common naming conventions.
  12. func foldName(in []byte) []byte {
  13. // This is inlinable to take advantage of "function outlining".
  14. // See https://blog.filippo.io/efficient-go-apis-with-the-inliner/
  15. var arr [32]byte // large enough for most JSON names
  16. return appendFoldedName(arr[:0], in)
  17. }
  18. func appendFoldedName(out, in []byte) []byte {
  19. for i := 0; i < len(in); {
  20. // Handle single-byte ASCII.
  21. if c := in[i]; c < utf8.RuneSelf {
  22. if c != '_' && c != '-' {
  23. if 'a' <= c && c <= 'z' {
  24. c -= 'a' - 'A'
  25. }
  26. out = append(out, c)
  27. }
  28. i++
  29. continue
  30. }
  31. // Handle multi-byte Unicode.
  32. r, n := utf8.DecodeRune(in[i:])
  33. out = utf8.AppendRune(out, foldRune(r))
  34. i += n
  35. }
  36. return out
  37. }
  38. // foldRune is a variation on unicode.SimpleFold that returns the same rune
  39. // for all runes in the same fold set.
  40. //
  41. // Invariant:
  42. //
  43. // foldRune(x) == foldRune(y) ⇔ strings.EqualFold(string(x), string(y))
  44. func foldRune(r rune) rune {
  45. for {
  46. r2 := unicode.SimpleFold(r)
  47. if r2 <= r {
  48. return r2 // smallest character in the fold set
  49. }
  50. r = r2
  51. }
  52. }