all: implement AppendText alongside MarshalText (#9207)
This eventually allows encoding packages that may respect the proposed encoding.TextAppender interface. The performance gains from this is between 10-30%. Updates tailscale/corp#14379 Signed-off-by: Joe Tsai <joetsai@digital-static.net>
This commit is contained in:
+15
-3
@@ -9,6 +9,7 @@ import (
|
||||
"encoding/base32"
|
||||
"errors"
|
||||
"fmt"
|
||||
"slices"
|
||||
|
||||
"github.com/fxamacker/cbor/v2"
|
||||
"golang.org/x/crypto/blake2s"
|
||||
@@ -37,11 +38,22 @@ func (h *AUMHash) UnmarshalText(text []byte) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// TODO(https://go.dev/issue/53693): Use base32.Encoding.AppendEncode instead.
|
||||
func base32AppendEncode(enc *base32.Encoding, dst, src []byte) []byte {
|
||||
n := enc.EncodedLen(len(src))
|
||||
dst = slices.Grow(dst, n)
|
||||
enc.Encode(dst[len(dst):][:n], src)
|
||||
return dst[:len(dst)+n]
|
||||
}
|
||||
|
||||
// AppendText implements encoding.TextAppender.
|
||||
func (h AUMHash) AppendText(b []byte) ([]byte, error) {
|
||||
return base32AppendEncode(base32StdNoPad, b, h[:]), nil
|
||||
}
|
||||
|
||||
// MarshalText implements encoding.TextMarshaler.
|
||||
func (h AUMHash) MarshalText() ([]byte, error) {
|
||||
b := make([]byte, base32StdNoPad.EncodedLen(len(h)))
|
||||
base32StdNoPad.Encode(b, h[:])
|
||||
return b, nil
|
||||
return h.AppendText(nil)
|
||||
}
|
||||
|
||||
// IsZero returns true if the hash is the empty value.
|
||||
|
||||
Reference in New Issue
Block a user