blob: b9ab77aec8a2495e13843442f034ffe5d767f38d [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"
Yu Liu1b2ddc82024-05-15 19:28:56 +000027
28 "github.com/google/blueprint/proptools"
Dan Willemsenb1957a52016-06-23 23:44:54 -070029)
Colin Cross1f8c52b2015-06-16 16:38:17 -070030
Colin Cross454c0872019-02-15 23:03:34 -080031// CopyOf returns a new slice that has the same contents as s.
Colin Cross48016d52023-06-27 09:45:26 -070032func CopyOf[T any](s []T) []T {
Spandan Dascc4da762023-04-27 19:34:08 +000033 // If the input is nil, return nil and not an empty list
34 if s == nil {
35 return s
36 }
Colin Cross48016d52023-06-27 09:45:26 -070037 return append([]T{}, s...)
Colin Cross454c0872019-02-15 23:03:34 -080038}
39
Wen-yi Chu41326c12023-09-22 03:58:59 +000040// Concat returns a new slice concatenated from the two input slices. It does not change the input
Jiakai Zhang8fe3a412023-02-23 17:37:16 +000041// slices.
Wen-yi Chu41326c12023-09-22 03:58:59 +000042func Concat[T any](s1, s2 []T) []T {
43 res := make([]T, 0, len(s1)+len(s2))
44 res = append(res, s1...)
45 res = append(res, s2...)
Jiakai Zhang8fe3a412023-02-23 17:37:16 +000046 return res
47}
48
Joe Onorato2f99c472023-06-21 18:10:28 -070049// JoinPathsWithPrefix converts the paths to strings, prefixes them
50// with prefix and then joins them separated by " ".
51func JoinPathsWithPrefix(paths []Path, prefix string) string {
52 strs := make([]string, len(paths))
53 for i := range paths {
54 strs[i] = paths[i].String()
55 }
56 return JoinWithPrefixAndSeparator(strs, prefix, " ")
57}
58
Sasha Smundak1e533922020-11-19 16:48:18 -080059// JoinWithPrefix prepends the prefix to each string in the list and
60// returns them joined together with " " as separator.
Colin Crossc0b06f12015-04-08 13:03:43 -070061func JoinWithPrefix(strs []string, prefix string) string {
Yu Liu8d82ac52022-05-17 15:13:28 -070062 return JoinWithPrefixAndSeparator(strs, prefix, " ")
63}
64
65// JoinWithPrefixAndSeparator prepends the prefix to each string in the list and
66// returns them joined together with the given separator.
67func JoinWithPrefixAndSeparator(strs []string, prefix string, sep string) string {
Jooyung Hanb0864e02023-11-07 13:08:53 +090068 return JoinWithPrefixSuffixAndSeparator(strs, prefix, "", sep)
69}
70
71// JoinWithSuffixAndSeparator appends the suffix to each string in the list and
72// returns them joined together with the given separator.
73func JoinWithSuffixAndSeparator(strs []string, suffix string, sep string) string {
74 return JoinWithPrefixSuffixAndSeparator(strs, "", suffix, sep)
75}
76
77// JoinWithPrefixSuffixAndSeparator appends the prefix/suffix to each string in the list and
78// returns them joined together with the given separator.
79func JoinWithPrefixSuffixAndSeparator(strs []string, prefix, suffix, sep string) string {
Colin Crossc0b06f12015-04-08 13:03:43 -070080 if len(strs) == 0 {
81 return ""
82 }
83
Jooyung Hanb0864e02023-11-07 13:08:53 +090084 // Pre-calculate the length of the result
85 length := 0
86 for _, s := range strs {
87 length += len(s)
88 }
89 length += (len(prefix)+len(suffix))*len(strs) + len(sep)*(len(strs)-1)
90
Sasha Smundak1e533922020-11-19 16:48:18 -080091 var buf strings.Builder
Jooyung Hanb0864e02023-11-07 13:08:53 +090092 buf.Grow(length)
Sasha Smundak1e533922020-11-19 16:48:18 -080093 buf.WriteString(prefix)
94 buf.WriteString(strs[0])
Jooyung Hanb0864e02023-11-07 13:08:53 +090095 buf.WriteString(suffix)
Sasha Smundak1e533922020-11-19 16:48:18 -080096 for i := 1; i < len(strs); i++ {
Yu Liu8d82ac52022-05-17 15:13:28 -070097 buf.WriteString(sep)
Sasha Smundak1e533922020-11-19 16:48:18 -080098 buf.WriteString(prefix)
99 buf.WriteString(strs[i])
Jooyung Hanb0864e02023-11-07 13:08:53 +0900100 buf.WriteString(suffix)
Colin Crossc0b06f12015-04-08 13:03:43 -0700101 }
Sasha Smundak1e533922020-11-19 16:48:18 -0800102 return buf.String()
Colin Crossc0b06f12015-04-08 13:03:43 -0700103}
Colin Cross9b6826f2015-04-10 15:47:33 -0700104
Cole Faust18994c72023-02-28 16:02:16 -0800105// SortedStringKeys returns the keys of the given map in the ascending order.
106//
107// Deprecated: Use SortedKeys instead.
Cole Faust195c7812023-03-01 14:21:30 -0800108func SortedStringKeys[V any](m map[string]V) []string {
109 return SortedKeys(m)
Colin Cross1f8c52b2015-06-16 16:38:17 -0700110}
Dan Willemsenb1957a52016-06-23 23:44:54 -0700111
Cole Faust18994c72023-02-28 16:02:16 -0800112// SortedKeys returns the keys of the given map in the ascending order.
Cole Faustefc70122024-01-30 14:42:12 -0800113func SortedKeys[T cmp.Ordered, V any](m map[T]V) []T {
Cole Faust18994c72023-02-28 16:02:16 -0800114 if len(m) == 0 {
115 return nil
116 }
117 ret := make([]T, 0, len(m))
118 for k := range m {
119 ret = append(ret, k)
120 }
121 sort.Slice(ret, func(i, j int) bool {
122 return ret[i] < ret[j]
123 })
124 return ret
125}
126
Colin Cross9eb853b2022-02-17 11:13:37 -0800127// stringValues returns the values of the given string-valued map in randomized map order.
128func stringValues(m interface{}) []string {
129 v := reflect.ValueOf(m)
130 if v.Kind() != reflect.Map {
131 panic(fmt.Sprintf("%#v is not a map", m))
132 }
133 if v.Len() == 0 {
134 return nil
135 }
136 iter := v.MapRange()
137 s := make([]string, 0, v.Len())
138 for iter.Next() {
139 s = append(s, iter.Value().String())
140 }
141 return s
142}
143
144// SortedStringValues returns the values of the given string-valued map in the ascending order.
145func SortedStringValues(m interface{}) []string {
146 s := stringValues(m)
147 sort.Strings(s)
148 return s
149}
150
151// SortedUniqueStringValues returns the values of the given string-valued map in the ascending order
152// with duplicates removed.
153func SortedUniqueStringValues(m interface{}) []string {
154 s := stringValues(m)
155 return SortedUniqueStrings(s)
156}
157
Sasha Smundak1e533922020-11-19 16:48:18 -0800158// IndexList returns the index of the first occurrence of the given string in the list or -1
Sam Delmerico1717b3b2023-07-18 15:07:24 -0400159func IndexList[T comparable](t T, list []T) int {
Dan Willemsenb1957a52016-06-23 23:44:54 -0700160 for i, l := range list {
Sam Delmerico1717b3b2023-07-18 15:07:24 -0400161 if l == t {
Dan Willemsenb1957a52016-06-23 23:44:54 -0700162 return i
163 }
164 }
Dan Willemsenb1957a52016-06-23 23:44:54 -0700165 return -1
166}
167
Sam Delmerico1717b3b2023-07-18 15:07:24 -0400168func InList[T comparable](t T, list []T) bool {
169 return IndexList(t, list) != -1
Dan Willemsenb1957a52016-06-23 23:44:54 -0700170}
171
Sam Delmerico4e115cc2023-01-19 15:36:52 -0500172func setFromList[T comparable](l []T) map[T]bool {
173 m := make(map[T]bool, len(l))
174 for _, t := range l {
175 m[t] = true
176 }
177 return m
178}
179
Jihoon Kang6e0280d2024-09-11 23:51:35 +0000180// PrettyConcat returns the formatted concatenated string suitable for displaying user-facing
181// messages.
182func PrettyConcat(list []string, quote bool, lastSep string) string {
183 if len(list) == 0 {
184 return ""
185 }
186
187 quoteStr := func(v string) string {
188 if !quote {
189 return v
190 }
191 return fmt.Sprintf("%q", v)
192 }
193
194 if len(list) == 1 {
195 return quoteStr(list[0])
196 }
197
198 var sb strings.Builder
199 for i, val := range list {
200 if i > 0 {
201 sb.WriteString(", ")
202 }
203 if i == len(list)-1 {
204 sb.WriteString(lastSep)
205 if lastSep != "" {
206 sb.WriteString(" ")
207 }
208 }
209 sb.WriteString(quoteStr(val))
210 }
211
212 return sb.String()
213}
214
Sam Delmerico5fb794a2023-01-27 16:01:37 -0500215// ListSetDifference checks if the two lists contain the same elements. It returns
216// a boolean which is true if there is a difference, and then returns lists of elements
217// that are in l1 but not l2, and l2 but not l1.
218func ListSetDifference[T comparable](l1, l2 []T) (bool, []T, []T) {
219 listsDiffer := false
220 diff1 := []T{}
221 diff2 := []T{}
Sam Delmerico4e115cc2023-01-19 15:36:52 -0500222 m1 := setFromList(l1)
223 m2 := setFromList(l2)
Sam Delmerico5fb794a2023-01-27 16:01:37 -0500224 for t := range m1 {
Sam Delmerico4e115cc2023-01-19 15:36:52 -0500225 if _, ok := m2[t]; !ok {
Sam Delmerico5fb794a2023-01-27 16:01:37 -0500226 diff1 = append(diff1, t)
227 listsDiffer = true
Sam Delmerico4e115cc2023-01-19 15:36:52 -0500228 }
229 }
Sam Delmerico5fb794a2023-01-27 16:01:37 -0500230 for t := range m2 {
Sam Delmerico4e115cc2023-01-19 15:36:52 -0500231 if _, ok := m1[t]; !ok {
Sam Delmerico5fb794a2023-01-27 16:01:37 -0500232 diff2 = append(diff2, t)
233 listsDiffer = true
Sam Delmerico4e115cc2023-01-19 15:36:52 -0500234 }
235 }
Sam Delmerico5fb794a2023-01-27 16:01:37 -0500236 return listsDiffer, diff1, diff2
Sam Delmerico4e115cc2023-01-19 15:36:52 -0500237}
238
Jihoon Kangb7e1a482024-06-26 22:11:02 +0000239// Returns true if the two lists have common elements.
240func HasIntersection[T comparable](l1, l2 []T) bool {
Cole Faust687b5ab2025-02-12 21:04:09 -0800241 m1 := setFromList(l1)
242 for _, x := range l2 {
243 if _, ok := m1[x]; ok {
244 return true
245 }
246 }
247 return false
Jihoon Kangb7e1a482024-06-26 22:11:02 +0000248}
249
Jaewoong Jung6431ca72020-01-15 14:15:10 -0800250// Returns true if the given string s is prefixed with any string in the given prefix list.
Jaewoong Jung3aff5782020-02-11 07:54:35 -0800251func HasAnyPrefix(s string, prefixList []string) bool {
Jaewoong Jung6431ca72020-01-15 14:15:10 -0800252 for _, prefix := range prefixList {
253 if strings.HasPrefix(s, prefix) {
254 return true
255 }
256 }
257 return false
258}
259
Chih-Hung Hsieh9f94c362021-02-10 21:56:03 -0800260// Returns true if any string in the given list has the given substring.
261func SubstringInList(list []string, substr string) bool {
262 for _, s := range list {
263 if strings.Contains(s, substr) {
264 return true
265 }
266 }
267 return false
268}
269
Jaewoong Jung6431ca72020-01-15 14:15:10 -0800270// Returns true if any string in the given list has the given prefix.
Jaewoong Jung3aff5782020-02-11 07:54:35 -0800271func PrefixInList(list []string, prefix string) bool {
Jaewoong Jung6431ca72020-01-15 14:15:10 -0800272 for _, s := range list {
Ivan Lozano5f595532017-07-13 14:46:05 -0700273 if strings.HasPrefix(s, prefix) {
274 return true
275 }
276 }
277 return false
278}
279
Ivan Lozanoa0cd8f92020-04-09 09:56:02 -0400280// Returns true if any string in the given list has the given suffix.
281func SuffixInList(list []string, suffix string) bool {
282 for _, s := range list {
283 if strings.HasSuffix(s, suffix) {
284 return true
285 }
286 }
287 return false
288}
289
Jooyung Han12df5fb2019-07-11 16:18:47 +0900290// IndexListPred returns the index of the element which in the given `list` satisfying the predicate, or -1 if there is no such element.
291func IndexListPred(pred func(s string) bool, list []string) int {
292 for i, l := range list {
293 if pred(l) {
294 return i
295 }
296 }
297
298 return -1
299}
300
Sasha Smundak1e533922020-11-19 16:48:18 -0800301// FilterList divides the string list into two lists: one with the strings belonging
302// to the given filter list, and the other with the remaining ones
Colin Crossb4330e22017-12-22 15:47:09 -0800303func FilterList(list []string, filter []string) (remainder []string, filtered []string) {
Sasha Smundak1e533922020-11-19 16:48:18 -0800304 // InList is O(n). May be worth using more efficient lookup for longer lists.
Colin Crossb4330e22017-12-22 15:47:09 -0800305 for _, l := range list {
306 if InList(l, filter) {
307 filtered = append(filtered, l)
308 } else {
309 remainder = append(remainder, l)
310 }
311 }
312
313 return
314}
315
Yurii Zubrytskyi3afd7952024-10-29 18:09:44 -0700316// FilterListByPrefixes performs the same splitting as FilterList does, but treats the passed
317// filters as prefixes
318func FilterListByPrefix(list []string, filter []string) (remainder []string, filtered []string) {
319 for _, l := range list {
320 if HasAnyPrefix(l, filter) {
321 filtered = append(filtered, l)
322 } else {
323 remainder = append(remainder, l)
324 }
325 }
326
327 return
328}
329
Martin Stjernholm1461c4d2021-03-27 19:04:05 +0000330// FilterListPred returns the elements of the given list for which the predicate
331// returns true. Order is kept.
332func FilterListPred(list []string, pred func(s string) bool) (filtered []string) {
333 for _, l := range list {
334 if pred(l) {
335 filtered = append(filtered, l)
336 }
337 }
338 return
339}
340
Sasha Smundak1e533922020-11-19 16:48:18 -0800341// RemoveListFromList removes the strings belonging to the filter list from the
342// given list and returns the result
Colin Crossb4330e22017-12-22 15:47:09 -0800343func RemoveListFromList(list []string, filter_out []string) (result []string) {
344 result = make([]string, 0, len(list))
345 for _, l := range list {
346 if !InList(l, filter_out) {
347 result = append(result, l)
348 }
349 }
350 return
351}
352
Sasha Smundak1e533922020-11-19 16:48:18 -0800353// RemoveFromList removes given string from the string list.
Colin Crossb4330e22017-12-22 15:47:09 -0800354func RemoveFromList(s string, list []string) (bool, []string) {
Sasha Smundak1e533922020-11-19 16:48:18 -0800355 result := make([]string, 0, len(list))
356 var removed bool
357 for _, item := range list {
358 if item != s {
359 result = append(result, item)
360 } else {
361 removed = true
Logan Chien7922ab82018-03-06 18:29:27 +0800362 }
363 }
Sasha Smundak1e533922020-11-19 16:48:18 -0800364 return removed, result
Colin Crossb4330e22017-12-22 15:47:09 -0800365}
366
Ivan Lozano0a468a42024-05-13 21:03:34 -0400367// FirstUniqueFunc returns all unique elements of a slice, keeping the first copy of
368// each. It does not modify the input slice. The eq function should return true
369// if two elements can be considered equal.
370func FirstUniqueFunc[SortableList ~[]Sortable, Sortable any](list SortableList, eq func(a, b Sortable) bool) SortableList {
371 k := 0
372outer:
373 for i := 0; i < len(list); i++ {
374 for j := 0; j < k; j++ {
375 if eq(list[i], list[j]) {
376 continue outer
377 }
378 }
379 list[k] = list[i]
380 k++
381 }
382 return list[:k]
383}
384
Colin Crossb6715442017-10-24 11:13:31 -0700385// FirstUniqueStrings returns all unique elements of a slice of strings, keeping the first copy of
Colin Cross48016d52023-06-27 09:45:26 -0700386// each. It does not modify the input slice.
Colin Crossb6715442017-10-24 11:13:31 -0700387func FirstUniqueStrings(list []string) []string {
Colin Crossc85750b2022-04-21 12:50:51 -0700388 return firstUnique(list)
Colin Cross27027c72020-02-28 15:34:17 -0800389}
390
Colin Crossc85750b2022-04-21 12:50:51 -0700391// firstUnique returns all unique elements of a slice, keeping the first copy of each. It
Colin Cross48016d52023-06-27 09:45:26 -0700392// does not modify the input slice.
Colin Crossc85750b2022-04-21 12:50:51 -0700393func firstUnique[T comparable](slice []T) []T {
Colin Cross48016d52023-06-27 09:45:26 -0700394 // Do not modify the input in-place, operate on a copy instead.
395 slice = CopyOf(slice)
396 return firstUniqueInPlace(slice)
397}
398
399// firstUniqueInPlace returns all unique elements of a slice, keeping the first copy of
400// each. It modifies the slice contents in place, and returns a subslice of the original
401// slice.
402func firstUniqueInPlace[T comparable](slice []T) []T {
403 // 128 was chosen based on BenchmarkFirstUniqueStrings results.
404 if len(slice) > 128 {
Colin Crossc85750b2022-04-21 12:50:51 -0700405 return firstUniqueMap(slice)
406 }
407 return firstUniqueList(slice)
408}
409
410// firstUniqueList is an implementation of firstUnique using an O(N^2) list comparison to look for
411// duplicates.
412func firstUniqueList[T any](in []T) []T {
413 writeIndex := 0
Colin Crossb6715442017-10-24 11:13:31 -0700414outer:
Colin Crossc85750b2022-04-21 12:50:51 -0700415 for readIndex := 0; readIndex < len(in); readIndex++ {
416 for compareIndex := 0; compareIndex < writeIndex; compareIndex++ {
417 if interface{}(in[readIndex]) == interface{}(in[compareIndex]) {
418 // The value at readIndex already exists somewhere in the output region
419 // of the slice before writeIndex, skip it.
Colin Crossb6715442017-10-24 11:13:31 -0700420 continue outer
421 }
422 }
Colin Crossc85750b2022-04-21 12:50:51 -0700423 if readIndex != writeIndex {
424 in[writeIndex] = in[readIndex]
425 }
426 writeIndex++
Colin Crossb6715442017-10-24 11:13:31 -0700427 }
Colin Crossc85750b2022-04-21 12:50:51 -0700428 return in[0:writeIndex]
Colin Crossb6715442017-10-24 11:13:31 -0700429}
430
Colin Crossc85750b2022-04-21 12:50:51 -0700431// firstUniqueMap is an implementation of firstUnique using an O(N) hash set lookup to look for
432// duplicates.
433func firstUniqueMap[T comparable](in []T) []T {
434 writeIndex := 0
435 seen := make(map[T]bool, len(in))
436 for readIndex := 0; readIndex < len(in); readIndex++ {
437 if _, exists := seen[in[readIndex]]; exists {
Colin Cross27027c72020-02-28 15:34:17 -0800438 continue
439 }
Colin Crossc85750b2022-04-21 12:50:51 -0700440 seen[in[readIndex]] = true
441 if readIndex != writeIndex {
442 in[writeIndex] = in[readIndex]
443 }
444 writeIndex++
Colin Cross27027c72020-02-28 15:34:17 -0800445 }
Colin Crossc85750b2022-04-21 12:50:51 -0700446 return in[0:writeIndex]
447}
448
Colin Crossb5e3f7d2023-07-06 15:37:53 -0700449// ReverseSliceInPlace reverses the elements of a slice in place and returns it.
450func ReverseSliceInPlace[T any](in []T) []T {
Colin Crossc85750b2022-04-21 12:50:51 -0700451 for i, j := 0, len(in)-1; i < j; i, j = i+1, j-1 {
452 in[i], in[j] = in[j], in[i]
453 }
Colin Crossb5e3f7d2023-07-06 15:37:53 -0700454 return in
Colin Crossc85750b2022-04-21 12:50:51 -0700455}
456
Colin Crossb5e3f7d2023-07-06 15:37:53 -0700457// ReverseSlice returns a copy of a slice in reverse order.
458func ReverseSlice[T any](in []T) []T {
459 if in == nil {
460 return in
461 }
Colin Crossc85750b2022-04-21 12:50:51 -0700462 out := make([]T, len(in))
463 for i := 0; i < len(in); i++ {
464 out[i] = in[len(in)-1-i]
465 }
466 return out
Colin Cross27027c72020-02-28 15:34:17 -0800467}
468
Colin Crossb6715442017-10-24 11:13:31 -0700469// LastUniqueStrings returns all unique elements of a slice of strings, keeping the last copy of
470// each. It modifies the slice contents in place, and returns a subslice of the original slice.
471func LastUniqueStrings(list []string) []string {
472 totalSkip := 0
473 for i := len(list) - 1; i >= totalSkip; i-- {
474 skip := 0
475 for j := i - 1; j >= totalSkip; j-- {
476 if list[i] == list[j] {
477 skip++
478 } else {
479 list[j+skip] = list[j]
480 }
481 }
482 totalSkip += skip
483 }
484 return list[totalSkip:]
485}
486
Jooyung Hane1633032019-08-01 17:41:43 +0900487// SortedUniqueStrings returns what the name says
488func SortedUniqueStrings(list []string) []string {
Spandan Das8a8714c2023-04-25 18:03:54 +0000489 // FirstUniqueStrings creates a copy of `list`, so the input remains untouched.
Jooyung Hane1633032019-08-01 17:41:43 +0900490 unique := FirstUniqueStrings(list)
491 sort.Strings(unique)
492 return unique
493}
494
Dan Willemsenb1957a52016-06-23 23:44:54 -0700495// checkCalledFromInit panics if a Go package's init function is not on the
496// call stack.
497func checkCalledFromInit() {
498 for skip := 3; ; skip++ {
499 _, funcName, ok := callerName(skip)
500 if !ok {
501 panic("not called from an init func")
502 }
503
Colin Cross3020fee2019-03-19 15:05:17 -0700504 if funcName == "init" || strings.HasPrefix(funcName, "init·") ||
505 strings.HasPrefix(funcName, "init.") {
Dan Willemsenb1957a52016-06-23 23:44:54 -0700506 return
507 }
508 }
509}
510
Colin Cross3020fee2019-03-19 15:05:17 -0700511// A regex to find a package path within a function name. It finds the shortest string that is
512// followed by '.' and doesn't have any '/'s left.
513var pkgPathRe = regexp.MustCompile(`^(.*?)\.([^/]+)$`)
514
Dan Willemsenb1957a52016-06-23 23:44:54 -0700515// callerName returns the package path and function name of the calling
516// function. The skip argument has the same meaning as the skip argument of
517// runtime.Callers.
518func callerName(skip int) (pkgPath, funcName string, ok bool) {
519 var pc [1]uintptr
520 n := runtime.Callers(skip+1, pc[:])
521 if n != 1 {
522 return "", "", false
523 }
524
Colin Cross3020fee2019-03-19 15:05:17 -0700525 f := runtime.FuncForPC(pc[0]).Name()
526 s := pkgPathRe.FindStringSubmatch(f)
527 if len(s) < 3 {
528 panic(fmt.Errorf("failed to extract package path and function name from %q", f))
Dan Willemsenb1957a52016-06-23 23:44:54 -0700529 }
530
Colin Cross3020fee2019-03-19 15:05:17 -0700531 return s[1], s[2], true
Dan Willemsenb1957a52016-06-23 23:44:54 -0700532}
Sundong Ahn0926fae2017-10-17 16:34:51 +0900533
Sasha Smundak1e533922020-11-19 16:48:18 -0800534// GetNumericSdkVersion removes the first occurrence of system_ in a string,
535// which is assumed to be something like "system_1.2.3"
Sundong Ahn0926fae2017-10-17 16:34:51 +0900536func GetNumericSdkVersion(v string) string {
Sasha Smundak1e533922020-11-19 16:48:18 -0800537 return strings.Replace(v, "system_", "", 1)
Sundong Ahn0926fae2017-10-17 16:34:51 +0900538}
Jiyong Park7f67f482019-01-05 12:57:48 +0900539
540// copied from build/kati/strutil.go
541func substPattern(pat, repl, str string) string {
542 ps := strings.SplitN(pat, "%", 2)
543 if len(ps) != 2 {
544 if str == pat {
545 return repl
546 }
547 return str
548 }
549 in := str
Sasha Smundak1e533922020-11-19 16:48:18 -0800550 trimmed := str
Jiyong Park7f67f482019-01-05 12:57:48 +0900551 if ps[0] != "" {
Sasha Smundak1e533922020-11-19 16:48:18 -0800552 trimmed = strings.TrimPrefix(in, ps[0])
553 if trimmed == in {
Jiyong Park7f67f482019-01-05 12:57:48 +0900554 return str
555 }
556 }
Sasha Smundak1e533922020-11-19 16:48:18 -0800557 in = trimmed
Jiyong Park7f67f482019-01-05 12:57:48 +0900558 if ps[1] != "" {
Sasha Smundak1e533922020-11-19 16:48:18 -0800559 trimmed = strings.TrimSuffix(in, ps[1])
560 if trimmed == in {
Jiyong Park7f67f482019-01-05 12:57:48 +0900561 return str
562 }
563 }
564
565 rs := strings.SplitN(repl, "%", 2)
566 if len(rs) != 2 {
567 return repl
568 }
Sasha Smundak1e533922020-11-19 16:48:18 -0800569 return rs[0] + trimmed + rs[1]
Jiyong Park7f67f482019-01-05 12:57:48 +0900570}
571
572// copied from build/kati/strutil.go
573func matchPattern(pat, str string) bool {
574 i := strings.IndexByte(pat, '%')
575 if i < 0 {
576 return pat == str
577 }
578 return strings.HasPrefix(str, pat[:i]) && strings.HasSuffix(str, pat[i+1:])
579}
Ivan Lozano022a73b2019-09-09 20:29:31 -0700580
581var shlibVersionPattern = regexp.MustCompile("(?:\\.\\d+(?:svn)?)+")
582
583// splitFileExt splits a file name into root, suffix and ext. root stands for the file name without
584// the file extension and the version number (e.g. "libexample"). suffix stands for the
585// concatenation of the file extension and the version number (e.g. ".so.1.0"). ext stands for the
586// file extension after the version numbers are trimmed (e.g. ".so").
587func SplitFileExt(name string) (string, string, string) {
588 // Extract and trim the shared lib version number if the file name ends with dot digits.
589 suffix := ""
590 matches := shlibVersionPattern.FindAllStringIndex(name, -1)
591 if len(matches) > 0 {
592 lastMatch := matches[len(matches)-1]
593 if lastMatch[1] == len(name) {
594 suffix = name[lastMatch[0]:lastMatch[1]]
595 name = name[0:lastMatch[0]]
596 }
597 }
598
599 // Extract the file name root and the file extension.
600 ext := filepath.Ext(name)
601 root := strings.TrimSuffix(name, ext)
602 suffix = ext + suffix
603
604 return root, suffix, ext
605}
Colin Cross0a2f7192019-09-23 14:33:09 -0700606
Jihoon Kangcd5bfe22024-04-12 00:19:09 +0000607// ShardPaths takes a Paths, and returns a slice of Paths where each one has at most shardSize paths.
608func ShardPaths(paths Paths, shardSize int) []Paths {
Yu Liu1b2ddc82024-05-15 19:28:56 +0000609 return proptools.ShardBySize(paths, shardSize)
Jihoon Kangcd5bfe22024-04-12 00:19:09 +0000610}
611
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +0100612// ShardString takes a string and returns a slice of strings where the length of each one is
613// at most shardSize.
614func ShardString(s string, shardSize int) []string {
615 if len(s) == 0 {
616 return nil
617 }
618 ret := make([]string, 0, (len(s)+shardSize-1)/shardSize)
619 for len(s) > shardSize {
620 ret = append(ret, s[0:shardSize])
621 s = s[shardSize:]
622 }
623 if len(s) > 0 {
624 ret = append(ret, s)
625 }
626 return ret
627}
628
Colin Cross0a2f7192019-09-23 14:33:09 -0700629// ShardStrings takes a slice of strings, and returns a slice of slices of strings where each one has at most shardSize
630// elements.
631func ShardStrings(s []string, shardSize int) [][]string {
Yu Liu1b2ddc82024-05-15 19:28:56 +0000632 return proptools.ShardBySize(s, shardSize)
Colin Cross0a2f7192019-09-23 14:33:09 -0700633}
Chih-Hung Hsieha5f22ed2019-10-24 20:47:54 -0700634
Sasha Smundak1e533922020-11-19 16:48:18 -0800635// CheckDuplicate checks if there are duplicates in given string list.
636// If there are, it returns first such duplicate and true.
Chih-Hung Hsieha5f22ed2019-10-24 20:47:54 -0700637func CheckDuplicate(values []string) (duplicate string, found bool) {
638 seen := make(map[string]string)
639 for _, v := range values {
640 if duplicate, found = seen[v]; found {
Sasha Smundak1e533922020-11-19 16:48:18 -0800641 return duplicate, true
Chih-Hung Hsieha5f22ed2019-10-24 20:47:54 -0700642 }
643 seen[v] = v
644 }
Sasha Smundak1e533922020-11-19 16:48:18 -0800645 return "", false
Chih-Hung Hsieha5f22ed2019-10-24 20:47:54 -0700646}
Colin Crossb63d7b32023-12-07 16:54:51 -0800647
648func AddToStringSet(set map[string]bool, items []string) {
649 for _, item := range items {
650 set[item] = true
651 }
652}
Colin Cross31a67452023-11-02 16:57:08 -0700653
654// SyncMap is a wrapper around sync.Map that provides type safety via generics.
655type SyncMap[K comparable, V any] struct {
656 sync.Map
657}
658
659// Load returns the value stored in the map for a key, or the zero value if no
660// value is present.
661// The ok result indicates whether value was found in the map.
662func (m *SyncMap[K, V]) Load(key K) (value V, ok bool) {
663 v, ok := m.Map.Load(key)
664 if !ok {
665 return *new(V), false
666 }
667 return v.(V), true
668}
669
670// Store sets the value for a key.
671func (m *SyncMap[K, V]) Store(key K, value V) {
672 m.Map.Store(key, value)
673}
674
675// LoadOrStore returns the existing value for the key if present.
676// Otherwise, it stores and returns the given value.
677// The loaded result is true if the value was loaded, false if stored.
678func (m *SyncMap[K, V]) LoadOrStore(key K, value V) (actual V, loaded bool) {
679 v, loaded := m.Map.LoadOrStore(key, value)
680 return v.(V), loaded
681}
Yu Liu76d94462024-10-31 23:32:36 +0000682
683// AppendIfNotZero append the given value to the slice if it is not the zero value
684// for its type.
685func AppendIfNotZero[T comparable](slice []T, value T) []T {
686 var zeroValue T // Get the zero value of the type T
687 if value != zeroValue {
688 return append(slice, value)
689 }
690 return slice
691}