/
eid.go
38 lines (28 loc) · 863 Bytes
/
eid.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package gocrunchybridge
import (
"encoding/base32"
"errors"
"fmt"
"strings"
"github.com/adelowo/go-crunchybridge/internal/util"
)
var cachedBase32 = base32.StdEncoding.WithPadding(base32.NoPadding)
// EID represents an encoded ID.
type EID string
func (e EID) IsEmpty() bool { return util.IsStringEmpty(e.String()) }
func (e EID) IsValid() error {
if len(string(e)) != 26 {
return fmt.Errorf("EID string should be exactly 26 characters long")
}
decoded, err := cachedBase32.DecodeString(strings.ToUpper(string(e)))
if err != nil {
return fmt.Errorf("failed to decode EID: %w", err)
}
dst := [16]byte{}
copy(dst[:], decoded)
if strings.ToLower(cachedBase32.EncodeToString(dst[:])) != e.String() {
return errors.New("string does not match EID format")
}
return nil
}
func (e EID) String() string { return strings.ToLower(string(e)) }