]> Cypherpunks repositories - gostls13.git/commitdiff
bytes: add ContainsAny
authorRob Pike <r@golang.org>
Tue, 5 Apr 2016 22:43:07 +0000 (15:43 -0700)
committerRob Pike <r@golang.org>
Wed, 6 Apr 2016 21:17:08 +0000 (21:17 +0000)
This function is present in the strings package but missing from bytes,
and we would like to keep the two packages consistent.

Add it to bytes, and copy the test over as well.

Fixes #15140

Change-Id: I5dbd28da83a9fe741885794ed15f2af2f826cb3c
Reviewed-on: https://go-review.googlesource.com/21562
Reviewed-by: Brad Fitzpatrick <bradfitz@golang.org>
src/bytes/bytes.go
src/bytes/bytes_test.go

index 8a4409cb6b66aeb222efef0c56a50d10a974505c..698d881c9dd2439367a799ed1cf6f365e821de2d 100644 (file)
@@ -83,6 +83,11 @@ func Contains(b, subslice []byte) bool {
        return Index(b, subslice) != -1
 }
 
+// ContainsAny reports whether any of the UTF-8-encoded Unicode code points in chars are within b.
+func ContainsAny(b []byte, chars string) bool {
+       return IndexAny(b, chars) >= 0
+}
+
 // Index returns the index of the first instance of sep in s, or -1 if sep is not present in s.
 func Index(s, sep []byte) int {
        n := len(sep)
index 1be29d6cc6d10fe99bb59af14486374a4197f07a..40e8d09b59eb65eddb66bcf962eca9384399ac06 100644 (file)
@@ -1218,6 +1218,33 @@ func TestContains(t *testing.T) {
        }
 }
 
+var ContainsAnyTests = []struct {
+       b        []byte
+       substr   string
+       expected bool
+}{
+       {[]byte(""), "", false},
+       {[]byte(""), "a", false},
+       {[]byte(""), "abc", false},
+       {[]byte("a"), "", false},
+       {[]byte("a"), "a", true},
+       {[]byte("aaa"), "a", true},
+       {[]byte("abc"), "xyz", false},
+       {[]byte("abc"), "xcz", true},
+       {[]byte("a☺b☻c☹d"), "uvw☻xyz", true},
+       {[]byte("aRegExp*"), ".(|)*+?^$[]", true},
+       {[]byte(dots + dots + dots), " ", false},
+}
+
+func TestContainsAny(t *testing.T) {
+       for _, ct := range ContainsAnyTests {
+               if ContainsAny(ct.b, ct.substr) != ct.expected {
+                       t.Errorf("ContainsAny(%s, %s) = %v, want %v",
+                               ct.b, ct.substr, !ct.expected, ct.expected)
+               }
+       }
+}
+
 var makeFieldsInput = func() []byte {
        x := make([]byte, 1<<20)
        // Input is ~10% space, ~10% 2-byte UTF-8, rest ASCII non-space.