util.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556
  1. // 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. package android
  15. import (
  16. "fmt"
  17. "path/filepath"
  18. "reflect"
  19. "regexp"
  20. "runtime"
  21. "sort"
  22. "strings"
  23. )
  24. // CopyOf returns a new slice that has the same contents as s.
  25. func CopyOf(s []string) []string {
  26. // If the input is nil, return nil and not an empty list
  27. if s == nil {
  28. return s
  29. }
  30. return append([]string{}, s...)
  31. }
  32. // Concat returns a new slice concatenated from the two input slices. It does not change the input
  33. // slices.
  34. func 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. // JoinWithPrefix prepends the prefix to each string in the list and
  41. // returns them joined together with " " as separator.
  42. func JoinWithPrefix(strs []string, prefix string) string {
  43. return JoinWithPrefixAndSeparator(strs, prefix, " ")
  44. }
  45. // JoinWithPrefixAndSeparator prepends the prefix to each string in the list and
  46. // returns them joined together with the given separator.
  47. func JoinWithPrefixAndSeparator(strs []string, prefix string, sep string) string {
  48. if len(strs) == 0 {
  49. return ""
  50. }
  51. var buf strings.Builder
  52. buf.WriteString(prefix)
  53. buf.WriteString(strs[0])
  54. for i := 1; i < len(strs); i++ {
  55. buf.WriteString(sep)
  56. buf.WriteString(prefix)
  57. buf.WriteString(strs[i])
  58. }
  59. return buf.String()
  60. }
  61. // SortedStringKeys returns the keys of the given map in the ascending order.
  62. //
  63. // Deprecated: Use SortedKeys instead.
  64. func SortedStringKeys[V any](m map[string]V) []string {
  65. return SortedKeys(m)
  66. }
  67. type Ordered interface {
  68. ~string |
  69. ~float32 | ~float64 |
  70. ~int | ~int8 | ~int16 | ~int32 | ~int64 |
  71. ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr
  72. }
  73. // SortedKeys returns the keys of the given map in the ascending order.
  74. func SortedKeys[T Ordered, V any](m map[T]V) []T {
  75. if len(m) == 0 {
  76. return nil
  77. }
  78. ret := make([]T, 0, len(m))
  79. for k := range m {
  80. ret = append(ret, k)
  81. }
  82. sort.Slice(ret, func(i, j int) bool {
  83. return ret[i] < ret[j]
  84. })
  85. return ret
  86. }
  87. // stringValues returns the values of the given string-valued map in randomized map order.
  88. func stringValues(m interface{}) []string {
  89. v := reflect.ValueOf(m)
  90. if v.Kind() != reflect.Map {
  91. panic(fmt.Sprintf("%#v is not a map", m))
  92. }
  93. if v.Len() == 0 {
  94. return nil
  95. }
  96. iter := v.MapRange()
  97. s := make([]string, 0, v.Len())
  98. for iter.Next() {
  99. s = append(s, iter.Value().String())
  100. }
  101. return s
  102. }
  103. // SortedStringValues returns the values of the given string-valued map in the ascending order.
  104. func SortedStringValues(m interface{}) []string {
  105. s := stringValues(m)
  106. sort.Strings(s)
  107. return s
  108. }
  109. // SortedUniqueStringValues returns the values of the given string-valued map in the ascending order
  110. // with duplicates removed.
  111. func SortedUniqueStringValues(m interface{}) []string {
  112. s := stringValues(m)
  113. return SortedUniqueStrings(s)
  114. }
  115. // IndexList returns the index of the first occurrence of the given string in the list or -1
  116. func IndexList(s string, list []string) int {
  117. for i, l := range list {
  118. if l == s {
  119. return i
  120. }
  121. }
  122. return -1
  123. }
  124. // InList checks if the string belongs to the list
  125. func InList(s string, list []string) bool {
  126. return IndexList(s, list) != -1
  127. }
  128. func setFromList[T comparable](l []T) map[T]bool {
  129. m := make(map[T]bool, len(l))
  130. for _, t := range l {
  131. m[t] = true
  132. }
  133. return m
  134. }
  135. // ListSetDifference checks if the two lists contain the same elements. It returns
  136. // a boolean which is true if there is a difference, and then returns lists of elements
  137. // that are in l1 but not l2, and l2 but not l1.
  138. func ListSetDifference[T comparable](l1, l2 []T) (bool, []T, []T) {
  139. listsDiffer := false
  140. diff1 := []T{}
  141. diff2 := []T{}
  142. m1 := setFromList(l1)
  143. m2 := setFromList(l2)
  144. for t := range m1 {
  145. if _, ok := m2[t]; !ok {
  146. diff1 = append(diff1, t)
  147. listsDiffer = true
  148. }
  149. }
  150. for t := range m2 {
  151. if _, ok := m1[t]; !ok {
  152. diff2 = append(diff2, t)
  153. listsDiffer = true
  154. }
  155. }
  156. return listsDiffer, diff1, diff2
  157. }
  158. // Returns true if the given string s is prefixed with any string in the given prefix list.
  159. func HasAnyPrefix(s string, prefixList []string) bool {
  160. for _, prefix := range prefixList {
  161. if strings.HasPrefix(s, prefix) {
  162. return true
  163. }
  164. }
  165. return false
  166. }
  167. // Returns true if any string in the given list has the given substring.
  168. func SubstringInList(list []string, substr string) bool {
  169. for _, s := range list {
  170. if strings.Contains(s, substr) {
  171. return true
  172. }
  173. }
  174. return false
  175. }
  176. // Returns true if any string in the given list has the given prefix.
  177. func PrefixInList(list []string, prefix string) bool {
  178. for _, s := range list {
  179. if strings.HasPrefix(s, prefix) {
  180. return true
  181. }
  182. }
  183. return false
  184. }
  185. // Returns true if any string in the given list has the given suffix.
  186. func SuffixInList(list []string, suffix string) bool {
  187. for _, s := range list {
  188. if strings.HasSuffix(s, suffix) {
  189. return true
  190. }
  191. }
  192. return false
  193. }
  194. // IndexListPred returns the index of the element which in the given `list` satisfying the predicate, or -1 if there is no such element.
  195. func IndexListPred(pred func(s string) bool, list []string) int {
  196. for i, l := range list {
  197. if pred(l) {
  198. return i
  199. }
  200. }
  201. return -1
  202. }
  203. // FilterList divides the string list into two lists: one with the strings belonging
  204. // to the given filter list, and the other with the remaining ones
  205. func FilterList(list []string, filter []string) (remainder []string, filtered []string) {
  206. // InList is O(n). May be worth using more efficient lookup for longer lists.
  207. for _, l := range list {
  208. if InList(l, filter) {
  209. filtered = append(filtered, l)
  210. } else {
  211. remainder = append(remainder, l)
  212. }
  213. }
  214. return
  215. }
  216. // FilterListPred returns the elements of the given list for which the predicate
  217. // returns true. Order is kept.
  218. func FilterListPred(list []string, pred func(s string) bool) (filtered []string) {
  219. for _, l := range list {
  220. if pred(l) {
  221. filtered = append(filtered, l)
  222. }
  223. }
  224. return
  225. }
  226. // RemoveListFromList removes the strings belonging to the filter list from the
  227. // given list and returns the result
  228. func RemoveListFromList(list []string, filter_out []string) (result []string) {
  229. result = make([]string, 0, len(list))
  230. for _, l := range list {
  231. if !InList(l, filter_out) {
  232. result = append(result, l)
  233. }
  234. }
  235. return
  236. }
  237. // RemoveFromList removes given string from the string list.
  238. func RemoveFromList(s string, list []string) (bool, []string) {
  239. result := make([]string, 0, len(list))
  240. var removed bool
  241. for _, item := range list {
  242. if item != s {
  243. result = append(result, item)
  244. } else {
  245. removed = true
  246. }
  247. }
  248. return removed, result
  249. }
  250. // FirstUniqueStrings returns all unique elements of a slice of strings, keeping the first copy of
  251. // each. It modifies the slice contents in place, and returns a subslice of the original slice.
  252. func FirstUniqueStrings(list []string) []string {
  253. // Do not moodify the input in-place, operate on a copy instead.
  254. list = CopyOf(list)
  255. // 128 was chosen based on BenchmarkFirstUniqueStrings results.
  256. if len(list) > 128 {
  257. return firstUnique(list)
  258. }
  259. return firstUnique(list)
  260. }
  261. // firstUnique returns all unique elements of a slice, keeping the first copy of each. It
  262. // modifies the slice contents in place, and returns a subslice of the original slice.
  263. func firstUnique[T comparable](slice []T) []T {
  264. // 4 was chosen based on Benchmark_firstUnique results.
  265. if len(slice) > 4 {
  266. return firstUniqueMap(slice)
  267. }
  268. return firstUniqueList(slice)
  269. }
  270. // firstUniqueList is an implementation of firstUnique using an O(N^2) list comparison to look for
  271. // duplicates.
  272. func firstUniqueList[T any](in []T) []T {
  273. writeIndex := 0
  274. outer:
  275. for readIndex := 0; readIndex < len(in); readIndex++ {
  276. for compareIndex := 0; compareIndex < writeIndex; compareIndex++ {
  277. if interface{}(in[readIndex]) == interface{}(in[compareIndex]) {
  278. // The value at readIndex already exists somewhere in the output region
  279. // of the slice before writeIndex, skip it.
  280. continue outer
  281. }
  282. }
  283. if readIndex != writeIndex {
  284. in[writeIndex] = in[readIndex]
  285. }
  286. writeIndex++
  287. }
  288. return in[0:writeIndex]
  289. }
  290. // firstUniqueMap is an implementation of firstUnique using an O(N) hash set lookup to look for
  291. // duplicates.
  292. func firstUniqueMap[T comparable](in []T) []T {
  293. writeIndex := 0
  294. seen := make(map[T]bool, len(in))
  295. for readIndex := 0; readIndex < len(in); readIndex++ {
  296. if _, exists := seen[in[readIndex]]; exists {
  297. continue
  298. }
  299. seen[in[readIndex]] = true
  300. if readIndex != writeIndex {
  301. in[writeIndex] = in[readIndex]
  302. }
  303. writeIndex++
  304. }
  305. return in[0:writeIndex]
  306. }
  307. // reverseSliceInPlace reverses the elements of a slice in place.
  308. func reverseSliceInPlace[T any](in []T) {
  309. for i, j := 0, len(in)-1; i < j; i, j = i+1, j-1 {
  310. in[i], in[j] = in[j], in[i]
  311. }
  312. }
  313. // reverseSlice returns a copy of a slice in reverse order.
  314. func reverseSlice[T any](in []T) []T {
  315. out := make([]T, len(in))
  316. for i := 0; i < len(in); i++ {
  317. out[i] = in[len(in)-1-i]
  318. }
  319. return out
  320. }
  321. // LastUniqueStrings returns all unique elements of a slice of strings, keeping the last copy of
  322. // each. It modifies the slice contents in place, and returns a subslice of the original slice.
  323. func LastUniqueStrings(list []string) []string {
  324. totalSkip := 0
  325. for i := len(list) - 1; i >= totalSkip; i-- {
  326. skip := 0
  327. for j := i - 1; j >= totalSkip; j-- {
  328. if list[i] == list[j] {
  329. skip++
  330. } else {
  331. list[j+skip] = list[j]
  332. }
  333. }
  334. totalSkip += skip
  335. }
  336. return list[totalSkip:]
  337. }
  338. // SortedUniqueStrings returns what the name says
  339. func SortedUniqueStrings(list []string) []string {
  340. // FirstUniqueStrings creates a copy of `list`, so the input remains untouched.
  341. unique := FirstUniqueStrings(list)
  342. sort.Strings(unique)
  343. return unique
  344. }
  345. // checkCalledFromInit panics if a Go package's init function is not on the
  346. // call stack.
  347. func checkCalledFromInit() {
  348. for skip := 3; ; skip++ {
  349. _, funcName, ok := callerName(skip)
  350. if !ok {
  351. panic("not called from an init func")
  352. }
  353. if funcName == "init" || strings.HasPrefix(funcName, "init·") ||
  354. strings.HasPrefix(funcName, "init.") {
  355. return
  356. }
  357. }
  358. }
  359. // A regex to find a package path within a function name. It finds the shortest string that is
  360. // followed by '.' and doesn't have any '/'s left.
  361. var pkgPathRe = regexp.MustCompile(`^(.*?)\.([^/]+)$`)
  362. // callerName returns the package path and function name of the calling
  363. // function. The skip argument has the same meaning as the skip argument of
  364. // runtime.Callers.
  365. func callerName(skip int) (pkgPath, funcName string, ok bool) {
  366. var pc [1]uintptr
  367. n := runtime.Callers(skip+1, pc[:])
  368. if n != 1 {
  369. return "", "", false
  370. }
  371. f := runtime.FuncForPC(pc[0]).Name()
  372. s := pkgPathRe.FindStringSubmatch(f)
  373. if len(s) < 3 {
  374. panic(fmt.Errorf("failed to extract package path and function name from %q", f))
  375. }
  376. return s[1], s[2], true
  377. }
  378. // GetNumericSdkVersion removes the first occurrence of system_ in a string,
  379. // which is assumed to be something like "system_1.2.3"
  380. func GetNumericSdkVersion(v string) string {
  381. return strings.Replace(v, "system_", "", 1)
  382. }
  383. // copied from build/kati/strutil.go
  384. func substPattern(pat, repl, str string) string {
  385. ps := strings.SplitN(pat, "%", 2)
  386. if len(ps) != 2 {
  387. if str == pat {
  388. return repl
  389. }
  390. return str
  391. }
  392. in := str
  393. trimmed := str
  394. if ps[0] != "" {
  395. trimmed = strings.TrimPrefix(in, ps[0])
  396. if trimmed == in {
  397. return str
  398. }
  399. }
  400. in = trimmed
  401. if ps[1] != "" {
  402. trimmed = strings.TrimSuffix(in, ps[1])
  403. if trimmed == in {
  404. return str
  405. }
  406. }
  407. rs := strings.SplitN(repl, "%", 2)
  408. if len(rs) != 2 {
  409. return repl
  410. }
  411. return rs[0] + trimmed + rs[1]
  412. }
  413. // copied from build/kati/strutil.go
  414. func matchPattern(pat, str string) bool {
  415. i := strings.IndexByte(pat, '%')
  416. if i < 0 {
  417. return pat == str
  418. }
  419. return strings.HasPrefix(str, pat[:i]) && strings.HasSuffix(str, pat[i+1:])
  420. }
  421. var shlibVersionPattern = regexp.MustCompile("(?:\\.\\d+(?:svn)?)+")
  422. // splitFileExt splits a file name into root, suffix and ext. root stands for the file name without
  423. // the file extension and the version number (e.g. "libexample"). suffix stands for the
  424. // concatenation of the file extension and the version number (e.g. ".so.1.0"). ext stands for the
  425. // file extension after the version numbers are trimmed (e.g. ".so").
  426. func SplitFileExt(name string) (string, string, string) {
  427. // Extract and trim the shared lib version number if the file name ends with dot digits.
  428. suffix := ""
  429. matches := shlibVersionPattern.FindAllStringIndex(name, -1)
  430. if len(matches) > 0 {
  431. lastMatch := matches[len(matches)-1]
  432. if lastMatch[1] == len(name) {
  433. suffix = name[lastMatch[0]:lastMatch[1]]
  434. name = name[0:lastMatch[0]]
  435. }
  436. }
  437. // Extract the file name root and the file extension.
  438. ext := filepath.Ext(name)
  439. root := strings.TrimSuffix(name, ext)
  440. suffix = ext + suffix
  441. return root, suffix, ext
  442. }
  443. // ShardPaths takes a Paths, and returns a slice of Paths where each one has at most shardSize paths.
  444. func ShardPaths(paths Paths, shardSize int) []Paths {
  445. if len(paths) == 0 {
  446. return nil
  447. }
  448. ret := make([]Paths, 0, (len(paths)+shardSize-1)/shardSize)
  449. for len(paths) > shardSize {
  450. ret = append(ret, paths[0:shardSize])
  451. paths = paths[shardSize:]
  452. }
  453. if len(paths) > 0 {
  454. ret = append(ret, paths)
  455. }
  456. return ret
  457. }
  458. // ShardString takes a string and returns a slice of strings where the length of each one is
  459. // at most shardSize.
  460. func ShardString(s string, shardSize int) []string {
  461. if len(s) == 0 {
  462. return nil
  463. }
  464. ret := make([]string, 0, (len(s)+shardSize-1)/shardSize)
  465. for len(s) > shardSize {
  466. ret = append(ret, s[0:shardSize])
  467. s = s[shardSize:]
  468. }
  469. if len(s) > 0 {
  470. ret = append(ret, s)
  471. }
  472. return ret
  473. }
  474. // ShardStrings takes a slice of strings, and returns a slice of slices of strings where each one has at most shardSize
  475. // elements.
  476. func ShardStrings(s []string, shardSize int) [][]string {
  477. if len(s) == 0 {
  478. return nil
  479. }
  480. ret := make([][]string, 0, (len(s)+shardSize-1)/shardSize)
  481. for len(s) > shardSize {
  482. ret = append(ret, s[0:shardSize])
  483. s = s[shardSize:]
  484. }
  485. if len(s) > 0 {
  486. ret = append(ret, s)
  487. }
  488. return ret
  489. }
  490. // CheckDuplicate checks if there are duplicates in given string list.
  491. // If there are, it returns first such duplicate and true.
  492. func CheckDuplicate(values []string) (duplicate string, found bool) {
  493. seen := make(map[string]string)
  494. for _, v := range values {
  495. if duplicate, found = seen[v]; found {
  496. return duplicate, true
  497. }
  498. seen[v] = v
  499. }
  500. return "", false
  501. }