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 15package android 16 17import ( 18 "cmp" 19 "fmt" 20 "path/filepath" 21 "reflect" 22 "regexp" 23 "runtime" 24 "sort" 25 "strings" 26 "sync" 27 28 "github.com/google/blueprint/proptools" 29) 30 31// CopyOf returns a new slice that has the same contents as s. 32func CopyOf[T any](s []T) []T { 33 // If the input is nil, return nil and not an empty list 34 if s == nil { 35 return s 36 } 37 return append([]T{}, s...) 38} 39 40// Concat returns a new slice concatenated from the two input slices. It does not change the input 41// slices. 42func 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...) 46 return res 47} 48 49// 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 59// JoinWithPrefix prepends the prefix to each string in the list and 60// returns them joined together with " " as separator. 61func JoinWithPrefix(strs []string, prefix string) string { 62 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 { 68 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 { 80 if len(strs) == 0 { 81 return "" 82 } 83 84 // 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 91 var buf strings.Builder 92 buf.Grow(length) 93 buf.WriteString(prefix) 94 buf.WriteString(strs[0]) 95 buf.WriteString(suffix) 96 for i := 1; i < len(strs); i++ { 97 buf.WriteString(sep) 98 buf.WriteString(prefix) 99 buf.WriteString(strs[i]) 100 buf.WriteString(suffix) 101 } 102 return buf.String() 103} 104 105// SortedStringKeys returns the keys of the given map in the ascending order. 106// 107// Deprecated: Use SortedKeys instead. 108func SortedStringKeys[V any](m map[string]V) []string { 109 return SortedKeys(m) 110} 111 112// SortedKeys returns the keys of the given map in the ascending order. 113func SortedKeys[T cmp.Ordered, V any](m map[T]V) []T { 114 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 127// 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 158// IndexList returns the index of the first occurrence of the given string in the list or -1 159func IndexList[T comparable](t T, list []T) int { 160 for i, l := range list { 161 if l == t { 162 return i 163 } 164 } 165 return -1 166} 167 168func InList[T comparable](t T, list []T) bool { 169 return IndexList(t, list) != -1 170} 171 172func 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 180// 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 215// 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{} 222 m1 := setFromList(l1) 223 m2 := setFromList(l2) 224 for t := range m1 { 225 if _, ok := m2[t]; !ok { 226 diff1 = append(diff1, t) 227 listsDiffer = true 228 } 229 } 230 for t := range m2 { 231 if _, ok := m1[t]; !ok { 232 diff2 = append(diff2, t) 233 listsDiffer = true 234 } 235 } 236 return listsDiffer, diff1, diff2 237} 238 239// Returns true if the two lists have common elements. 240func HasIntersection[T comparable](l1, l2 []T) bool { 241 _, a, b := ListSetDifference(l1, l2) 242 return len(a)+len(b) < len(setFromList(l1))+len(setFromList(l2)) 243} 244 245// Returns true if the given string s is prefixed with any string in the given prefix list. 246func HasAnyPrefix(s string, prefixList []string) bool { 247 for _, prefix := range prefixList { 248 if strings.HasPrefix(s, prefix) { 249 return true 250 } 251 } 252 return false 253} 254 255// Returns true if any string in the given list has the given substring. 256func SubstringInList(list []string, substr string) bool { 257 for _, s := range list { 258 if strings.Contains(s, substr) { 259 return true 260 } 261 } 262 return false 263} 264 265// Returns true if any string in the given list has the given prefix. 266func PrefixInList(list []string, prefix string) bool { 267 for _, s := range list { 268 if strings.HasPrefix(s, prefix) { 269 return true 270 } 271 } 272 return false 273} 274 275// Returns true if any string in the given list has the given suffix. 276func SuffixInList(list []string, suffix string) bool { 277 for _, s := range list { 278 if strings.HasSuffix(s, suffix) { 279 return true 280 } 281 } 282 return false 283} 284 285// IndexListPred returns the index of the element which in the given `list` satisfying the predicate, or -1 if there is no such element. 286func IndexListPred(pred func(s string) bool, list []string) int { 287 for i, l := range list { 288 if pred(l) { 289 return i 290 } 291 } 292 293 return -1 294} 295 296// FilterList divides the string list into two lists: one with the strings belonging 297// to the given filter list, and the other with the remaining ones 298func FilterList(list []string, filter []string) (remainder []string, filtered []string) { 299 // InList is O(n). May be worth using more efficient lookup for longer lists. 300 for _, l := range list { 301 if InList(l, filter) { 302 filtered = append(filtered, l) 303 } else { 304 remainder = append(remainder, l) 305 } 306 } 307 308 return 309} 310 311// FilterListPred returns the elements of the given list for which the predicate 312// returns true. Order is kept. 313func FilterListPred(list []string, pred func(s string) bool) (filtered []string) { 314 for _, l := range list { 315 if pred(l) { 316 filtered = append(filtered, l) 317 } 318 } 319 return 320} 321 322// RemoveListFromList removes the strings belonging to the filter list from the 323// given list and returns the result 324func RemoveListFromList(list []string, filter_out []string) (result []string) { 325 result = make([]string, 0, len(list)) 326 for _, l := range list { 327 if !InList(l, filter_out) { 328 result = append(result, l) 329 } 330 } 331 return 332} 333 334// RemoveFromList removes given string from the string list. 335func RemoveFromList(s string, list []string) (bool, []string) { 336 result := make([]string, 0, len(list)) 337 var removed bool 338 for _, item := range list { 339 if item != s { 340 result = append(result, item) 341 } else { 342 removed = true 343 } 344 } 345 return removed, result 346} 347 348// FirstUniqueFunc returns all unique elements of a slice, keeping the first copy of 349// each. It does not modify the input slice. The eq function should return true 350// if two elements can be considered equal. 351func FirstUniqueFunc[SortableList ~[]Sortable, Sortable any](list SortableList, eq func(a, b Sortable) bool) SortableList { 352 k := 0 353outer: 354 for i := 0; i < len(list); i++ { 355 for j := 0; j < k; j++ { 356 if eq(list[i], list[j]) { 357 continue outer 358 } 359 } 360 list[k] = list[i] 361 k++ 362 } 363 return list[:k] 364} 365 366// FirstUniqueStrings returns all unique elements of a slice of strings, keeping the first copy of 367// each. It does not modify the input slice. 368func FirstUniqueStrings(list []string) []string { 369 return firstUnique(list) 370} 371 372// firstUnique returns all unique elements of a slice, keeping the first copy of each. It 373// does not modify the input slice. 374func firstUnique[T comparable](slice []T) []T { 375 // Do not modify the input in-place, operate on a copy instead. 376 slice = CopyOf(slice) 377 return firstUniqueInPlace(slice) 378} 379 380// firstUniqueInPlace returns all unique elements of a slice, keeping the first copy of 381// each. It modifies the slice contents in place, and returns a subslice of the original 382// slice. 383func firstUniqueInPlace[T comparable](slice []T) []T { 384 // 128 was chosen based on BenchmarkFirstUniqueStrings results. 385 if len(slice) > 128 { 386 return firstUniqueMap(slice) 387 } 388 return firstUniqueList(slice) 389} 390 391// firstUniqueList is an implementation of firstUnique using an O(N^2) list comparison to look for 392// duplicates. 393func firstUniqueList[T any](in []T) []T { 394 writeIndex := 0 395outer: 396 for readIndex := 0; readIndex < len(in); readIndex++ { 397 for compareIndex := 0; compareIndex < writeIndex; compareIndex++ { 398 if interface{}(in[readIndex]) == interface{}(in[compareIndex]) { 399 // The value at readIndex already exists somewhere in the output region 400 // of the slice before writeIndex, skip it. 401 continue outer 402 } 403 } 404 if readIndex != writeIndex { 405 in[writeIndex] = in[readIndex] 406 } 407 writeIndex++ 408 } 409 return in[0:writeIndex] 410} 411 412// firstUniqueMap is an implementation of firstUnique using an O(N) hash set lookup to look for 413// duplicates. 414func firstUniqueMap[T comparable](in []T) []T { 415 writeIndex := 0 416 seen := make(map[T]bool, len(in)) 417 for readIndex := 0; readIndex < len(in); readIndex++ { 418 if _, exists := seen[in[readIndex]]; exists { 419 continue 420 } 421 seen[in[readIndex]] = true 422 if readIndex != writeIndex { 423 in[writeIndex] = in[readIndex] 424 } 425 writeIndex++ 426 } 427 return in[0:writeIndex] 428} 429 430// ReverseSliceInPlace reverses the elements of a slice in place and returns it. 431func ReverseSliceInPlace[T any](in []T) []T { 432 for i, j := 0, len(in)-1; i < j; i, j = i+1, j-1 { 433 in[i], in[j] = in[j], in[i] 434 } 435 return in 436} 437 438// ReverseSlice returns a copy of a slice in reverse order. 439func ReverseSlice[T any](in []T) []T { 440 if in == nil { 441 return in 442 } 443 out := make([]T, len(in)) 444 for i := 0; i < len(in); i++ { 445 out[i] = in[len(in)-1-i] 446 } 447 return out 448} 449 450// LastUniqueStrings returns all unique elements of a slice of strings, keeping the last copy of 451// each. It modifies the slice contents in place, and returns a subslice of the original slice. 452func LastUniqueStrings(list []string) []string { 453 totalSkip := 0 454 for i := len(list) - 1; i >= totalSkip; i-- { 455 skip := 0 456 for j := i - 1; j >= totalSkip; j-- { 457 if list[i] == list[j] { 458 skip++ 459 } else { 460 list[j+skip] = list[j] 461 } 462 } 463 totalSkip += skip 464 } 465 return list[totalSkip:] 466} 467 468// SortedUniqueStrings returns what the name says 469func SortedUniqueStrings(list []string) []string { 470 // FirstUniqueStrings creates a copy of `list`, so the input remains untouched. 471 unique := FirstUniqueStrings(list) 472 sort.Strings(unique) 473 return unique 474} 475 476// checkCalledFromInit panics if a Go package's init function is not on the 477// call stack. 478func checkCalledFromInit() { 479 for skip := 3; ; skip++ { 480 _, funcName, ok := callerName(skip) 481 if !ok { 482 panic("not called from an init func") 483 } 484 485 if funcName == "init" || strings.HasPrefix(funcName, "init·") || 486 strings.HasPrefix(funcName, "init.") { 487 return 488 } 489 } 490} 491 492// A regex to find a package path within a function name. It finds the shortest string that is 493// followed by '.' and doesn't have any '/'s left. 494var pkgPathRe = regexp.MustCompile(`^(.*?)\.([^/]+)$`) 495 496// callerName returns the package path and function name of the calling 497// function. The skip argument has the same meaning as the skip argument of 498// runtime.Callers. 499func callerName(skip int) (pkgPath, funcName string, ok bool) { 500 var pc [1]uintptr 501 n := runtime.Callers(skip+1, pc[:]) 502 if n != 1 { 503 return "", "", false 504 } 505 506 f := runtime.FuncForPC(pc[0]).Name() 507 s := pkgPathRe.FindStringSubmatch(f) 508 if len(s) < 3 { 509 panic(fmt.Errorf("failed to extract package path and function name from %q", f)) 510 } 511 512 return s[1], s[2], true 513} 514 515// GetNumericSdkVersion removes the first occurrence of system_ in a string, 516// which is assumed to be something like "system_1.2.3" 517func GetNumericSdkVersion(v string) string { 518 return strings.Replace(v, "system_", "", 1) 519} 520 521// copied from build/kati/strutil.go 522func substPattern(pat, repl, str string) string { 523 ps := strings.SplitN(pat, "%", 2) 524 if len(ps) != 2 { 525 if str == pat { 526 return repl 527 } 528 return str 529 } 530 in := str 531 trimmed := str 532 if ps[0] != "" { 533 trimmed = strings.TrimPrefix(in, ps[0]) 534 if trimmed == in { 535 return str 536 } 537 } 538 in = trimmed 539 if ps[1] != "" { 540 trimmed = strings.TrimSuffix(in, ps[1]) 541 if trimmed == in { 542 return str 543 } 544 } 545 546 rs := strings.SplitN(repl, "%", 2) 547 if len(rs) != 2 { 548 return repl 549 } 550 return rs[0] + trimmed + rs[1] 551} 552 553// copied from build/kati/strutil.go 554func matchPattern(pat, str string) bool { 555 i := strings.IndexByte(pat, '%') 556 if i < 0 { 557 return pat == str 558 } 559 return strings.HasPrefix(str, pat[:i]) && strings.HasSuffix(str, pat[i+1:]) 560} 561 562var shlibVersionPattern = regexp.MustCompile("(?:\\.\\d+(?:svn)?)+") 563 564// splitFileExt splits a file name into root, suffix and ext. root stands for the file name without 565// the file extension and the version number (e.g. "libexample"). suffix stands for the 566// concatenation of the file extension and the version number (e.g. ".so.1.0"). ext stands for the 567// file extension after the version numbers are trimmed (e.g. ".so"). 568func SplitFileExt(name string) (string, string, string) { 569 // Extract and trim the shared lib version number if the file name ends with dot digits. 570 suffix := "" 571 matches := shlibVersionPattern.FindAllStringIndex(name, -1) 572 if len(matches) > 0 { 573 lastMatch := matches[len(matches)-1] 574 if lastMatch[1] == len(name) { 575 suffix = name[lastMatch[0]:lastMatch[1]] 576 name = name[0:lastMatch[0]] 577 } 578 } 579 580 // Extract the file name root and the file extension. 581 ext := filepath.Ext(name) 582 root := strings.TrimSuffix(name, ext) 583 suffix = ext + suffix 584 585 return root, suffix, ext 586} 587 588// ShardPaths takes a Paths, and returns a slice of Paths where each one has at most shardSize paths. 589func ShardPaths(paths Paths, shardSize int) []Paths { 590 return proptools.ShardBySize(paths, shardSize) 591} 592 593// ShardString takes a string and returns a slice of strings where the length of each one is 594// at most shardSize. 595func ShardString(s string, shardSize int) []string { 596 if len(s) == 0 { 597 return nil 598 } 599 ret := make([]string, 0, (len(s)+shardSize-1)/shardSize) 600 for len(s) > shardSize { 601 ret = append(ret, s[0:shardSize]) 602 s = s[shardSize:] 603 } 604 if len(s) > 0 { 605 ret = append(ret, s) 606 } 607 return ret 608} 609 610// ShardStrings takes a slice of strings, and returns a slice of slices of strings where each one has at most shardSize 611// elements. 612func ShardStrings(s []string, shardSize int) [][]string { 613 return proptools.ShardBySize(s, shardSize) 614} 615 616// CheckDuplicate checks if there are duplicates in given string list. 617// If there are, it returns first such duplicate and true. 618func CheckDuplicate(values []string) (duplicate string, found bool) { 619 seen := make(map[string]string) 620 for _, v := range values { 621 if duplicate, found = seen[v]; found { 622 return duplicate, true 623 } 624 seen[v] = v 625 } 626 return "", false 627} 628 629func AddToStringSet(set map[string]bool, items []string) { 630 for _, item := range items { 631 set[item] = true 632 } 633} 634 635// SyncMap is a wrapper around sync.Map that provides type safety via generics. 636type SyncMap[K comparable, V any] struct { 637 sync.Map 638} 639 640// Load returns the value stored in the map for a key, or the zero value if no 641// value is present. 642// The ok result indicates whether value was found in the map. 643func (m *SyncMap[K, V]) Load(key K) (value V, ok bool) { 644 v, ok := m.Map.Load(key) 645 if !ok { 646 return *new(V), false 647 } 648 return v.(V), true 649} 650 651// Store sets the value for a key. 652func (m *SyncMap[K, V]) Store(key K, value V) { 653 m.Map.Store(key, value) 654} 655 656// LoadOrStore returns the existing value for the key if present. 657// Otherwise, it stores and returns the given value. 658// The loaded result is true if the value was loaded, false if stored. 659func (m *SyncMap[K, V]) LoadOrStore(key K, value V) (actual V, loaded bool) { 660 v, loaded := m.Map.LoadOrStore(key, value) 661 return v.(V), loaded 662} 663 664// AppendIfNotZero append the given value to the slice if it is not the zero value 665// for its type. 666func AppendIfNotZero[T comparable](slice []T, value T) []T { 667 var zeroValue T // Get the zero value of the type T 668 if value != zeroValue { 669 return append(slice, value) 670 } 671 return slice 672} 673