strings.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. package ini
  2. import (
  3. "strings"
  4. )
  5. func trimProfileComment(s string) string {
  6. r, _, _ := strings.Cut(s, "#")
  7. r, _, _ = strings.Cut(r, ";")
  8. return r
  9. }
  10. func trimPropertyComment(s string) string {
  11. r, _, _ := strings.Cut(s, " #")
  12. r, _, _ = strings.Cut(r, " ;")
  13. r, _, _ = strings.Cut(r, "\t#")
  14. r, _, _ = strings.Cut(r, "\t;")
  15. return r
  16. }
  17. // assumes no surrounding comment
  18. func splitProperty(s string) (string, string, bool) {
  19. equalsi := strings.Index(s, "=")
  20. coloni := strings.Index(s, ":") // LEGACY: also supported for property assignment
  21. sep := "="
  22. if equalsi == -1 || coloni != -1 && coloni < equalsi {
  23. sep = ":"
  24. }
  25. k, v, ok := strings.Cut(s, sep)
  26. if !ok {
  27. return "", "", false
  28. }
  29. return strings.TrimSpace(k), strings.TrimSpace(v), true
  30. }
  31. // assumes no surrounding comment, whitespace, or profile brackets
  32. func splitProfile(s string) (string, string) {
  33. var first int
  34. for i, r := range s {
  35. if isLineSpace(r) {
  36. if first == 0 {
  37. first = i
  38. }
  39. } else {
  40. if first != 0 {
  41. return s[:first], s[i:]
  42. }
  43. }
  44. }
  45. if first == 0 {
  46. return "", s // type component is effectively blank
  47. }
  48. return "", ""
  49. }
  50. func isLineSpace(r rune) bool {
  51. return r == ' ' || r == '\t'
  52. }
  53. func unquote(s string) string {
  54. if isSingleQuoted(s) || isDoubleQuoted(s) {
  55. return s[1 : len(s)-1]
  56. }
  57. return s
  58. }
  59. // applies various legacy conversions to property values:
  60. // - remote wrapping single/doublequotes
  61. func legacyStrconv(s string) string {
  62. s = unquote(s)
  63. return s
  64. }
  65. func isSingleQuoted(s string) bool {
  66. return hasAffixes(s, "'", "'")
  67. }
  68. func isDoubleQuoted(s string) bool {
  69. return hasAffixes(s, `"`, `"`)
  70. }
  71. func isBracketed(s string) bool {
  72. return hasAffixes(s, "[", "]")
  73. }
  74. func hasAffixes(s, left, right string) bool {
  75. return strings.HasPrefix(s, left) && strings.HasSuffix(s, right)
  76. }