stringsx.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. // Copyright (c) Tailscale Inc & contributors
  2. // SPDX-License-Identifier: BSD-3-Clause
  3. // Package stringsx provides additional string manipulation functions
  4. // that aren't in the standard library's strings package or go4.org/mem.
  5. package stringsx
  6. import (
  7. "unicode"
  8. "unicode/utf8"
  9. )
  10. // CompareFold returns -1, 0, or 1 depending on whether a < b, a == b, or a > b,
  11. // like cmp.Compare, but case insensitively.
  12. func CompareFold(a, b string) int {
  13. // Track our position in both strings
  14. ia, ib := 0, 0
  15. for ia < len(a) && ib < len(b) {
  16. ra, wa := nextRuneLower(a[ia:])
  17. rb, wb := nextRuneLower(b[ib:])
  18. if ra < rb {
  19. return -1
  20. }
  21. if ra > rb {
  22. return 1
  23. }
  24. ia += wa
  25. ib += wb
  26. if wa == 0 || wb == 0 {
  27. break
  28. }
  29. }
  30. // If we've reached here, one or both strings are exhausted
  31. // The shorter string is "less than" if they match up to this point
  32. switch {
  33. case ia == len(a) && ib == len(b):
  34. return 0
  35. case ia == len(a):
  36. return -1
  37. default:
  38. return 1
  39. }
  40. }
  41. // nextRuneLower returns the next rune in the string, lowercased, along with its
  42. // original (consumed) width in bytes. If the string is empty, it returns
  43. // (utf8.RuneError, 0)
  44. func nextRuneLower(s string) (r rune, width int) {
  45. r, width = utf8.DecodeRuneInString(s)
  46. return unicode.ToLower(r), width
  47. }