Donate to e Foundation | Murena handsets with /e/OS | Own a part of Murena! Learn more

Commit 454c087b authored by Colin Cross's avatar Colin Cross
Browse files

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
parent d7cfaeee
Loading
Loading
Loading
Loading
+5 −0
Original line number Diff line number Diff line
@@ -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 ""
+45 −0
Original line number Diff line number Diff line
@@ -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"]
}
+1 −3
Original line number Diff line number Diff line
@@ -578,9 +578,7 @@ func replace(l []string, from, to string) {
	}
}

func copyOf(l []string) []string {
	return append([]string(nil), l...)
}
var copyOf = android.CopyOf

func anyHavePrefix(l []string, prefix string) bool {
	for _, x := range l {