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	"fmt"
19	"path/filepath"
20	"reflect"
21	"regexp"
22	"runtime"
23	"sort"
24	"strings"
25)
26
27// 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
32func JoinWithPrefix(strs []string, prefix string) string {
33	if len(strs) == 0 {
34		return ""
35	}
36
37	if len(strs) == 1 {
38		return prefix + strs[0]
39	}
40
41	n := len(" ") * (len(strs) - 1)
42	for _, s := range strs {
43		n += len(prefix) + len(s)
44	}
45
46	ret := make([]byte, 0, n)
47	for i, s := range strs {
48		if i != 0 {
49			ret = append(ret, ' ')
50		}
51		ret = append(ret, prefix...)
52		ret = append(ret, s...)
53	}
54	return string(ret)
55}
56
57func JoinWithSuffix(strs []string, suffix string, separator string) string {
58	if len(strs) == 0 {
59		return ""
60	}
61
62	if len(strs) == 1 {
63		return strs[0] + suffix
64	}
65
66	n := len(" ") * (len(strs) - 1)
67	for _, s := range strs {
68		n += len(suffix) + len(s)
69	}
70
71	ret := make([]byte, 0, n)
72	for i, s := range strs {
73		if i != 0 {
74			ret = append(ret, separator...)
75		}
76		ret = append(ret, s...)
77		ret = append(ret, suffix...)
78	}
79	return string(ret)
80}
81
82func SortedStringKeys(m interface{}) []string {
83	v := reflect.ValueOf(m)
84	if v.Kind() != reflect.Map {
85		panic(fmt.Sprintf("%#v is not a map", m))
86	}
87	keys := v.MapKeys()
88	s := make([]string, 0, len(keys))
89	for _, key := range keys {
90		s = append(s, key.String())
91	}
92	sort.Strings(s)
93	return s
94}
95
96func SortedStringMapValues(m interface{}) []string {
97	v := reflect.ValueOf(m)
98	if v.Kind() != reflect.Map {
99		panic(fmt.Sprintf("%#v is not a map", m))
100	}
101	keys := v.MapKeys()
102	s := make([]string, 0, len(keys))
103	for _, key := range keys {
104		s = append(s, v.MapIndex(key).String())
105	}
106	sort.Strings(s)
107	return s
108}
109
110func IndexList(s string, list []string) int {
111	for i, l := range list {
112		if l == s {
113			return i
114		}
115	}
116
117	return -1
118}
119
120func InList(s string, list []string) bool {
121	return IndexList(s, list) != -1
122}
123
124// Returns true if the given string s is prefixed with any string in the given prefix list.
125func HasAnyPrefix(s string, prefixList []string) bool {
126	for _, prefix := range prefixList {
127		if strings.HasPrefix(s, prefix) {
128			return true
129		}
130	}
131	return false
132}
133
134// Returns true if any string in the given list has the given prefix.
135func PrefixInList(list []string, prefix string) bool {
136	for _, s := range list {
137		if strings.HasPrefix(s, prefix) {
138			return true
139		}
140	}
141	return false
142}
143
144// Returns true if any string in the given list has the given suffix.
145func SuffixInList(list []string, suffix string) bool {
146	for _, s := range list {
147		if strings.HasSuffix(s, suffix) {
148			return true
149		}
150	}
151	return false
152}
153
154// IndexListPred returns the index of the element which in the given `list` satisfying the predicate, or -1 if there is no such element.
155func IndexListPred(pred func(s string) bool, list []string) int {
156	for i, l := range list {
157		if pred(l) {
158			return i
159		}
160	}
161
162	return -1
163}
164
165func FilterList(list []string, filter []string) (remainder []string, filtered []string) {
166	for _, l := range list {
167		if InList(l, filter) {
168			filtered = append(filtered, l)
169		} else {
170			remainder = append(remainder, l)
171		}
172	}
173
174	return
175}
176
177func RemoveListFromList(list []string, filter_out []string) (result []string) {
178	result = make([]string, 0, len(list))
179	for _, l := range list {
180		if !InList(l, filter_out) {
181			result = append(result, l)
182		}
183	}
184	return
185}
186
187func RemoveFromList(s string, list []string) (bool, []string) {
188	i := IndexList(s, list)
189	if i == -1 {
190		return false, list
191	}
192
193	result := make([]string, 0, len(list)-1)
194	result = append(result, list[:i]...)
195	for _, l := range list[i+1:] {
196		if l != s {
197			result = append(result, l)
198		}
199	}
200	return true, result
201}
202
203// FirstUniqueStrings returns all unique elements of a slice of strings, keeping the first copy of
204// each.  It modifies the slice contents in place, and returns a subslice of the original slice.
205func FirstUniqueStrings(list []string) []string {
206	// 128 was chosen based on BenchmarkFirstUniqueStrings results.
207	if len(list) > 128 {
208		return firstUniqueStringsMap(list)
209	}
210	return firstUniqueStringsList(list)
211}
212
213func firstUniqueStringsList(list []string) []string {
214	k := 0
215outer:
216	for i := 0; i < len(list); i++ {
217		for j := 0; j < k; j++ {
218			if list[i] == list[j] {
219				continue outer
220			}
221		}
222		list[k] = list[i]
223		k++
224	}
225	return list[:k]
226}
227
228func firstUniqueStringsMap(list []string) []string {
229	k := 0
230	seen := make(map[string]bool, len(list))
231	for i := 0; i < len(list); i++ {
232		if seen[list[i]] {
233			continue
234		}
235		seen[list[i]] = true
236		list[k] = list[i]
237		k++
238	}
239	return list[:k]
240}
241
242// LastUniqueStrings returns all unique elements of a slice of strings, keeping the last copy of
243// each.  It modifies the slice contents in place, and returns a subslice of the original slice.
244func LastUniqueStrings(list []string) []string {
245	totalSkip := 0
246	for i := len(list) - 1; i >= totalSkip; i-- {
247		skip := 0
248		for j := i - 1; j >= totalSkip; j-- {
249			if list[i] == list[j] {
250				skip++
251			} else {
252				list[j+skip] = list[j]
253			}
254		}
255		totalSkip += skip
256	}
257	return list[totalSkip:]
258}
259
260// SortedUniqueStrings returns what the name says
261func SortedUniqueStrings(list []string) []string {
262	unique := FirstUniqueStrings(list)
263	sort.Strings(unique)
264	return unique
265}
266
267// checkCalledFromInit panics if a Go package's init function is not on the
268// call stack.
269func checkCalledFromInit() {
270	for skip := 3; ; skip++ {
271		_, funcName, ok := callerName(skip)
272		if !ok {
273			panic("not called from an init func")
274		}
275
276		if funcName == "init" || strings.HasPrefix(funcName, "init·") ||
277			strings.HasPrefix(funcName, "init.") {
278			return
279		}
280	}
281}
282
283// A regex to find a package path within a function name. It finds the shortest string that is
284// followed by '.' and doesn't have any '/'s left.
285var pkgPathRe = regexp.MustCompile(`^(.*?)\.([^/]+)$`)
286
287// callerName returns the package path and function name of the calling
288// function.  The skip argument has the same meaning as the skip argument of
289// runtime.Callers.
290func callerName(skip int) (pkgPath, funcName string, ok bool) {
291	var pc [1]uintptr
292	n := runtime.Callers(skip+1, pc[:])
293	if n != 1 {
294		return "", "", false
295	}
296
297	f := runtime.FuncForPC(pc[0]).Name()
298	s := pkgPathRe.FindStringSubmatch(f)
299	if len(s) < 3 {
300		panic(fmt.Errorf("failed to extract package path and function name from %q", f))
301	}
302
303	return s[1], s[2], true
304}
305
306func GetNumericSdkVersion(v string) string {
307	if strings.Contains(v, "system_") {
308		return strings.Replace(v, "system_", "", 1)
309	}
310	return v
311}
312
313// copied from build/kati/strutil.go
314func substPattern(pat, repl, str string) string {
315	ps := strings.SplitN(pat, "%", 2)
316	if len(ps) != 2 {
317		if str == pat {
318			return repl
319		}
320		return str
321	}
322	in := str
323	trimed := str
324	if ps[0] != "" {
325		trimed = strings.TrimPrefix(in, ps[0])
326		if trimed == in {
327			return str
328		}
329	}
330	in = trimed
331	if ps[1] != "" {
332		trimed = strings.TrimSuffix(in, ps[1])
333		if trimed == in {
334			return str
335		}
336	}
337
338	rs := strings.SplitN(repl, "%", 2)
339	if len(rs) != 2 {
340		return repl
341	}
342	return rs[0] + trimed + rs[1]
343}
344
345// copied from build/kati/strutil.go
346func matchPattern(pat, str string) bool {
347	i := strings.IndexByte(pat, '%')
348	if i < 0 {
349		return pat == str
350	}
351	return strings.HasPrefix(str, pat[:i]) && strings.HasSuffix(str, pat[i+1:])
352}
353
354var shlibVersionPattern = regexp.MustCompile("(?:\\.\\d+(?:svn)?)+")
355
356// splitFileExt splits a file name into root, suffix and ext. root stands for the file name without
357// the file extension and the version number (e.g. "libexample"). suffix stands for the
358// concatenation of the file extension and the version number (e.g. ".so.1.0"). ext stands for the
359// file extension after the version numbers are trimmed (e.g. ".so").
360func SplitFileExt(name string) (string, string, string) {
361	// Extract and trim the shared lib version number if the file name ends with dot digits.
362	suffix := ""
363	matches := shlibVersionPattern.FindAllStringIndex(name, -1)
364	if len(matches) > 0 {
365		lastMatch := matches[len(matches)-1]
366		if lastMatch[1] == len(name) {
367			suffix = name[lastMatch[0]:lastMatch[1]]
368			name = name[0:lastMatch[0]]
369		}
370	}
371
372	// Extract the file name root and the file extension.
373	ext := filepath.Ext(name)
374	root := strings.TrimSuffix(name, ext)
375	suffix = ext + suffix
376
377	return root, suffix, ext
378}
379
380// ShardPaths takes a Paths, and returns a slice of Paths where each one has at most shardSize paths.
381func ShardPaths(paths Paths, shardSize int) []Paths {
382	if len(paths) == 0 {
383		return nil
384	}
385	ret := make([]Paths, 0, (len(paths)+shardSize-1)/shardSize)
386	for len(paths) > shardSize {
387		ret = append(ret, paths[0:shardSize])
388		paths = paths[shardSize:]
389	}
390	if len(paths) > 0 {
391		ret = append(ret, paths)
392	}
393	return ret
394}
395
396// ShardStrings takes a slice of strings, and returns a slice of slices of strings where each one has at most shardSize
397// elements.
398func ShardStrings(s []string, shardSize int) [][]string {
399	if len(s) == 0 {
400		return nil
401	}
402	ret := make([][]string, 0, (len(s)+shardSize-1)/shardSize)
403	for len(s) > shardSize {
404		ret = append(ret, s[0:shardSize])
405		s = s[shardSize:]
406	}
407	if len(s) > 0 {
408		ret = append(ret, s)
409	}
410	return ret
411}
412
413func CheckDuplicate(values []string) (duplicate string, found bool) {
414	seen := make(map[string]string)
415	for _, v := range values {
416		if duplicate, found = seen[v]; found {
417			return
418		}
419		seen[v] = v
420	}
421	return
422}
423