logtail: reduce PublicID.UnmarshalText from 2 allocs to 0

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
This commit is contained in:
Brad Fitzpatrick
2021-04-15 10:42:02 -07:00
parent bb0710d51d
commit b34fbb24e8
2 changed files with 32 additions and 6 deletions

View File

@ -121,14 +121,17 @@ func (id PublicID) MarshalText() ([]byte, error) {
}
func (id *PublicID) UnmarshalText(s []byte) error {
b, err := hex.DecodeString(string(s))
if err != nil {
return fmt.Errorf("logtail.PublicID.UnmarshalText: %v", err)
if len(s) != len(id)*2 {
return fmt.Errorf("logtail.PublicID.UnmarshalText: invalid hex length: %d", len(s))
}
if len(b) != len(id) {
return fmt.Errorf("logtail.PublicID.UnmarshalText: invalid hex length: %d", len(b))
for i := range id {
a, ok1 := fromHexChar(s[i*2+0])
b, ok2 := fromHexChar(s[i*2+1])
if !ok1 || !ok2 {
return errors.New("invalid hex character")
}
id[i] = (a << 4) | b
}
copy(id[:], b)
return nil
}