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(
65 pattern,
66 func() (*regexp.Regexp, error) {
67 return regexp.Compile(pattern)
68 },
69 )
70 }
71
72 // HasAnyPrefix checks if the string s has any of the prefixes given.
73 func HasAnyPrefix(s string, prefixes ...string) bool {
74 for _, p := range prefixes {
75 if strings.HasPrefix(s, p) {
76 return true
77 }
78 }
79 return false
80 }
81
82 func HasUppercase(s string) bool {
83 for _, r := range s {
84 if 'A' <= r && r <= 'Z' {
85 return true
86 }
87 }
88 return false
89 }
90
91 // InSlice checks if a string is an element of a slice of strings
92 // and returns a boolean value.
93 func InSlice(arr []string, el string) bool {
94 return slices.Contains(arr, el)
95 }
96
97 // InSlicEqualFold checks if a string is an element of a slice of strings
98 // and returns a boolean value.
99 // It uses strings.EqualFold to compare.
100 func InSlicEqualFold(arr []string, el string) bool {
101 for _, v := range arr {
102 if strings.EqualFold(v, el) {
103 return true
104 }
105 }
106 return false
107 }
108
109 // ToString converts the given value to a string.
110 // Note that this is a more strict version compared to cast.ToString,
111 // as it will not try to convert numeric values to strings,
112 // but only accept strings or fmt.Stringer.
113 func ToString(v any) (string, bool) {
114 switch vv := v.(type) {
115 case string:
116 return vv, true
117 case fmt.Stringer:
118 return vv.String(), true
119 }
120 return "", false
121 }
122
123 // UniqueStrings returns a new slice with any duplicates removed.
124 func UniqueStrings(s []string) []string {
125 unique := make([]string, 0, len(s))
126 for i, val := range s {
127 var seen bool
128 for j := range i {
129 if s[j] == val {
130 seen = true
131 break
132 }
133 }
134 if !seen {
135 unique = append(unique, val)
136 }
137 }
138 return unique
139 }
140
141 // UniqueStringsReuse returns a slice with any duplicates removed.
142 // It will modify the input slice.
143 func UniqueStringsReuse(s []string) []string {
144 result := s[:0]
145 for i, val := range s {
146 var seen bool
147
148 for j := range i {
149 if s[j] == val {
150 seen = true
151 break
152 }
153 }
154
155 if !seen {
156 result = append(result, val)
157 }
158 }
159 return result
160 }
161
162 // UniqueStringsSorted returns a sorted slice with any duplicates removed.
163 // It will modify the input slice.
164 func UniqueStringsSorted(s []string) []string {
165 if len(s) == 0 {
166 return nil
167 }
168 ss := sort.StringSlice(s)
169 ss.Sort()
170 i := 0
171 for j := 1; j < len(s); j++ {
172 if !ss.Less(i, j) {
173 continue
174 }
175 i++
176 s[i] = s[j]
177 }
178
179 return s[:i+1]
180 }
181
182 // Matcher is an interface for matching strings.
183 type Matcher interface {
184 Match(s string) bool
185 }