blob: de4ca4df1094b54241a6bc1cddb02e75314a0b64 [file] [log] [blame]
Colin Crossc0b06f12015-04-08 13:03:43 -07001// Copyright 2015 Google Inc. 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//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
Colin Cross635c3b02016-05-18 15:37:25 -070015package android
Colin Crossc0b06f12015-04-08 13:03:43 -070016
Dan Willemsenb1957a52016-06-23 23:44:54 -070017import (
Cole Faustefc70122024-01-30 14:42:12 -080018 "cmp"
Colin Cross3020fee2019-03-19 15:05:17 -070019 "fmt"
Ivan Lozano022a73b2019-09-09 20:29:31 -070020 "path/filepath"
Inseob Kim1a365c62019-06-08 15:47:51 +090021 "reflect"
Colin Cross3020fee2019-03-19 15:05:17 -070022 "regexp"
Dan Willemsenb1957a52016-06-23 23:44:54 -070023 "runtime"
24 "sort"
25 "strings"
Colin Cross31a67452023-11-02 16:57:08 -070026 "sync"
Dan Willemsenb1957a52016-06-23 23:44:54 -070027)
Colin Cross1f8c52b2015-06-16 16:38:17 -070028
Colin Cross454c0872019-02-15 23:03:34 -080029// CopyOf returns a new slice that has the same contents as s.
Colin Cross48016d52023-06-27 09:45:26 -070030func CopyOf[T any](s []T) []T {
Spandan Dascc4da762023-04-27 19:34:08 +000031 // If the input is nil, return nil and not an empty list
32 if s == nil {
33 return s
34 }
Colin Cross48016d52023-06-27 09:45:26 -070035 return append([]T{}, s...)
Colin Cross454c0872019-02-15 23:03:34 -080036}
37
Wen-yi Chu41326c12023-09-22 03:58:59 +000038// Concat returns a new slice concatenated from the two input slices. It does not change the input
Jiakai Zhang8fe3a412023-02-23 17:37:16 +000039// slices.
Wen-yi Chu41326c12023-09-22 03:58:59 +000040func Concat[T any](s1, s2 []T) []T {
41 res := make([]T, 0, len(s1)+len(s2))
42 res = append(res, s1...)
43 res = append(res, s2...)
Jiakai Zhang8fe3a412023-02-23 17:37:16 +000044 return res
45}
46
Joe Onorato2f99c472023-06-21 18:10:28 -070047// JoinPathsWithPrefix converts the paths to strings, prefixes them
48// with prefix and then joins them separated by " ".
49func JoinPathsWithPrefix(paths []Path, prefix string) string {
50 strs := make([]string, len(paths))
51 for i := range paths {
52 strs[i] = paths[i].String()
53 }
54 return JoinWithPrefixAndSeparator(strs, prefix, " ")
55}
56
Sasha Smundak1e533922020-11-19 16:48:18 -080057// JoinWithPrefix prepends the prefix to each string in the list and
58// returns them joined together with " " as separator.
Colin Crossc0b06f12015-04-08 13:03:43 -070059func JoinWithPrefix(strs []string, prefix string) string {
Yu Liu8d82ac52022-05-17 15:13:28 -070060 return JoinWithPrefixAndSeparator(strs, prefix, " ")
61}
62
63// JoinWithPrefixAndSeparator prepends the prefix to each string in the list and
64// returns them joined together with the given separator.
65func JoinWithPrefixAndSeparator(strs []string, prefix string, sep string) string {
Jooyung Hanb0864e02023-11-07 13:08:53 +090066 return JoinWithPrefixSuffixAndSeparator(strs, prefix, "", sep)
67}
68
69// JoinWithSuffixAndSeparator appends the suffix to each string in the list and
70// returns them joined together with the given separator.
71func JoinWithSuffixAndSeparator(strs []string, suffix string, sep string) string {
72 return JoinWithPrefixSuffixAndSeparator(strs, "", suffix, sep)
73}
74
75// JoinWithPrefixSuffixAndSeparator appends the prefix/suffix to each string in the list and
76// returns them joined together with the given separator.
77func JoinWithPrefixSuffixAndSeparator(strs []string, prefix, suffix, sep string) string {
Colin Crossc0b06f12015-04-08 13:03:43 -070078 if len(strs) == 0 {
79 return ""
80 }
81
Jooyung Hanb0864e02023-11-07 13:08:53 +090082 // Pre-calculate the length of the result
83 length := 0
84 for _, s := range strs {
85 length += len(s)
86 }
87 length += (len(prefix)+len(suffix))*len(strs) + len(sep)*(len(strs)-1)
88
Sasha Smundak1e533922020-11-19 16:48:18 -080089 var buf strings.Builder
Jooyung Hanb0864e02023-11-07 13:08:53 +090090 buf.Grow(length)
Sasha Smundak1e533922020-11-19 16:48:18 -080091 buf.WriteString(prefix)
92 buf.WriteString(strs[0])
Jooyung Hanb0864e02023-11-07 13:08:53 +090093 buf.WriteString(suffix)
Sasha Smundak1e533922020-11-19 16:48:18 -080094 for i := 1; i < len(strs); i++ {
Yu Liu8d82ac52022-05-17 15:13:28 -070095 buf.WriteString(sep)
Sasha Smundak1e533922020-11-19 16:48:18 -080096 buf.WriteString(prefix)
97 buf.WriteString(strs[i])
Jooyung Hanb0864e02023-11-07 13:08:53 +090098 buf.WriteString(suffix)
Colin Crossc0b06f12015-04-08 13:03:43 -070099 }
Sasha Smundak1e533922020-11-19 16:48:18 -0800100 return buf.String()
Colin Crossc0b06f12015-04-08 13:03:43 -0700101}
Colin Cross9b6826f2015-04-10 15:47:33 -0700102
Cole Faust18994c72023-02-28 16:02:16 -0800103// SortedStringKeys returns the keys of the given map in the ascending order.
104//
105// Deprecated: Use SortedKeys instead.
Cole Faust195c7812023-03-01 14:21:30 -0800106func SortedStringKeys[V any](m map[string]V) []string {
107 return SortedKeys(m)
Colin Cross1f8c52b2015-06-16 16:38:17 -0700108}
Dan Willemsenb1957a52016-06-23 23:44:54 -0700109
Cole Faust18994c72023-02-28 16:02:16 -0800110// SortedKeys returns the keys of the given map in the ascending order.
Cole Faustefc70122024-01-30 14:42:12 -0800111func SortedKeys[T cmp.Ordered, V any](m map[T]V) []T {
Cole Faust18994c72023-02-28 16:02:16 -0800112 if len(m) == 0 {
113 return nil
114 }
115 ret := make([]T, 0, len(m))
116 for k := range m {
117 ret = append(ret, k)
118 }
119 sort.Slice(ret, func(i, j int) bool {
120 return ret[i] < ret[j]
121 })
122 return ret
123}
124
Colin Cross9eb853b2022-02-17 11:13:37 -0800125// stringValues returns the values of the given string-valued map in randomized map order.
126func stringValues(m interface{}) []string {
127 v := reflect.ValueOf(m)
128 if v.Kind() != reflect.Map {
129 panic(fmt.Sprintf("%#v is not a map", m))
130 }
131 if v.Len() == 0 {
132 return nil
133 }
134 iter := v.MapRange()
135 s := make([]string, 0, v.Len())
136 for iter.Next() {
137 s = append(s, iter.Value().String())
138 }
139 return s
140}
141
142// SortedStringValues returns the values of the given string-valued map in the ascending order.
143func SortedStringValues(m interface{}) []string {
144 s := stringValues(m)
145 sort.Strings(s)
146 return s
147}
148
149// SortedUniqueStringValues returns the values of the given string-valued map in the ascending order
150// with duplicates removed.
151func SortedUniqueStringValues(m interface{}) []string {
152 s := stringValues(m)
153 return SortedUniqueStrings(s)
154}
155
Sasha Smundak1e533922020-11-19 16:48:18 -0800156// IndexList returns the index of the first occurrence of the given string in the list or -1
Sam Delmerico1717b3b2023-07-18 15:07:24 -0400157func IndexList[T comparable](t T, list []T) int {
Dan Willemsenb1957a52016-06-23 23:44:54 -0700158 for i, l := range list {
Sam Delmerico1717b3b2023-07-18 15:07:24 -0400159 if l == t {
Dan Willemsenb1957a52016-06-23 23:44:54 -0700160 return i
161 }
162 }
Dan Willemsenb1957a52016-06-23 23:44:54 -0700163 return -1
164}
165
Sam Delmerico1717b3b2023-07-18 15:07:24 -0400166func InList[T comparable](t T, list []T) bool {
167 return IndexList(t, list) != -1
Dan Willemsenb1957a52016-06-23 23:44:54 -0700168}
169
Sam Delmerico4e115cc2023-01-19 15:36:52 -0500170func setFromList[T comparable](l []T) map[T]bool {
171 m := make(map[T]bool, len(l))
172 for _, t := range l {
173 m[t] = true
174 }
175 return m
176}
177
Sam Delmerico5fb794a2023-01-27 16:01:37 -0500178// ListSetDifference checks if the two lists contain the same elements. It returns
179// a boolean which is true if there is a difference, and then returns lists of elements
180// that are in l1 but not l2, and l2 but not l1.
181func ListSetDifference[T comparable](l1, l2 []T) (bool, []T, []T) {
182 listsDiffer := false
183 diff1 := []T{}
184 diff2 := []T{}
Sam Delmerico4e115cc2023-01-19 15:36:52 -0500185 m1 := setFromList(l1)
186 m2 := setFromList(l2)
Sam Delmerico5fb794a2023-01-27 16:01:37 -0500187 for t := range m1 {
Sam Delmerico4e115cc2023-01-19 15:36:52 -0500188 if _, ok := m2[t]; !ok {
Sam Delmerico5fb794a2023-01-27 16:01:37 -0500189 diff1 = append(diff1, t)
190 listsDiffer = true
Sam Delmerico4e115cc2023-01-19 15:36:52 -0500191 }
192 }
Sam Delmerico5fb794a2023-01-27 16:01:37 -0500193 for t := range m2 {
Sam Delmerico4e115cc2023-01-19 15:36:52 -0500194 if _, ok := m1[t]; !ok {
Sam Delmerico5fb794a2023-01-27 16:01:37 -0500195 diff2 = append(diff2, t)
196 listsDiffer = true
Sam Delmerico4e115cc2023-01-19 15:36:52 -0500197 }
198 }
Sam Delmerico5fb794a2023-01-27 16:01:37 -0500199 return listsDiffer, diff1, diff2
Sam Delmerico4e115cc2023-01-19 15:36:52 -0500200}
201
Jaewoong Jung6431ca72020-01-15 14:15:10 -0800202// Returns true if the given string s is prefixed with any string in the given prefix list.
Jaewoong Jung3aff5782020-02-11 07:54:35 -0800203func HasAnyPrefix(s string, prefixList []string) bool {
Jaewoong Jung6431ca72020-01-15 14:15:10 -0800204 for _, prefix := range prefixList {
205 if strings.HasPrefix(s, prefix) {
206 return true
207 }
208 }
209 return false
210}
211
Chih-Hung Hsieh9f94c362021-02-10 21:56:03 -0800212// Returns true if any string in the given list has the given substring.
213func SubstringInList(list []string, substr string) bool {
214 for _, s := range list {
215 if strings.Contains(s, substr) {
216 return true
217 }
218 }
219 return false
220}
221
Jaewoong Jung6431ca72020-01-15 14:15:10 -0800222// Returns true if any string in the given list has the given prefix.
Jaewoong Jung3aff5782020-02-11 07:54:35 -0800223func PrefixInList(list []string, prefix string) bool {
Jaewoong Jung6431ca72020-01-15 14:15:10 -0800224 for _, s := range list {
Ivan Lozano5f595532017-07-13 14:46:05 -0700225 if strings.HasPrefix(s, prefix) {
226 return true
227 }
228 }
229 return false
230}
231
Ivan Lozanoa0cd8f92020-04-09 09:56:02 -0400232// Returns true if any string in the given list has the given suffix.
233func SuffixInList(list []string, suffix string) bool {
234 for _, s := range list {
235 if strings.HasSuffix(s, suffix) {
236 return true
237 }
238 }
239 return false
240}
241
Jooyung Han12df5fb2019-07-11 16:18:47 +0900242// IndexListPred returns the index of the element which in the given `list` satisfying the predicate, or -1 if there is no such element.
243func IndexListPred(pred func(s string) bool, list []string) int {
244 for i, l := range list {
245 if pred(l) {
246 return i
247 }
248 }
249
250 return -1
251}
252
Sasha Smundak1e533922020-11-19 16:48:18 -0800253// FilterList divides the string list into two lists: one with the strings belonging
254// to the given filter list, and the other with the remaining ones
Colin Crossb4330e22017-12-22 15:47:09 -0800255func FilterList(list []string, filter []string) (remainder []string, filtered []string) {
Sasha Smundak1e533922020-11-19 16:48:18 -0800256 // InList is O(n). May be worth using more efficient lookup for longer lists.
Colin Crossb4330e22017-12-22 15:47:09 -0800257 for _, l := range list {
258 if InList(l, filter) {
259 filtered = append(filtered, l)
260 } else {
261 remainder = append(remainder, l)
262 }
263 }
264
265 return
266}
267
Martin Stjernholm1461c4d2021-03-27 19:04:05 +0000268// FilterListPred returns the elements of the given list for which the predicate
269// returns true. Order is kept.
270func FilterListPred(list []string, pred func(s string) bool) (filtered []string) {
271 for _, l := range list {
272 if pred(l) {
273 filtered = append(filtered, l)
274 }
275 }
276 return
277}
278
Sasha Smundak1e533922020-11-19 16:48:18 -0800279// RemoveListFromList removes the strings belonging to the filter list from the
280// given list and returns the result
Colin Crossb4330e22017-12-22 15:47:09 -0800281func RemoveListFromList(list []string, filter_out []string) (result []string) {
282 result = make([]string, 0, len(list))
283 for _, l := range list {
284 if !InList(l, filter_out) {
285 result = append(result, l)
286 }
287 }
288 return
289}
290
Sasha Smundak1e533922020-11-19 16:48:18 -0800291// RemoveFromList removes given string from the string list.
Colin Crossb4330e22017-12-22 15:47:09 -0800292func RemoveFromList(s string, list []string) (bool, []string) {
Sasha Smundak1e533922020-11-19 16:48:18 -0800293 result := make([]string, 0, len(list))
294 var removed bool
295 for _, item := range list {
296 if item != s {
297 result = append(result, item)
298 } else {
299 removed = true
Logan Chien7922ab82018-03-06 18:29:27 +0800300 }
301 }
Sasha Smundak1e533922020-11-19 16:48:18 -0800302 return removed, result
Colin Crossb4330e22017-12-22 15:47:09 -0800303}
304
Ivan Lozano0a468a42024-05-13 21:03:34 -0400305// FirstUniqueFunc returns all unique elements of a slice, keeping the first copy of
306// each. It does not modify the input slice. The eq function should return true
307// if two elements can be considered equal.
308func FirstUniqueFunc[SortableList ~[]Sortable, Sortable any](list SortableList, eq func(a, b Sortable) bool) SortableList {
309 k := 0
310outer:
311 for i := 0; i < len(list); i++ {
312 for j := 0; j < k; j++ {
313 if eq(list[i], list[j]) {
314 continue outer
315 }
316 }
317 list[k] = list[i]
318 k++
319 }
320 return list[:k]
321}
322
Colin Crossb6715442017-10-24 11:13:31 -0700323// FirstUniqueStrings returns all unique elements of a slice of strings, keeping the first copy of
Colin Cross48016d52023-06-27 09:45:26 -0700324// each. It does not modify the input slice.
Colin Crossb6715442017-10-24 11:13:31 -0700325func FirstUniqueStrings(list []string) []string {
Colin Crossc85750b2022-04-21 12:50:51 -0700326 return firstUnique(list)
Colin Cross27027c72020-02-28 15:34:17 -0800327}
328
Colin Crossc85750b2022-04-21 12:50:51 -0700329// firstUnique returns all unique elements of a slice, keeping the first copy of each. It
Colin Cross48016d52023-06-27 09:45:26 -0700330// does not modify the input slice.
Colin Crossc85750b2022-04-21 12:50:51 -0700331func firstUnique[T comparable](slice []T) []T {
Colin Cross48016d52023-06-27 09:45:26 -0700332 // Do not modify the input in-place, operate on a copy instead.
333 slice = CopyOf(slice)
334 return firstUniqueInPlace(slice)
335}
336
337// firstUniqueInPlace returns all unique elements of a slice, keeping the first copy of
338// each. It modifies the slice contents in place, and returns a subslice of the original
339// slice.
340func firstUniqueInPlace[T comparable](slice []T) []T {
341 // 128 was chosen based on BenchmarkFirstUniqueStrings results.
342 if len(slice) > 128 {
Colin Crossc85750b2022-04-21 12:50:51 -0700343 return firstUniqueMap(slice)
344 }
345 return firstUniqueList(slice)
346}
347
348// firstUniqueList is an implementation of firstUnique using an O(N^2) list comparison to look for
349// duplicates.
350func firstUniqueList[T any](in []T) []T {
351 writeIndex := 0
Colin Crossb6715442017-10-24 11:13:31 -0700352outer:
Colin Crossc85750b2022-04-21 12:50:51 -0700353 for readIndex := 0; readIndex < len(in); readIndex++ {
354 for compareIndex := 0; compareIndex < writeIndex; compareIndex++ {
355 if interface{}(in[readIndex]) == interface{}(in[compareIndex]) {
356 // The value at readIndex already exists somewhere in the output region
357 // of the slice before writeIndex, skip it.
Colin Crossb6715442017-10-24 11:13:31 -0700358 continue outer
359 }
360 }
Colin Crossc85750b2022-04-21 12:50:51 -0700361 if readIndex != writeIndex {
362 in[writeIndex] = in[readIndex]
363 }
364 writeIndex++
Colin Crossb6715442017-10-24 11:13:31 -0700365 }
Colin Crossc85750b2022-04-21 12:50:51 -0700366 return in[0:writeIndex]
Colin Crossb6715442017-10-24 11:13:31 -0700367}
368
Colin Crossc85750b2022-04-21 12:50:51 -0700369// firstUniqueMap is an implementation of firstUnique using an O(N) hash set lookup to look for
370// duplicates.
371func firstUniqueMap[T comparable](in []T) []T {
372 writeIndex := 0
373 seen := make(map[T]bool, len(in))
374 for readIndex := 0; readIndex < len(in); readIndex++ {
375 if _, exists := seen[in[readIndex]]; exists {
Colin Cross27027c72020-02-28 15:34:17 -0800376 continue
377 }
Colin Crossc85750b2022-04-21 12:50:51 -0700378 seen[in[readIndex]] = true
379 if readIndex != writeIndex {
380 in[writeIndex] = in[readIndex]
381 }
382 writeIndex++
Colin Cross27027c72020-02-28 15:34:17 -0800383 }
Colin Crossc85750b2022-04-21 12:50:51 -0700384 return in[0:writeIndex]
385}
386
Colin Crossb5e3f7d2023-07-06 15:37:53 -0700387// ReverseSliceInPlace reverses the elements of a slice in place and returns it.
388func ReverseSliceInPlace[T any](in []T) []T {
Colin Crossc85750b2022-04-21 12:50:51 -0700389 for i, j := 0, len(in)-1; i < j; i, j = i+1, j-1 {
390 in[i], in[j] = in[j], in[i]
391 }
Colin Crossb5e3f7d2023-07-06 15:37:53 -0700392 return in
Colin Crossc85750b2022-04-21 12:50:51 -0700393}
394
Colin Crossb5e3f7d2023-07-06 15:37:53 -0700395// ReverseSlice returns a copy of a slice in reverse order.
396func ReverseSlice[T any](in []T) []T {
397 if in == nil {
398 return in
399 }
Colin Crossc85750b2022-04-21 12:50:51 -0700400 out := make([]T, len(in))
401 for i := 0; i < len(in); i++ {
402 out[i] = in[len(in)-1-i]
403 }
404 return out
Colin Cross27027c72020-02-28 15:34:17 -0800405}
406
Colin Crossb6715442017-10-24 11:13:31 -0700407// LastUniqueStrings returns all unique elements of a slice of strings, keeping the last copy of
408// each. It modifies the slice contents in place, and returns a subslice of the original slice.
409func LastUniqueStrings(list []string) []string {
410 totalSkip := 0
411 for i := len(list) - 1; i >= totalSkip; i-- {
412 skip := 0
413 for j := i - 1; j >= totalSkip; j-- {
414 if list[i] == list[j] {
415 skip++
416 } else {
417 list[j+skip] = list[j]
418 }
419 }
420 totalSkip += skip
421 }
422 return list[totalSkip:]
423}
424
Jooyung Hane1633032019-08-01 17:41:43 +0900425// SortedUniqueStrings returns what the name says
426func SortedUniqueStrings(list []string) []string {
Spandan Das8a8714c2023-04-25 18:03:54 +0000427 // FirstUniqueStrings creates a copy of `list`, so the input remains untouched.
Jooyung Hane1633032019-08-01 17:41:43 +0900428 unique := FirstUniqueStrings(list)
429 sort.Strings(unique)
430 return unique
431}
432
Dan Willemsenb1957a52016-06-23 23:44:54 -0700433// checkCalledFromInit panics if a Go package's init function is not on the
434// call stack.
435func checkCalledFromInit() {
436 for skip := 3; ; skip++ {
437 _, funcName, ok := callerName(skip)
438 if !ok {
439 panic("not called from an init func")
440 }
441
Colin Cross3020fee2019-03-19 15:05:17 -0700442 if funcName == "init" || strings.HasPrefix(funcName, "init·") ||
443 strings.HasPrefix(funcName, "init.") {
Dan Willemsenb1957a52016-06-23 23:44:54 -0700444 return
445 }
446 }
447}
448
Colin Cross3020fee2019-03-19 15:05:17 -0700449// A regex to find a package path within a function name. It finds the shortest string that is
450// followed by '.' and doesn't have any '/'s left.
451var pkgPathRe = regexp.MustCompile(`^(.*?)\.([^/]+)$`)
452
Dan Willemsenb1957a52016-06-23 23:44:54 -0700453// callerName returns the package path and function name of the calling
454// function. The skip argument has the same meaning as the skip argument of
455// runtime.Callers.
456func callerName(skip int) (pkgPath, funcName string, ok bool) {
457 var pc [1]uintptr
458 n := runtime.Callers(skip+1, pc[:])
459 if n != 1 {
460 return "", "", false
461 }
462
Colin Cross3020fee2019-03-19 15:05:17 -0700463 f := runtime.FuncForPC(pc[0]).Name()
464 s := pkgPathRe.FindStringSubmatch(f)
465 if len(s) < 3 {
466 panic(fmt.Errorf("failed to extract package path and function name from %q", f))
Dan Willemsenb1957a52016-06-23 23:44:54 -0700467 }
468
Colin Cross3020fee2019-03-19 15:05:17 -0700469 return s[1], s[2], true
Dan Willemsenb1957a52016-06-23 23:44:54 -0700470}
Sundong Ahn0926fae2017-10-17 16:34:51 +0900471
Sasha Smundak1e533922020-11-19 16:48:18 -0800472// GetNumericSdkVersion removes the first occurrence of system_ in a string,
473// which is assumed to be something like "system_1.2.3"
Sundong Ahn0926fae2017-10-17 16:34:51 +0900474func GetNumericSdkVersion(v string) string {
Sasha Smundak1e533922020-11-19 16:48:18 -0800475 return strings.Replace(v, "system_", "", 1)
Sundong Ahn0926fae2017-10-17 16:34:51 +0900476}
Jiyong Park7f67f482019-01-05 12:57:48 +0900477
478// copied from build/kati/strutil.go
479func substPattern(pat, repl, str string) string {
480 ps := strings.SplitN(pat, "%", 2)
481 if len(ps) != 2 {
482 if str == pat {
483 return repl
484 }
485 return str
486 }
487 in := str
Sasha Smundak1e533922020-11-19 16:48:18 -0800488 trimmed := str
Jiyong Park7f67f482019-01-05 12:57:48 +0900489 if ps[0] != "" {
Sasha Smundak1e533922020-11-19 16:48:18 -0800490 trimmed = strings.TrimPrefix(in, ps[0])
491 if trimmed == in {
Jiyong Park7f67f482019-01-05 12:57:48 +0900492 return str
493 }
494 }
Sasha Smundak1e533922020-11-19 16:48:18 -0800495 in = trimmed
Jiyong Park7f67f482019-01-05 12:57:48 +0900496 if ps[1] != "" {
Sasha Smundak1e533922020-11-19 16:48:18 -0800497 trimmed = strings.TrimSuffix(in, ps[1])
498 if trimmed == in {
Jiyong Park7f67f482019-01-05 12:57:48 +0900499 return str
500 }
501 }
502
503 rs := strings.SplitN(repl, "%", 2)
504 if len(rs) != 2 {
505 return repl
506 }
Sasha Smundak1e533922020-11-19 16:48:18 -0800507 return rs[0] + trimmed + rs[1]
Jiyong Park7f67f482019-01-05 12:57:48 +0900508}
509
510// copied from build/kati/strutil.go
511func matchPattern(pat, str string) bool {
512 i := strings.IndexByte(pat, '%')
513 if i < 0 {
514 return pat == str
515 }
516 return strings.HasPrefix(str, pat[:i]) && strings.HasSuffix(str, pat[i+1:])
517}
Ivan Lozano022a73b2019-09-09 20:29:31 -0700518
519var shlibVersionPattern = regexp.MustCompile("(?:\\.\\d+(?:svn)?)+")
520
521// splitFileExt splits a file name into root, suffix and ext. root stands for the file name without
522// the file extension and the version number (e.g. "libexample"). suffix stands for the
523// concatenation of the file extension and the version number (e.g. ".so.1.0"). ext stands for the
524// file extension after the version numbers are trimmed (e.g. ".so").
525func SplitFileExt(name string) (string, string, string) {
526 // Extract and trim the shared lib version number if the file name ends with dot digits.
527 suffix := ""
528 matches := shlibVersionPattern.FindAllStringIndex(name, -1)
529 if len(matches) > 0 {
530 lastMatch := matches[len(matches)-1]
531 if lastMatch[1] == len(name) {
532 suffix = name[lastMatch[0]:lastMatch[1]]
533 name = name[0:lastMatch[0]]
534 }
535 }
536
537 // Extract the file name root and the file extension.
538 ext := filepath.Ext(name)
539 root := strings.TrimSuffix(name, ext)
540 suffix = ext + suffix
541
542 return root, suffix, ext
543}
Colin Cross0a2f7192019-09-23 14:33:09 -0700544
Jihoon Kangcd5bfe22024-04-12 00:19:09 +0000545func shard[T ~[]E, E any](toShard T, shardSize int) []T {
546 if len(toShard) == 0 {
Colin Cross0a2f7192019-09-23 14:33:09 -0700547 return nil
548 }
Jihoon Kangcd5bfe22024-04-12 00:19:09 +0000549
550 ret := make([]T, 0, (len(toShard)+shardSize-1)/shardSize)
551 for len(toShard) > shardSize {
552 ret = append(ret, toShard[0:shardSize])
553 toShard = toShard[shardSize:]
Colin Cross0a2f7192019-09-23 14:33:09 -0700554 }
Jihoon Kangcd5bfe22024-04-12 00:19:09 +0000555 if len(toShard) > 0 {
556 ret = append(ret, toShard)
Colin Cross0a2f7192019-09-23 14:33:09 -0700557 }
558 return ret
559}
560
Jihoon Kangcd5bfe22024-04-12 00:19:09 +0000561// ShardPaths takes a Paths, and returns a slice of Paths where each one has at most shardSize paths.
562func ShardPaths(paths Paths, shardSize int) []Paths {
563 return shard(paths, shardSize)
564}
565
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +0100566// ShardString takes a string and returns a slice of strings where the length of each one is
567// at most shardSize.
568func ShardString(s string, shardSize int) []string {
569 if len(s) == 0 {
570 return nil
571 }
572 ret := make([]string, 0, (len(s)+shardSize-1)/shardSize)
573 for len(s) > shardSize {
574 ret = append(ret, s[0:shardSize])
575 s = s[shardSize:]
576 }
577 if len(s) > 0 {
578 ret = append(ret, s)
579 }
580 return ret
581}
582
Colin Cross0a2f7192019-09-23 14:33:09 -0700583// ShardStrings takes a slice of strings, and returns a slice of slices of strings where each one has at most shardSize
584// elements.
585func ShardStrings(s []string, shardSize int) [][]string {
Jihoon Kangcd5bfe22024-04-12 00:19:09 +0000586 return shard(s, shardSize)
Colin Cross0a2f7192019-09-23 14:33:09 -0700587}
Chih-Hung Hsieha5f22ed2019-10-24 20:47:54 -0700588
Sasha Smundak1e533922020-11-19 16:48:18 -0800589// CheckDuplicate checks if there are duplicates in given string list.
590// If there are, it returns first such duplicate and true.
Chih-Hung Hsieha5f22ed2019-10-24 20:47:54 -0700591func CheckDuplicate(values []string) (duplicate string, found bool) {
592 seen := make(map[string]string)
593 for _, v := range values {
594 if duplicate, found = seen[v]; found {
Sasha Smundak1e533922020-11-19 16:48:18 -0800595 return duplicate, true
Chih-Hung Hsieha5f22ed2019-10-24 20:47:54 -0700596 }
597 seen[v] = v
598 }
Sasha Smundak1e533922020-11-19 16:48:18 -0800599 return "", false
Chih-Hung Hsieha5f22ed2019-10-24 20:47:54 -0700600}
Colin Crossb63d7b32023-12-07 16:54:51 -0800601
602func AddToStringSet(set map[string]bool, items []string) {
603 for _, item := range items {
604 set[item] = true
605 }
606}
Colin Cross31a67452023-11-02 16:57:08 -0700607
608// SyncMap is a wrapper around sync.Map that provides type safety via generics.
609type SyncMap[K comparable, V any] struct {
610 sync.Map
611}
612
613// Load returns the value stored in the map for a key, or the zero value if no
614// value is present.
615// The ok result indicates whether value was found in the map.
616func (m *SyncMap[K, V]) Load(key K) (value V, ok bool) {
617 v, ok := m.Map.Load(key)
618 if !ok {
619 return *new(V), false
620 }
621 return v.(V), true
622}
623
624// Store sets the value for a key.
625func (m *SyncMap[K, V]) Store(key K, value V) {
626 m.Map.Store(key, value)
627}
628
629// LoadOrStore returns the existing value for the key if present.
630// Otherwise, it stores and returns the given value.
631// The loaded result is true if the value was loaded, false if stored.
632func (m *SyncMap[K, V]) LoadOrStore(key K, value V) (actual V, loaded bool) {
633 v, loaded := m.Map.LoadOrStore(key, value)
634 return v.(V), loaded
635}