fork of indigo with slightly nicer lexgen
at main 1.4 kB view raw
1package syntax 2 3import ( 4 "errors" 5 "regexp" 6 "strings" 7) 8 9// Represents a CIDv1 in string format, as would pass Lexicon syntax validation. 10// 11// 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. 12// 13// Always use [ParseCID] instead of wrapping strings directly, especially when working with network input. 14type CID string 15 16var cidRegex = regexp.MustCompile(`^[a-zA-Z0-9+=]{8,256}$`) 17 18func ParseCID(raw string) (CID, error) { 19 if raw == "" { 20 return "", errors.New("expected CID, got empty string") 21 } 22 if len(raw) > 256 { 23 return "", errors.New("CID is too long (256 chars max)") 24 } 25 if len(raw) < 8 { 26 return "", errors.New("CID is too short (8 chars min)") 27 } 28 29 if !cidRegex.MatchString(raw) { 30 return "", errors.New("CID syntax didn't validate via regex") 31 } 32 if strings.HasPrefix(raw, "Qmb") { 33 return "", errors.New("CIDv0 not allowed in this version of atproto") 34 } 35 return CID(raw), nil 36} 37 38func (c CID) String() string { 39 return string(c) 40} 41 42func (c CID) MarshalText() ([]byte, error) { 43 return []byte(c.String()), nil 44} 45 46func (c *CID) UnmarshalText(text []byte) error { 47 cid, err := ParseCID(string(text)) 48 if err != nil { 49 return err 50 } 51 *c = cid 52 return nil 53}