diff options
| author | Ophestra Umiker <cat@ophivana.moe> | 2024-12-19 18:19:47 +0900 |
|---|---|---|
| committer | Ophestra Umiker <cat@ophivana.moe> | 2024-12-19 18:19:47 +0900 |
| commit | 5ea7333431942780c79c02a990682e44b6834ed6 (patch) | |
| tree | 28abe7af49bb11b71f91cff55d4aa1ea1614ae5c /fst/id.go | |
| parent | f796622c35ad15f4a8d2e91fb0437f566fc77e52 (diff) | |
fst: implement app id parser
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
Diffstat (limited to 'fst/id.go')
| -rw-r--r-- | fst/id.go | 48 |
1 files changed, 48 insertions, 0 deletions
diff --git a/fst/id.go b/fst/id.go new file mode 100644 index 00000000..a8363c25 --- /dev/null +++ b/fst/id.go @@ -0,0 +1,48 @@ +package fst + +import ( + "crypto/rand" + "encoding/hex" + "errors" + "fmt" +) + +type ID [16]byte + +var ( + ErrInvalidLength = errors.New("string representation must have a length of 32") +) + +func (a *ID) String() string { + return hex.EncodeToString(a[:]) +} + +func NewAppID(id *ID) error { + _, err := rand.Read(id[:]) + return err +} + +func ParseAppID(id *ID, s string) error { + if len(s) != 32 { + return ErrInvalidLength + } + + for i, b := range s { + if b < '0' || b > 'f' { + return fmt.Errorf("invalid char %q at byte %d", b, i) + } + + v := uint8(b) + if v > '9' { + v = 10 + v - 'a' + } else { + v -= '0' + } + if i%2 == 0 { + v <<= 4 + } + id[i/2] += v + } + + return nil +} |
