-
Notifications
You must be signed in to change notification settings - Fork 89
/
cid.go
50 lines (42 loc) · 1.31 KB
/
cid.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
39
40
41
42
43
44
45
46
47
48
49
50
package syntax
import (
"fmt"
"regexp"
"strings"
)
// Represents a CIDv1 in string format, as would pass Lexicon syntax validation.
//
// You usually want to use the github.com/ipfs/go-cid package and type when working with CIDs ("Links") in atproto. This specific type (syntax.CID) is an informal/incomplete helper specifically for doing fast string verification or pass-through without parsing, re-serialization, or normalization.
//
// Always use [ParseCID] instead of wrapping strings directly, especially when working with network input.
type CID string
var cidRegex = regexp.MustCompile(`^[a-zA-Z0-9+=]{8,256}$`)
func ParseCID(raw string) (CID, error) {
if len(raw) > 256 {
return "", fmt.Errorf("CID is too long (256 chars max)")
}
if len(raw) < 8 {
return "", fmt.Errorf("CID is too short (8 chars min)")
}
if !cidRegex.MatchString(raw) {
return "", fmt.Errorf("CID syntax didn't validate via regex")
}
if strings.HasPrefix(raw, "Qmb") {
return "", fmt.Errorf("CIDv0 not allowed in this version of atproto")
}
return CID(raw), nil
}
func (c CID) String() string {
return string(c)
}
func (c CID) MarshalText() ([]byte, error) {
return []byte(c.String()), nil
}
func (c *CID) UnmarshalText(text []byte) error {
cid, err := ParseCID(string(text))
if err != nil {
return err
}
*c = cid
return nil
}