1
0
mirror of https://github.com/golang/go synced 2024-11-22 03:54:39 -07:00

bytes: document Compare/Equal semantics for nil arguments, and add tests.

R=golang-dev, bradfitz, r, r
CC=golang-dev
https://golang.org/cl/5676090
This commit is contained in:
David Symonds 2012-02-18 17:39:40 +11:00
parent f18b0b0c16
commit 85f2d18a72
2 changed files with 26 additions and 17 deletions

View File

@ -13,6 +13,7 @@ import (
// Compare returns an integer comparing the two byte arrays lexicographically. // Compare returns an integer comparing the two byte arrays lexicographically.
// The result will be 0 if a==b, -1 if a < b, and +1 if a > b // The result will be 0 if a==b, -1 if a < b, and +1 if a > b
// A nil argument is equivalent to an empty slice.
func Compare(a, b []byte) int { func Compare(a, b []byte) int {
m := len(a) m := len(a)
if m > len(b) { if m > len(b) {
@ -37,6 +38,7 @@ func Compare(a, b []byte) int {
} }
// Equal returns a boolean reporting whether a == b. // Equal returns a boolean reporting whether a == b.
// A nil argument is equivalent to an empty slice.
func Equal(a, b []byte) bool func Equal(a, b []byte) bool
func equalPortable(a, b []byte) bool { func equalPortable(a, b []byte) bool {

View File

@ -46,32 +46,39 @@ type BinOpTest struct {
i int i int
} }
var comparetests = []BinOpTest{ var compareTests = []struct {
{"", "", 0}, a, b []byte
{"a", "", 1}, i int
{"", "a", -1}, }{
{"abc", "abc", 0}, {[]byte(""), []byte(""), 0},
{"ab", "abc", -1}, {[]byte("a"), []byte(""), 1},
{"abc", "ab", 1}, {[]byte(""), []byte("a"), -1},
{"x", "ab", 1}, {[]byte("abc"), []byte("abc"), 0},
{"ab", "x", -1}, {[]byte("ab"), []byte("abc"), -1},
{"x", "a", 1}, {[]byte("abc"), []byte("ab"), 1},
{"b", "x", -1}, {[]byte("x"), []byte("ab"), 1},
{[]byte("ab"), []byte("x"), -1},
{[]byte("x"), []byte("a"), 1},
{[]byte("b"), []byte("x"), -1},
// nil tests
{nil, nil, 0},
{[]byte(""), nil, 0},
{nil, []byte(""), 0},
{[]byte("a"), nil, 1},
{nil, []byte("a"), -1},
} }
func TestCompare(t *testing.T) { func TestCompare(t *testing.T) {
for _, tt := range comparetests { for _, tt := range compareTests {
a := []byte(tt.a) cmp := Compare(tt.a, tt.b)
b := []byte(tt.b)
cmp := Compare(a, b)
if cmp != tt.i { if cmp != tt.i {
t.Errorf(`Compare(%q, %q) = %v`, tt.a, tt.b, cmp) t.Errorf(`Compare(%q, %q) = %v`, tt.a, tt.b, cmp)
} }
eql := Equal(a, b) eql := Equal(tt.a, tt.b)
if eql != (tt.i == 0) { if eql != (tt.i == 0) {
t.Errorf(`Equal(%q, %q) = %v`, tt.a, tt.b, eql) t.Errorf(`Equal(%q, %q) = %v`, tt.a, tt.b, eql)
} }
eql = EqualPortable(a, b) eql = EqualPortable(tt.a, tt.b)
if eql != (tt.i == 0) { if eql != (tt.i == 0) {
t.Errorf(`EqualPortable(%q, %q) = %v`, tt.a, tt.b, eql) t.Errorf(`EqualPortable(%q, %q) = %v`, tt.a, tt.b, eql)
} }