forked from scorum/bitshares-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
objectid.go
94 lines (76 loc) · 1.97 KB
/
objectid.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package types
import (
"encoding/json"
"fmt"
"github.com/pkg/errors"
"github.com/youthonline/bitshares-go/encoding/transaction"
"strconv"
"strings"
)
// On the BitShares blockchains there are no addresses, but objects identified by a unique id,
// an type and a space in the form: space.type.id
type ObjectID struct {
Space uint64
Type uint64
ID uint64
}
func (o ObjectID) String() string {
return fmt.Sprintf("%d.%d.%d", o.Space, o.Type, o.ID)
}
func (o *ObjectID) MarshalJSON() ([]byte, error) {
return json.Marshal(o.String())
}
func (o *ObjectID) UnmarshalJSON(s []byte) error {
str, err := unquote(string(s))
if err != nil {
return errors.Errorf("unable to parse ObjectID from %s", s)
}
objectID, err := ParseObjectID(str)
if err != nil {
return err
}
*o = objectID
return nil
}
func (o ObjectID) MarshalTransaction(encoder *transaction.Encoder) error {
encoder.EncodeVarint(int64(o.ID))
return nil
}
func MustParseObjectID(str string) ObjectID {
out, err := ParseObjectID(str)
if err != nil {
panic(err)
}
return out
}
func ParseObjectID(str string) (ObjectID, error) {
var err error
objectID := ObjectID{}
parts := strings.Split(str, ".")
if len(parts) != 3 {
return objectID, errors.Errorf("unable to parse ObjectID from %s", str)
}
objectID.Space, err = strconv.ParseUint(parts[0], 10, 64)
if err != nil {
return objectID, errors.Errorf("unable to parse ObjectID [space] from %s", str)
}
objectID.Type, err = strconv.ParseUint(parts[1], 10, 64)
if err != nil {
return objectID, errors.Errorf("unable to parse ObjectID [type] from %s", str)
}
objectID.ID, err = strconv.ParseUint(parts[2], 10, 64)
if err != nil {
return objectID, errors.Errorf("unable to parse ObjectID [id] from %ss", str)
}
return objectID, nil
}
func unquote(in string) (string, error) {
if strings.HasPrefix(in, "\"") && strings.HasSuffix(in, "\"") {
q, err := strconv.Unquote(in)
if err != nil {
return "", err
}
return q, nil
}
return in, nil
}