blob: 6c0ddf40e90815bf1a36a95564695da13d15a315 [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 (
Colin Cross3020fee2019-03-19 15:05:17 -070018 "fmt"
Ivan Lozano022a73b2019-09-09 20:29:31 -070019 "path/filepath"
Inseob Kim1a365c62019-06-08 15:47:51 +090020 "reflect"
Colin Cross3020fee2019-03-19 15:05:17 -070021 "regexp"
Dan Willemsenb1957a52016-06-23 23:44:54 -070022 "runtime"
23 "sort"
24 "strings"
25)
Colin Cross1f8c52b2015-06-16 16:38:17 -070026
Colin Cross454c0872019-02-15 23:03:34 -080027// CopyOf returns a new slice that has the same contents as s.
28func CopyOf(s []string) []string {
29 return append([]string(nil), s...)
30}
31
Jiakai Zhang8fe3a412023-02-23 17:37:16 +000032// Concat returns a new slice concatenated from the two input slices. It does not change the input
33// slices.
34func Concat[T any](s1, s2 []T) []T {
35 res := make([]T, 0, len(s1)+len(s2))
36 res = append(res, s1...)
37 res = append(res, s2...)
38 return res
39}
40
Sasha Smundak1e533922020-11-19 16:48:18 -080041// JoinWithPrefix prepends the prefix to each string in the list and
42// returns them joined together with " " as separator.
Colin Crossc0b06f12015-04-08 13:03:43 -070043func JoinWithPrefix(strs []string, prefix string) string {
Yu Liu8d82ac52022-05-17 15:13:28 -070044 return JoinWithPrefixAndSeparator(strs, prefix, " ")
45}
46
47// JoinWithPrefixAndSeparator prepends the prefix to each string in the list and
48// returns them joined together with the given separator.
49func JoinWithPrefixAndSeparator(strs []string, prefix string, sep string) string {
Colin Crossc0b06f12015-04-08 13:03:43 -070050 if len(strs) == 0 {
51 return ""
52 }
53
Sasha Smundak1e533922020-11-19 16:48:18 -080054 var buf strings.Builder
55 buf.WriteString(prefix)
56 buf.WriteString(strs[0])
57 for i := 1; i < len(strs); i++ {
Yu Liu8d82ac52022-05-17 15:13:28 -070058 buf.WriteString(sep)
Sasha Smundak1e533922020-11-19 16:48:18 -080059 buf.WriteString(prefix)
60 buf.WriteString(strs[i])
Colin Crossc0b06f12015-04-08 13:03:43 -070061 }
Sasha Smundak1e533922020-11-19 16:48:18 -080062 return buf.String()
Colin Crossc0b06f12015-04-08 13:03:43 -070063}
Colin Cross9b6826f2015-04-10 15:47:33 -070064
Cole Faust18994c72023-02-28 16:02:16 -080065// SortedStringKeys returns the keys of the given map in the ascending order.
66//
67// Deprecated: Use SortedKeys instead.
Inseob Kim1a365c62019-06-08 15:47:51 +090068func SortedStringKeys(m interface{}) []string {
69 v := reflect.ValueOf(m)
70 if v.Kind() != reflect.Map {
71 panic(fmt.Sprintf("%#v is not a map", m))
72 }
Colin Cross9eb853b2022-02-17 11:13:37 -080073 if v.Len() == 0 {
74 return nil
75 }
76 iter := v.MapRange()
77 s := make([]string, 0, v.Len())
78 for iter.Next() {
79 s = append(s, iter.Key().String())
Colin Cross1f8c52b2015-06-16 16:38:17 -070080 }
81 sort.Strings(s)
82 return s
83}
Dan Willemsenb1957a52016-06-23 23:44:54 -070084
Cole Faust18994c72023-02-28 16:02:16 -080085type Ordered interface {
86 ~string |
87 ~float32 | ~float64 |
88 ~int | ~int8 | ~int16 | ~int32 | ~int64 |
89 ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr
90}
91
92// SortedKeys returns the keys of the given map in the ascending order.
93func SortedKeys[T Ordered, V any](m map[T]V) []T {
94 if len(m) == 0 {
95 return nil
96 }
97 ret := make([]T, 0, len(m))
98 for k := range m {
99 ret = append(ret, k)
100 }
101 sort.Slice(ret, func(i, j int) bool {
102 return ret[i] < ret[j]
103 })
104 return ret
105}
106
Colin Cross9eb853b2022-02-17 11:13:37 -0800107// stringValues returns the values of the given string-valued map in randomized map order.
108func stringValues(m interface{}) []string {
109 v := reflect.ValueOf(m)
110 if v.Kind() != reflect.Map {
111 panic(fmt.Sprintf("%#v is not a map", m))
112 }
113 if v.Len() == 0 {
114 return nil
115 }
116 iter := v.MapRange()
117 s := make([]string, 0, v.Len())
118 for iter.Next() {
119 s = append(s, iter.Value().String())
120 }
121 return s
122}
123
124// SortedStringValues returns the values of the given string-valued map in the ascending order.
125func SortedStringValues(m interface{}) []string {
126 s := stringValues(m)
127 sort.Strings(s)
128 return s
129}
130
131// SortedUniqueStringValues returns the values of the given string-valued map in the ascending order
132// with duplicates removed.
133func SortedUniqueStringValues(m interface{}) []string {
134 s := stringValues(m)
135 return SortedUniqueStrings(s)
136}
137
Sasha Smundak1e533922020-11-19 16:48:18 -0800138// IndexList returns the index of the first occurrence of the given string in the list or -1
Colin Crossb4330e22017-12-22 15:47:09 -0800139func IndexList(s string, list []string) int {
Dan Willemsenb1957a52016-06-23 23:44:54 -0700140 for i, l := range list {
141 if l == s {
142 return i
143 }
144 }
145
146 return -1
147}
148
Sasha Smundak1e533922020-11-19 16:48:18 -0800149// InList checks if the string belongs to the list
Colin Crossb4330e22017-12-22 15:47:09 -0800150func InList(s string, list []string) bool {
151 return IndexList(s, list) != -1
Dan Willemsenb1957a52016-06-23 23:44:54 -0700152}
153
Sam Delmerico4e115cc2023-01-19 15:36:52 -0500154func setFromList[T comparable](l []T) map[T]bool {
155 m := make(map[T]bool, len(l))
156 for _, t := range l {
157 m[t] = true
158 }
159 return m
160}
161
Sam Delmerico5fb794a2023-01-27 16:01:37 -0500162// ListSetDifference checks if the two lists contain the same elements. It returns
163// a boolean which is true if there is a difference, and then returns lists of elements
164// that are in l1 but not l2, and l2 but not l1.
165func ListSetDifference[T comparable](l1, l2 []T) (bool, []T, []T) {
166 listsDiffer := false
167 diff1 := []T{}
168 diff2 := []T{}
Sam Delmerico4e115cc2023-01-19 15:36:52 -0500169 m1 := setFromList(l1)
170 m2 := setFromList(l2)
Sam Delmerico5fb794a2023-01-27 16:01:37 -0500171 for t := range m1 {
Sam Delmerico4e115cc2023-01-19 15:36:52 -0500172 if _, ok := m2[t]; !ok {
Sam Delmerico5fb794a2023-01-27 16:01:37 -0500173 diff1 = append(diff1, t)
174 listsDiffer = true
Sam Delmerico4e115cc2023-01-19 15:36:52 -0500175 }
176 }
Sam Delmerico5fb794a2023-01-27 16:01:37 -0500177 for t := range m2 {
Sam Delmerico4e115cc2023-01-19 15:36:52 -0500178 if _, ok := m1[t]; !ok {
Sam Delmerico5fb794a2023-01-27 16:01:37 -0500179 diff2 = append(diff2, t)
180 listsDiffer = true
Sam Delmerico4e115cc2023-01-19 15:36:52 -0500181 }
182 }
Sam Delmerico5fb794a2023-01-27 16:01:37 -0500183 return listsDiffer, diff1, diff2
Sam Delmerico4e115cc2023-01-19 15:36:52 -0500184}
185
Jaewoong Jung6431ca72020-01-15 14:15:10 -0800186// Returns true if the given string s is prefixed with any string in the given prefix list.
Jaewoong Jung3aff5782020-02-11 07:54:35 -0800187func HasAnyPrefix(s string, prefixList []string) bool {
Jaewoong Jung6431ca72020-01-15 14:15:10 -0800188 for _, prefix := range prefixList {
189 if strings.HasPrefix(s, prefix) {
190 return true
191 }
192 }
193 return false
194}
195
Chih-Hung Hsieh9f94c362021-02-10 21:56:03 -0800196// Returns true if any string in the given list has the given substring.
197func SubstringInList(list []string, substr string) bool {
198 for _, s := range list {
199 if strings.Contains(s, substr) {
200 return true
201 }
202 }
203 return false
204}
205
Jaewoong Jung6431ca72020-01-15 14:15:10 -0800206// Returns true if any string in the given list has the given prefix.
Jaewoong Jung3aff5782020-02-11 07:54:35 -0800207func PrefixInList(list []string, prefix string) bool {
Jaewoong Jung6431ca72020-01-15 14:15:10 -0800208 for _, s := range list {
Ivan Lozano5f595532017-07-13 14:46:05 -0700209 if strings.HasPrefix(s, prefix) {
210 return true
211 }
212 }
213 return false
214}
215
Ivan Lozanoa0cd8f92020-04-09 09:56:02 -0400216// Returns true if any string in the given list has the given suffix.
217func SuffixInList(list []string, suffix string) bool {
218 for _, s := range list {
219 if strings.HasSuffix(s, suffix) {
220 return true
221 }
222 }
223 return false
224}
225
Jooyung Han12df5fb2019-07-11 16:18:47 +0900226// IndexListPred returns the index of the element which in the given `list` satisfying the predicate, or -1 if there is no such element.
227func IndexListPred(pred func(s string) bool, list []string) int {
228 for i, l := range list {
229 if pred(l) {
230 return i
231 }
232 }
233
234 return -1
235}
236
Sasha Smundak1e533922020-11-19 16:48:18 -0800237// FilterList divides the string list into two lists: one with the strings belonging
238// to the given filter list, and the other with the remaining ones
Colin Crossb4330e22017-12-22 15:47:09 -0800239func FilterList(list []string, filter []string) (remainder []string, filtered []string) {
Sasha Smundak1e533922020-11-19 16:48:18 -0800240 // InList is O(n). May be worth using more efficient lookup for longer lists.
Colin Crossb4330e22017-12-22 15:47:09 -0800241 for _, l := range list {
242 if InList(l, filter) {
243 filtered = append(filtered, l)
244 } else {
245 remainder = append(remainder, l)
246 }
247 }
248
249 return
250}
251
Martin Stjernholm1461c4d2021-03-27 19:04:05 +0000252// FilterListPred returns the elements of the given list for which the predicate
253// returns true. Order is kept.
254func FilterListPred(list []string, pred func(s string) bool) (filtered []string) {
255 for _, l := range list {
256 if pred(l) {
257 filtered = append(filtered, l)
258 }
259 }
260 return
261}
262
Sasha Smundak1e533922020-11-19 16:48:18 -0800263// RemoveListFromList removes the strings belonging to the filter list from the
264// given list and returns the result
Colin Crossb4330e22017-12-22 15:47:09 -0800265func RemoveListFromList(list []string, filter_out []string) (result []string) {
266 result = make([]string, 0, len(list))
267 for _, l := range list {
268 if !InList(l, filter_out) {
269 result = append(result, l)
270 }
271 }
272 return
273}
274
Sasha Smundak1e533922020-11-19 16:48:18 -0800275// RemoveFromList removes given string from the string list.
Colin Crossb4330e22017-12-22 15:47:09 -0800276func RemoveFromList(s string, list []string) (bool, []string) {
Sasha Smundak1e533922020-11-19 16:48:18 -0800277 result := make([]string, 0, len(list))
278 var removed bool
279 for _, item := range list {
280 if item != s {
281 result = append(result, item)
282 } else {
283 removed = true
Logan Chien7922ab82018-03-06 18:29:27 +0800284 }
285 }
Sasha Smundak1e533922020-11-19 16:48:18 -0800286 return removed, result
Colin Crossb4330e22017-12-22 15:47:09 -0800287}
288
Colin Crossb6715442017-10-24 11:13:31 -0700289// FirstUniqueStrings returns all unique elements of a slice of strings, keeping the first copy of
290// each. It modifies the slice contents in place, and returns a subslice of the original slice.
291func FirstUniqueStrings(list []string) []string {
Colin Cross27027c72020-02-28 15:34:17 -0800292 // 128 was chosen based on BenchmarkFirstUniqueStrings results.
293 if len(list) > 128 {
294 return firstUniqueStringsMap(list)
295 }
296 return firstUniqueStringsList(list)
297}
298
299func firstUniqueStringsList(list []string) []string {
Colin Crossb6715442017-10-24 11:13:31 -0700300 k := 0
301outer:
302 for i := 0; i < len(list); i++ {
303 for j := 0; j < k; j++ {
304 if list[i] == list[j] {
305 continue outer
306 }
307 }
308 list[k] = list[i]
309 k++
310 }
311 return list[:k]
312}
313
Colin Cross27027c72020-02-28 15:34:17 -0800314func firstUniqueStringsMap(list []string) []string {
315 k := 0
316 seen := make(map[string]bool, len(list))
317 for i := 0; i < len(list); i++ {
318 if seen[list[i]] {
319 continue
320 }
321 seen[list[i]] = true
322 list[k] = list[i]
323 k++
324 }
325 return list[:k]
326}
327
Colin Crossb6715442017-10-24 11:13:31 -0700328// LastUniqueStrings returns all unique elements of a slice of strings, keeping the last copy of
329// each. It modifies the slice contents in place, and returns a subslice of the original slice.
330func LastUniqueStrings(list []string) []string {
331 totalSkip := 0
332 for i := len(list) - 1; i >= totalSkip; i-- {
333 skip := 0
334 for j := i - 1; j >= totalSkip; j-- {
335 if list[i] == list[j] {
336 skip++
337 } else {
338 list[j+skip] = list[j]
339 }
340 }
341 totalSkip += skip
342 }
343 return list[totalSkip:]
344}
345
Jooyung Hane1633032019-08-01 17:41:43 +0900346// SortedUniqueStrings returns what the name says
347func SortedUniqueStrings(list []string) []string {
348 unique := FirstUniqueStrings(list)
349 sort.Strings(unique)
350 return unique
351}
352
Dan Willemsenb1957a52016-06-23 23:44:54 -0700353// checkCalledFromInit panics if a Go package's init function is not on the
354// call stack.
355func checkCalledFromInit() {
356 for skip := 3; ; skip++ {
357 _, funcName, ok := callerName(skip)
358 if !ok {
359 panic("not called from an init func")
360 }
361
Colin Cross3020fee2019-03-19 15:05:17 -0700362 if funcName == "init" || strings.HasPrefix(funcName, "init·") ||
363 strings.HasPrefix(funcName, "init.") {
Dan Willemsenb1957a52016-06-23 23:44:54 -0700364 return
365 }
366 }
367}
368
Colin Cross3020fee2019-03-19 15:05:17 -0700369// A regex to find a package path within a function name. It finds the shortest string that is
370// followed by '.' and doesn't have any '/'s left.
371var pkgPathRe = regexp.MustCompile(`^(.*?)\.([^/]+)$`)
372
Dan Willemsenb1957a52016-06-23 23:44:54 -0700373// callerName returns the package path and function name of the calling
374// function. The skip argument has the same meaning as the skip argument of
375// runtime.Callers.
376func callerName(skip int) (pkgPath, funcName string, ok bool) {
377 var pc [1]uintptr
378 n := runtime.Callers(skip+1, pc[:])
379 if n != 1 {
380 return "", "", false
381 }
382
Colin Cross3020fee2019-03-19 15:05:17 -0700383 f := runtime.FuncForPC(pc[0]).Name()
384 s := pkgPathRe.FindStringSubmatch(f)
385 if len(s) < 3 {
386 panic(fmt.Errorf("failed to extract package path and function name from %q", f))
Dan Willemsenb1957a52016-06-23 23:44:54 -0700387 }
388
Colin Cross3020fee2019-03-19 15:05:17 -0700389 return s[1], s[2], true
Dan Willemsenb1957a52016-06-23 23:44:54 -0700390}
Sundong Ahn0926fae2017-10-17 16:34:51 +0900391
Sasha Smundak1e533922020-11-19 16:48:18 -0800392// GetNumericSdkVersion removes the first occurrence of system_ in a string,
393// which is assumed to be something like "system_1.2.3"
Sundong Ahn0926fae2017-10-17 16:34:51 +0900394func GetNumericSdkVersion(v string) string {
Sasha Smundak1e533922020-11-19 16:48:18 -0800395 return strings.Replace(v, "system_", "", 1)
Sundong Ahn0926fae2017-10-17 16:34:51 +0900396}
Jiyong Park7f67f482019-01-05 12:57:48 +0900397
398// copied from build/kati/strutil.go
399func substPattern(pat, repl, str string) string {
400 ps := strings.SplitN(pat, "%", 2)
401 if len(ps) != 2 {
402 if str == pat {
403 return repl
404 }
405 return str
406 }
407 in := str
Sasha Smundak1e533922020-11-19 16:48:18 -0800408 trimmed := str
Jiyong Park7f67f482019-01-05 12:57:48 +0900409 if ps[0] != "" {
Sasha Smundak1e533922020-11-19 16:48:18 -0800410 trimmed = strings.TrimPrefix(in, ps[0])
411 if trimmed == in {
Jiyong Park7f67f482019-01-05 12:57:48 +0900412 return str
413 }
414 }
Sasha Smundak1e533922020-11-19 16:48:18 -0800415 in = trimmed
Jiyong Park7f67f482019-01-05 12:57:48 +0900416 if ps[1] != "" {
Sasha Smundak1e533922020-11-19 16:48:18 -0800417 trimmed = strings.TrimSuffix(in, ps[1])
418 if trimmed == in {
Jiyong Park7f67f482019-01-05 12:57:48 +0900419 return str
420 }
421 }
422
423 rs := strings.SplitN(repl, "%", 2)
424 if len(rs) != 2 {
425 return repl
426 }
Sasha Smundak1e533922020-11-19 16:48:18 -0800427 return rs[0] + trimmed + rs[1]
Jiyong Park7f67f482019-01-05 12:57:48 +0900428}
429
430// copied from build/kati/strutil.go
431func matchPattern(pat, str string) bool {
432 i := strings.IndexByte(pat, '%')
433 if i < 0 {
434 return pat == str
435 }
436 return strings.HasPrefix(str, pat[:i]) && strings.HasSuffix(str, pat[i+1:])
437}
Ivan Lozano022a73b2019-09-09 20:29:31 -0700438
439var shlibVersionPattern = regexp.MustCompile("(?:\\.\\d+(?:svn)?)+")
440
441// splitFileExt splits a file name into root, suffix and ext. root stands for the file name without
442// the file extension and the version number (e.g. "libexample"). suffix stands for the
443// concatenation of the file extension and the version number (e.g. ".so.1.0"). ext stands for the
444// file extension after the version numbers are trimmed (e.g. ".so").
445func SplitFileExt(name string) (string, string, string) {
446 // Extract and trim the shared lib version number if the file name ends with dot digits.
447 suffix := ""
448 matches := shlibVersionPattern.FindAllStringIndex(name, -1)
449 if len(matches) > 0 {
450 lastMatch := matches[len(matches)-1]
451 if lastMatch[1] == len(name) {
452 suffix = name[lastMatch[0]:lastMatch[1]]
453 name = name[0:lastMatch[0]]
454 }
455 }
456
457 // Extract the file name root and the file extension.
458 ext := filepath.Ext(name)
459 root := strings.TrimSuffix(name, ext)
460 suffix = ext + suffix
461
462 return root, suffix, ext
463}
Colin Cross0a2f7192019-09-23 14:33:09 -0700464
465// ShardPaths takes a Paths, and returns a slice of Paths where each one has at most shardSize paths.
466func ShardPaths(paths Paths, shardSize int) []Paths {
467 if len(paths) == 0 {
468 return nil
469 }
470 ret := make([]Paths, 0, (len(paths)+shardSize-1)/shardSize)
471 for len(paths) > shardSize {
472 ret = append(ret, paths[0:shardSize])
473 paths = paths[shardSize:]
474 }
475 if len(paths) > 0 {
476 ret = append(ret, paths)
477 }
478 return ret
479}
480
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +0100481// ShardString takes a string and returns a slice of strings where the length of each one is
482// at most shardSize.
483func ShardString(s string, shardSize int) []string {
484 if len(s) == 0 {
485 return nil
486 }
487 ret := make([]string, 0, (len(s)+shardSize-1)/shardSize)
488 for len(s) > shardSize {
489 ret = append(ret, s[0:shardSize])
490 s = s[shardSize:]
491 }
492 if len(s) > 0 {
493 ret = append(ret, s)
494 }
495 return ret
496}
497
Colin Cross0a2f7192019-09-23 14:33:09 -0700498// ShardStrings takes a slice of strings, and returns a slice of slices of strings where each one has at most shardSize
499// elements.
500func ShardStrings(s []string, shardSize int) [][]string {
501 if len(s) == 0 {
502 return nil
503 }
504 ret := make([][]string, 0, (len(s)+shardSize-1)/shardSize)
505 for len(s) > shardSize {
506 ret = append(ret, s[0:shardSize])
507 s = s[shardSize:]
508 }
509 if len(s) > 0 {
510 ret = append(ret, s)
511 }
512 return ret
513}
Chih-Hung Hsieha5f22ed2019-10-24 20:47:54 -0700514
Sasha Smundak1e533922020-11-19 16:48:18 -0800515// CheckDuplicate checks if there are duplicates in given string list.
516// If there are, it returns first such duplicate and true.
Chih-Hung Hsieha5f22ed2019-10-24 20:47:54 -0700517func CheckDuplicate(values []string) (duplicate string, found bool) {
518 seen := make(map[string]string)
519 for _, v := range values {
520 if duplicate, found = seen[v]; found {
Sasha Smundak1e533922020-11-19 16:48:18 -0800521 return duplicate, true
Chih-Hung Hsieha5f22ed2019-10-24 20:47:54 -0700522 }
523 seen[v] = v
524 }
Sasha Smundak1e533922020-11-19 16:48:18 -0800525 return "", false
Chih-Hung Hsieha5f22ed2019-10-24 20:47:54 -0700526}