summaryrefslogtreecommitdiff
path: root/android
diff options
context:
space:
mode:
author Colin Cross <ccross@android.com> 2019-02-15 23:03:34 -0800
committer Colin Cross <ccross@android.com> 2019-02-19 11:19:09 -0800
commit454c087be64de626ce3a3ceac6f2aacef85e59ea (patch)
treeb6e71f93ee2e348cca6e0c0371b7152139702385 /android
parentd7cfaeeebc3a28077deeceec3ec6e0b81bec058a (diff)
Add CopyOf utility method
Add a utility method that returns a copy of a slice of strings. This is primarily useful when appending to a string slice to avoid accidentally reusing the backing array. Test: util_test.go Change-Id: I7801fc7ca19e27ddc9f1b1b452788b723c7f619c
Diffstat (limited to 'android')
-rw-r--r--android/util.go5
-rw-r--r--android/util_test.go45
2 files changed, 50 insertions, 0 deletions
diff --git a/android/util.go b/android/util.go
index 92ab845ba..8fc159dc8 100644
--- a/android/util.go
+++ b/android/util.go
@@ -20,6 +20,11 @@ import (
"strings"
)
+// CopyOf returns a new slice that has the same contents as s.
+func CopyOf(s []string) []string {
+ return append([]string(nil), s...)
+}
+
func JoinWithPrefix(strs []string, prefix string) string {
if len(strs) == 0 {
return ""
diff --git a/android/util_test.go b/android/util_test.go
index 1c791b240..2e5eb07ee 100644
--- a/android/util_test.go
+++ b/android/util_test.go
@@ -15,6 +15,7 @@
package android
import (
+ "fmt"
"reflect"
"testing"
)
@@ -359,3 +360,47 @@ func TestRemoveFromList(t *testing.T) {
})
}
}
+
+func ExampleCopyOf() {
+ a := []string{"1", "2", "3"}
+ b := CopyOf(a)
+ a[0] = "-1"
+ fmt.Printf("a = %q\n", a)
+ fmt.Printf("b = %q\n", b)
+
+ // Output:
+ // a = ["-1" "2" "3"]
+ // b = ["1" "2" "3"]
+}
+
+func ExampleCopyOf_append() {
+ a := make([]string, 1, 2)
+ a[0] = "foo"
+
+ fmt.Println("Without CopyOf:")
+ b := append(a, "bar")
+ c := append(a, "baz")
+ fmt.Printf("a = %q\n", a)
+ fmt.Printf("b = %q\n", b)
+ fmt.Printf("c = %q\n", c)
+
+ a = make([]string, 1, 2)
+ a[0] = "foo"
+
+ fmt.Println("With CopyOf:")
+ b = append(CopyOf(a), "bar")
+ c = append(CopyOf(a), "baz")
+ fmt.Printf("a = %q\n", a)
+ fmt.Printf("b = %q\n", b)
+ fmt.Printf("c = %q\n", c)
+
+ // Output:
+ // Without CopyOf:
+ // a = ["foo"]
+ // b = ["foo" "baz"]
+ // c = ["foo" "baz"]
+ // With CopyOf:
+ // a = ["foo"]
+ // b = ["foo" "bar"]
+ // c = ["foo" "baz"]
+}