common: adding Address.Equals

It's a common use-case to compare addresses.
Here we add the Equals method to the address type.
It uses for loop instead of bytes.Equals to avoid extra memory allocation.
This commit is contained in:
Robert Zaremba 2017-11-13 11:07:59 +01:00
parent 3d88ecd61a
commit ae5cb602b7
2 changed files with 31 additions and 0 deletions

View file

@ -165,6 +165,16 @@ func (a Address) Bytes() []byte { return a[:] }
func (a Address) Big() *big.Int { return new(big.Int).SetBytes(a[:]) } func (a Address) Big() *big.Int { return new(big.Int).SetBytes(a[:]) }
func (a Address) Hash() Hash { return BytesToHash(a[:]) } func (a Address) Hash() Hash { return BytesToHash(a[:]) }
// Equals returns a boolean reporting whether a and b are the same addresses
func (a Address) Equals(b Address) bool {
for i := 0; i < AddressLength; i++ {
if a[i] != b[i] {
return false
}
}
return true
}
// Hex returns an EIP55-compliant hex string representation of the address. // Hex returns an EIP55-compliant hex string representation of the address.
func (a Address) Hex() string { func (a Address) Hex() string {
unchecksummed := hex.EncodeToString(a[:]) unchecksummed := hex.EncodeToString(a[:])

View file

@ -125,3 +125,24 @@ func BenchmarkAddressHex(b *testing.B) {
testAddr.Hex() testAddr.Hex()
} }
} }
func TestAddressEquals(t *testing.T) {
var tests = []struct {
a1, a2 string
result bool
}{
{"0x5aaeb6053f3e94c9b9a09f33669435e7ef1beaed", "0x5aaeb6053f3e94c9b9a09f33669435e7ef1beaed", true},
{"0x5aaeb6053f3e94c9b9a09f33669435e7ef1beaed", "0x5AAEB6053f3e94c9b9a09f33669435e7ef1beaed", true},
{"0x0", "0x0000000000000000000000000000000000000000", true},
{"0x1aaeb6053f3e94c9b9a09f33669435e7ef1beaed", "0x5aaeb6053f3e94c9b9a09f33669435e7ef1beaed", false},
{"0x0", "0x5aaeb6053f3e94c9b9a09f33669435e7ef1beaed", false},
}
for i, test := range tests {
a1 := HexToAddress(test.a1)
a2 := HexToAddress(test.a2)
if a1.Equals(a2) != test.result {
t.Errorf("test #%d: failed. Should (%s == %s) be %v",
i, test.a1, test.a2, test.result)
}
}
}