util.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559
  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[T any](s []T) []T {
  26. // If the input is nil, return nil and not an empty list
  27. if s == nil {
  28. return s
  29. }
  30. return append([]T{}, 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 does not modify the input slice.
  252. func FirstUniqueStrings(list []string) []string {
  253. return firstUnique(list)
  254. }
  255. // firstUnique returns all unique elements of a slice, keeping the first copy of each. It
  256. // does not modify the input slice.
  257. func firstUnique[T comparable](slice []T) []T {
  258. // Do not modify the input in-place, operate on a copy instead.
  259. slice = CopyOf(slice)
  260. return firstUniqueInPlace(slice)
  261. }
  262. // firstUniqueInPlace returns all unique elements of a slice, keeping the first copy of
  263. // each. It modifies the slice contents in place, and returns a subslice of the original
  264. // slice.
  265. func firstUniqueInPlace[T comparable](slice []T) []T {
  266. // 128 was chosen based on BenchmarkFirstUniqueStrings results.
  267. if len(slice) > 128 {
  268. return firstUniqueMap(slice)
  269. }
  270. return firstUniqueList(slice)
  271. }
  272. // firstUniqueList is an implementation of firstUnique using an O(N^2) list comparison to look for
  273. // duplicates.
  274. func firstUniqueList[T any](in []T) []T {
  275. writeIndex := 0
  276. outer:
  277. for readIndex := 0; readIndex < len(in); readIndex++ {
  278. for compareIndex := 0; compareIndex < writeIndex; compareIndex++ {
  279. if interface{}(in[readIndex]) == interface{}(in[compareIndex]) {
  280. // The value at readIndex already exists somewhere in the output region
  281. // of the slice before writeIndex, skip it.
  282. continue outer
  283. }
  284. }
  285. if readIndex != writeIndex {
  286. in[writeIndex] = in[readIndex]
  287. }
  288. writeIndex++
  289. }
  290. return in[0:writeIndex]
  291. }
  292. // firstUniqueMap is an implementation of firstUnique using an O(N) hash set lookup to look for
  293. // duplicates.
  294. func firstUniqueMap[T comparable](in []T) []T {
  295. writeIndex := 0
  296. seen := make(map[T]bool, len(in))
  297. for readIndex := 0; readIndex < len(in); readIndex++ {
  298. if _, exists := seen[in[readIndex]]; exists {
  299. continue
  300. }
  301. seen[in[readIndex]] = true
  302. if readIndex != writeIndex {
  303. in[writeIndex] = in[readIndex]
  304. }
  305. writeIndex++
  306. }
  307. return in[0:writeIndex]
  308. }
  309. // reverseSliceInPlace reverses the elements of a slice in place.
  310. func reverseSliceInPlace[T any](in []T) {
  311. for i, j := 0, len(in)-1; i < j; i, j = i+1, j-1 {
  312. in[i], in[j] = in[j], in[i]
  313. }
  314. }
  315. // reverseSlice returns a copy of a slice in reverse order.
  316. func reverseSlice[T any](in []T) []T {
  317. out := make([]T, len(in))
  318. for i := 0; i < len(in); i++ {
  319. out[i] = in[len(in)-1-i]
  320. }
  321. return out
  322. }
  323. // LastUniqueStrings returns all unique elements of a slice of strings, keeping the last copy of
  324. // each. It modifies the slice contents in place, and returns a subslice of the original slice.
  325. func LastUniqueStrings(list []string) []string {
  326. totalSkip := 0
  327. for i := len(list) - 1; i >= totalSkip; i-- {
  328. skip := 0
  329. for j := i - 1; j >= totalSkip; j-- {
  330. if list[i] == list[j] {
  331. skip++
  332. } else {
  333. list[j+skip] = list[j]
  334. }
  335. }
  336. totalSkip += skip
  337. }
  338. return list[totalSkip:]
  339. }
  340. // SortedUniqueStrings returns what the name says
  341. func SortedUniqueStrings(list []string) []string {
  342. // FirstUniqueStrings creates a copy of `list`, so the input remains untouched.
  343. unique := FirstUniqueStrings(list)
  344. sort.Strings(unique)
  345. return unique
  346. }
  347. // checkCalledFromInit panics if a Go package's init function is not on the
  348. // call stack.
  349. func checkCalledFromInit() {
  350. for skip := 3; ; skip++ {
  351. _, funcName, ok := callerName(skip)
  352. if !ok {
  353. panic("not called from an init func")
  354. }
  355. if funcName == "init" || strings.HasPrefix(funcName, "init·") ||
  356. strings.HasPrefix(funcName, "init.") {
  357. return
  358. }
  359. }
  360. }
  361. // A regex to find a package path within a function name. It finds the shortest string that is
  362. // followed by '.' and doesn't have any '/'s left.
  363. var pkgPathRe = regexp.MustCompile(`^(.*?)\.([^/]+)$`)
  364. // callerName returns the package path and function name of the calling
  365. // function. The skip argument has the same meaning as the skip argument of
  366. // runtime.Callers.
  367. func callerName(skip int) (pkgPath, funcName string, ok bool) {
  368. var pc [1]uintptr
  369. n := runtime.Callers(skip+1, pc[:])
  370. if n != 1 {
  371. return "", "", false
  372. }
  373. f := runtime.FuncForPC(pc[0]).Name()
  374. s := pkgPathRe.FindStringSubmatch(f)
  375. if len(s) < 3 {
  376. panic(fmt.Errorf("failed to extract package path and function name from %q", f))
  377. }
  378. return s[1], s[2], true
  379. }
  380. // GetNumericSdkVersion removes the first occurrence of system_ in a string,
  381. // which is assumed to be something like "system_1.2.3"
  382. func GetNumericSdkVersion(v string) string {
  383. return strings.Replace(v, "system_", "", 1)
  384. }
  385. // copied from build/kati/strutil.go
  386. func substPattern(pat, repl, str string) string {
  387. ps := strings.SplitN(pat, "%", 2)
  388. if len(ps) != 2 {
  389. if str == pat {
  390. return repl
  391. }
  392. return str
  393. }
  394. in := str
  395. trimmed := str
  396. if ps[0] != "" {
  397. trimmed = strings.TrimPrefix(in, ps[0])
  398. if trimmed == in {
  399. return str
  400. }
  401. }
  402. in = trimmed
  403. if ps[1] != "" {
  404. trimmed = strings.TrimSuffix(in, ps[1])
  405. if trimmed == in {
  406. return str
  407. }
  408. }
  409. rs := strings.SplitN(repl, "%", 2)
  410. if len(rs) != 2 {
  411. return repl
  412. }
  413. return rs[0] + trimmed + rs[1]
  414. }
  415. // copied from build/kati/strutil.go
  416. func matchPattern(pat, str string) bool {
  417. i := strings.IndexByte(pat, '%')
  418. if i < 0 {
  419. return pat == str
  420. }
  421. return strings.HasPrefix(str, pat[:i]) && strings.HasSuffix(str, pat[i+1:])
  422. }
  423. var shlibVersionPattern = regexp.MustCompile("(?:\\.\\d+(?:svn)?)+")
  424. // splitFileExt splits a file name into root, suffix and ext. root stands for the file name without
  425. // the file extension and the version number (e.g. "libexample"). suffix stands for the
  426. // concatenation of the file extension and the version number (e.g. ".so.1.0"). ext stands for the
  427. // file extension after the version numbers are trimmed (e.g. ".so").
  428. func SplitFileExt(name string) (string, string, string) {
  429. // Extract and trim the shared lib version number if the file name ends with dot digits.
  430. suffix := ""
  431. matches := shlibVersionPattern.FindAllStringIndex(name, -1)
  432. if len(matches) > 0 {
  433. lastMatch := matches[len(matches)-1]
  434. if lastMatch[1] == len(name) {
  435. suffix = name[lastMatch[0]:lastMatch[1]]
  436. name = name[0:lastMatch[0]]
  437. }
  438. }
  439. // Extract the file name root and the file extension.
  440. ext := filepath.Ext(name)
  441. root := strings.TrimSuffix(name, ext)
  442. suffix = ext + suffix
  443. return root, suffix, ext
  444. }
  445. // ShardPaths takes a Paths, and returns a slice of Paths where each one has at most shardSize paths.
  446. func ShardPaths(paths Paths, shardSize int) []Paths {
  447. if len(paths) == 0 {
  448. return nil
  449. }
  450. ret := make([]Paths, 0, (len(paths)+shardSize-1)/shardSize)
  451. for len(paths) > shardSize {
  452. ret = append(ret, paths[0:shardSize])
  453. paths = paths[shardSize:]
  454. }
  455. if len(paths) > 0 {
  456. ret = append(ret, paths)
  457. }
  458. return ret
  459. }
  460. // ShardString takes a string and returns a slice of strings where the length of each one is
  461. // at most shardSize.
  462. func ShardString(s string, shardSize int) []string {
  463. if len(s) == 0 {
  464. return nil
  465. }
  466. ret := make([]string, 0, (len(s)+shardSize-1)/shardSize)
  467. for len(s) > shardSize {
  468. ret = append(ret, s[0:shardSize])
  469. s = s[shardSize:]
  470. }
  471. if len(s) > 0 {
  472. ret = append(ret, s)
  473. }
  474. return ret
  475. }
  476. // ShardStrings takes a slice of strings, and returns a slice of slices of strings where each one has at most shardSize
  477. // elements.
  478. func ShardStrings(s []string, shardSize int) [][]string {
  479. if len(s) == 0 {
  480. return nil
  481. }
  482. ret := make([][]string, 0, (len(s)+shardSize-1)/shardSize)
  483. for len(s) > shardSize {
  484. ret = append(ret, s[0:shardSize])
  485. s = s[shardSize:]
  486. }
  487. if len(s) > 0 {
  488. ret = append(ret, s)
  489. }
  490. return ret
  491. }
  492. // CheckDuplicate checks if there are duplicates in given string list.
  493. // If there are, it returns first such duplicate and true.
  494. func CheckDuplicate(values []string) (duplicate string, found bool) {
  495. seen := make(map[string]string)
  496. for _, v := range values {
  497. if duplicate, found = seen[v]; found {
  498. return duplicate, true
  499. }
  500. seen[v] = v
  501. }
  502. return "", false
  503. }