Debian Codegraph @

strings/case.go

raw symbols SCIP
1 package strings
2
3 import (
4 "github.com/gofiber/utils/v2/internal/caseconv"
5 "github.com/gofiber/utils/v2/internal/unsafeconv"
6 )
7
8 // swarMinLen is the smallest input length worth routing through the
9 // word-at-a-time (SWAR) helpers; shorter inputs are cheaper byte-by-byte.
10 const swarMinLen = caseconv.WordLen
11
12 // ToLower converts an ASCII string to lower-case without modifying the input.
13 func ToLower(s string) string {
14 n := len(s)
15 if n < swarMinLen {
16 table := caseconv.ToLowerTable
17 for i := 0; i < n; i++ {
18 c := s[i]
19 low := table[c]
20 if low != c {
21 res := make([]byte, n)
22 copy(res, s[:i])
23 res[i] = low
24 for i++; i < n; i++ {
25 res[i] = table[s[i]]
26 }
27 return unsafeconv.UnsafeString(res)
28 }
29 }
30 return s
31 }
32
33 src := unsafeconv.UnsafeBytes(s)
34 i := caseconv.FirstUpperIndex(src)
35 if i < 0 {
36 return s
37 }
38
39 res := make([]byte, n)
40 // Copy the unchanged prefix up to the word containing the first
41 // uppercase byte, then convert the rest word-at-a-time.
42 from := i &^ (caseconv.WordLen - 1)
43 copy(res, src[:from])
44 caseconv.ToLowerCopy(res, src, from)
45 return unsafeconv.UnsafeString(res)
46 }
47
48 // ToUpper converts an ASCII string to upper-case without modifying the input.
49 func ToUpper(s string) string {
50 n := len(s)
51 if n < swarMinLen {
52 table := caseconv.ToUpperTable
53 for i := 0; i < n; i++ {
54 c := s[i]
55 up := table[c]
56 if up != c {
57 res := make([]byte, n)
58 copy(res, s[:i])
59 res[i] = up
60 for i++; i < n; i++ {
61 res[i] = table[s[i]]
62 }
63 return unsafeconv.UnsafeString(res)
64 }
65 }
66 return s
67 }
68
69 src := unsafeconv.UnsafeBytes(s)
70 i := caseconv.FirstLowerIndex(src)
71 if i < 0 {
72 return s
73 }
74
75 res := make([]byte, n)
76 from := i &^ (caseconv.WordLen - 1)
77 copy(res, src[:from])
78 caseconv.ToUpperCopy(res, src, from)
79 return unsafeconv.UnsafeString(res)
80 }
81
82 // UnsafeToLower converts an ASCII string to lower-case by mutating its backing bytes in-place.
83 // This function is unsafe: it breaks string immutability and must only be used when the
84 // string is known to reference mutable memory.
85 func UnsafeToLower(s string) string {
86 b := unsafeconv.UnsafeBytes(s)
87 if len(b) < swarMinLen {
88 table := caseconv.ToLowerTable
89 for i := range b {
90 b[i] = table[b[i]]
91 }
92 return s
93 }
94 caseconv.ToLowerInPlace(b)
95 return s
96 }
97
98 // UnsafeToUpper converts an ASCII string to upper-case by mutating its backing bytes in-place.
99 // This function is unsafe: it breaks string immutability and must only be used when the
100 // string is known to reference mutable memory.
101 func UnsafeToUpper(s string) string {
102 b := unsafeconv.UnsafeBytes(s)
103 if len(b) < swarMinLen {
104 table := caseconv.ToUpperTable
105 for i := range b {
106 b[i] = table[b[i]]
107 }
108 return s
109 }
110 caseconv.ToUpperInPlace(b)
111 return s
112 }