1package syntax
2
3import (
4 "errors"
5 "strings"
6)
7
8type AtIdentifier struct {
9 Inner interface{}
10}
11
12func ParseAtIdentifier(raw string) (*AtIdentifier, error) {
13 if raw == "" {
14 return nil, errors.New("expected AT account identifier, got empty string")
15 }
16 if strings.HasPrefix(raw, "did:") {
17 did, err := ParseDID(raw)
18 if err != nil {
19 return nil, err
20 }
21 return &AtIdentifier{Inner: did}, nil
22 }
23 handle, err := ParseHandle(raw)
24 if err != nil {
25 return nil, err
26 }
27 return &AtIdentifier{Inner: handle}, nil
28}
29
30func (n AtIdentifier) IsHandle() bool {
31 _, ok := n.Inner.(Handle)
32 return ok
33}
34
35func (n AtIdentifier) AsHandle() (Handle, error) {
36 handle, ok := n.Inner.(Handle)
37 if ok {
38 return handle, nil
39 }
40 return "", errors.New("AT Identifier is not a Handle")
41}
42
43func (n AtIdentifier) IsDID() bool {
44 _, ok := n.Inner.(DID)
45 return ok
46}
47
48func (n AtIdentifier) AsDID() (DID, error) {
49 did, ok := n.Inner.(DID)
50 if ok {
51 return did, nil
52 }
53 return "", errors.New("AT Identifier is not a DID")
54}
55
56func (n AtIdentifier) Normalize() AtIdentifier {
57 handle, ok := n.Inner.(Handle)
58 if ok {
59 return AtIdentifier{Inner: handle.Normalize()}
60 }
61 return n
62}
63
64func (n AtIdentifier) String() string {
65 did, ok := n.Inner.(DID)
66 if ok {
67 return did.String()
68 }
69 handle, ok := n.Inner.(Handle)
70 if ok {
71 return handle.String()
72 }
73 return ""
74}
75
76func (a AtIdentifier) MarshalText() ([]byte, error) {
77 return []byte(a.String()), nil
78}
79
80func (a *AtIdentifier) UnmarshalText(text []byte) error {
81 atid, err := ParseAtIdentifier(string(text))
82 if err != nil {
83 return err
84 }
85 *a = *atid
86 return nil
87}