logtail: add ParsePublicID that doesn't allocate

pull/296/head
Brad Fitzpatrick 5 years ago
parent 780deb9996
commit 3464114b88

@ -92,6 +92,23 @@ func (id PrivateID) Public() (pub PublicID) {
// The public ID value is a SHA-256 hash of a private ID.
type PublicID [sha256.Size]byte
// ParsePublicID returns a PublicID from its hex (String) representation.
func ParsePublicID(s string) (PublicID, error) {
if len(s) != sha256.Size*2 {
return PublicID{}, errors.New("invalid length")
}
var p PublicID
for i := range p {
a, ok1 := fromHexChar(s[i*2+0])
b, ok2 := fromHexChar(s[i*2+1])
if !ok1 || !ok2 {
return PublicID{}, errors.New("invalid hex character")
}
p[i] = (a << 4) | b
}
return p, nil
}
func (id PublicID) MarshalText() ([]byte, error) {
b := make([]byte, hex.EncodedLen(len(id)))
if i := hex.Encode(b, id[:]); i != len(b) {

@ -51,6 +51,11 @@ func TestIDs(t *testing.T) {
if id1.String() != id3.String() {
t.Fatalf("id1.String()=%v does not match id3.String()=%v", id1.String(), id3.String())
}
if id3, err := ParsePublicID(id1.Public().String()); err != nil {
t.Errorf("ParsePublicID: %v", err)
} else if id1.Public() != id3 {
t.Errorf("ParsePublicID mismatch")
}
id4, err := ParsePrivateID(id1.String())
if err != nil {

Loading…
Cancel
Save