package uuids import ( "encoding/hex" "fmt" "regexp" ) // MarshalText is a wrapper around [UUID.String]. func (uuid UUID) MarshalText() ([]byte, error) { if uuid.IsZero() { return []byte(UUID{}.String()), nil } return []byte(uuid.String()), nil } var reParse = regexp.MustCompile(`^([0-9A-Fa-f]{8})-([0-9A-Fa-f]{4})-([0-9A-Fa-f]{4})-([0-9A-Fa-f]{4})-([0-9A-Fa-f]{12})$`) // UnmarshalText parses a hexadecimal UUID representation // of [UUID.String]'s flavour. // Both upper-case and lower-case hexadecimal digits are recognized. // // TODO(jfrech): 2024-04-30: Emit a better error. func (uuid *UUID) UnmarshalText(text []byte) error { *uuid = UUID{} parse := func(s string) (UUID, error) { smatchs := reParse.FindStringSubmatch(s) if len(smatchs) != 1+5 { return UUID{}, fmt.Errorf("not a UUID: %q", s) } uuid, err := hex.DecodeString(smatchs[1] + smatchs[2] + smatchs[3] + smatchs[4] + smatchs[5]) if err != nil { panic("unreachable: " + err.Error()) } else if len(uuid) != Size { panic("unreachable") } return UUID(uuid), nil } u, err := parse(string(text)) if err != nil { return err } *uuid = u return nil }