Debian Codegraph @

common/hstrings/strings.go

raw
1 // Copyright 2024 The Hugo Authors. All rights reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package hstrings
15
16 import (
17 "fmt"
18 "regexp"
19 "slices"
20 "sort"
21 "strings"
22
23 "github.com/bep/helpers/maphelpers"
24 "github.com/gohugoio/hugo/compare"
25 )
26
27 var _ compare.Eqer = StringEqualFold("")
28
29 // StringEqualFold is a string that implements the compare.Eqer interface and considers
30 // two strings equal if they are equal when folded to lower case.
31 // The compare.Eqer interface is used in Hugo to compare values in templates (e.g. using the eq template function).
32 type StringEqualFold string
33
34 func (s StringEqualFold) EqualFold(s2 string) bool {
35 return strings.EqualFold(string(s), s2)
36 }
37
38 func (s StringEqualFold) String() string {
39 return string(s)
40 }
41
42 func (s StringEqualFold) Eq(s2 any) bool {
43 switch ss := s2.(type) {
44 case string:
45 return s.EqualFold(ss)
46 case fmt.Stringer:
47 return s.EqualFold(ss.String())
48 }
49
50 return false
51 }
52
53 // EqualAny returns whether a string is equal to any of the given strings.
54 func EqualAny(a string, b ...string) bool {
55 return slices.Contains(b, a)
56 }
57
58 var reCache = *maphelpers.NewConcurrentMap[string, *regexp.Regexp]()
59
60 // GetOrCompileRegexp retrieves a regexp object from the cache based upon the pattern.
61 // If the pattern is not found in the cache, the pattern is compiled and added to
62 // the cache.
63 func GetOrCompileRegexp(pattern string) (re *regexp.Regexp, err error) {
64 return reCache.GetOrCreate(pattern,
65 func() (*regexp.Regexp, error) {
66 return regexp.Compile(pattern)
67 },
68 )
69 }
70
71 // HasAnyPrefix checks if the string s has any of the prefixes given.
72 func HasAnyPrefix(s string, prefixes ...string) bool {
73 for _, p := range prefixes {
74 if strings.HasPrefix(s, p) {
75 return true
76 }
77 }
78 return false
79 }
80
81 func HasUppercase(s string) bool {
82 for _, r := range s {
83 if 'A' <= r && r <= 'Z' {
84 return true
85 }
86 }
87 return false
88 }
89
90 // InSlice checks if a string is an element of a slice of strings
91 // and returns a boolean value.
92 func InSlice(arr []string, el string) bool {
93 return slices.Contains(arr, el)
94 }
95
96 // InSlicEqualFold checks if a string is an element of a slice of strings
97 // and returns a boolean value.
98 // It uses strings.EqualFold to compare.
99 func InSlicEqualFold(arr []string, el string) bool {
100 for _, v := range arr {
101 if strings.EqualFold(v, el) {
102 return true
103 }
104 }
105 return false
106 }
107
108 // ToString converts the given value to a string.
109 // Note that this is a more strict version compared to cast.ToString,
110 // as it will not try to convert numeric values to strings,
111 // but only accept strings or fmt.Stringer.
112 func ToString(v any) (string, bool) {
113 switch vv := v.(type) {
114 case string:
115 return vv, true
116 case fmt.Stringer:
117 return vv.String(), true
118 }
119 return "", false
120 }
121
122 // UniqueStrings returns a new slice with any duplicates removed.
123 func UniqueStrings(s []string) []string {
124 unique := make([]string, 0, len(s))
125 for i, val := range s {
126 var seen bool
127 for j := range i {
128 if s[j] == val {
129 seen = true
130 break
131 }
132 }
133 if !seen {
134 unique = append(unique, val)
135 }
136 }
137 return unique
138 }
139
140 // UniqueStringsReuse returns a slice with any duplicates removed.
141 // It will modify the input slice.
142 func UniqueStringsReuse(s []string) []string {
143 result := s[:0]
144 for i, val := range s {
145 var seen bool
146
147 for j := range i {
148 if s[j] == val {
149 seen = true
150 break
151 }
152 }
153
154 if !seen {
155 result = append(result, val)
156 }
157 }
158 return result
159 }
160
161 // UniqueStringsSorted returns a sorted slice with any duplicates removed.
162 // It will modify the input slice.
163 func UniqueStringsSorted(s []string) []string {
164 if len(s) == 0 {
165 return nil
166 }
167 ss := sort.StringSlice(s)
168 ss.Sort()
169 i := 0
170 for j := 1; j < len(s); j++ {
171 if !ss.Less(i, j) {
172 continue
173 }
174 i++
175 s[i] = s[j]
176 }
177
178 return s[:i+1]
179 }