diff --git a/example_test.go b/example_test.go index 7f2e33e..cc83040 100644 --- a/example_test.go +++ b/example_test.go @@ -69,13 +69,21 @@ func ExampleText_UnmarshalText() { } func ExampleEqual() { - tx1 := secret.New("hello") - tx2 := secret.New("hello", secret.RedactAs(secret.Redacted)) - tx3 := secret.New("world") - fmt.Println(secret.Equal(tx1, tx2)) - fmt.Println(secret.Equal(tx1, tx3)) + // Empty Texts are equal. + fmt.Println(secret.Equal(secret.Text{}, secret.Text{})) + + // Initialsed Text is not equal to an empty one. + fmt.Println(secret.Equal(secret.New("hello"), secret.Text{})) + + // Texts with different secret strings are not equal. + fmt.Println(secret.Equal(secret.New("hello"), secret.New("world"))) + + // Texts with different redact strings but same secret string are equal. + fmt.Println(secret.Equal(secret.New("hello"), secret.New("hello", secret.RedactAs(secret.FiveX)))) // Output: // true // false + // false + // true } diff --git a/secret.go b/secret.go index 749e308..9b7e774 100644 --- a/secret.go +++ b/secret.go @@ -79,7 +79,19 @@ func (tx *Text) UnmarshalText(b []byte) error { return nil } -// Equal returns true if both arguments have the same secret. The redact strings are not considered. +// Equal returns true if both arguments have the same secret regardless of the redact strings. func Equal(tx1, tx2 Text) bool { + // If both pointers are equal then it means either both are nil or point to same value. + if tx1.secret == tx2.secret { + return true + } + + // If we are here then it means the two pointers have different values hence return false + // if any one of them is nil. + if tx1.secret == nil || tx2.secret == nil { + return false + } + + // If we are here then it means both pointers are not nil hence compare the values pointed by them. return *tx1.secret == *tx2.secret }