Debian Codegraph @

_rsrch/cidiface/cidStruct.go

raw
1 package cid
2
3 import (
4 "encoding/binary"
5 "fmt"
6
7 mbase "github.com/multiformats/go-multibase"
8 mh "github.com/multiformats/go-multihash"
9 )
10
11 //=================
12 // def & accessors
13 //=================
14
15 var _ Cid = CidStruct{}
16
17 //var _ map[CidStruct]struct{} = nil // Will not compile! See struct def docs.
18 //var _ map[Cid]struct{} = map[Cid]struct{}{CidStruct{}: struct{}{}} // Legal to compile...
19 // but you'll get panics: "runtime error: hash of unhashable type cid.CidStruct"
20
21 // CidStruct represents a CID in a struct format.
22 //
23 // This format complies with the exact same Cid interface as the CidStr
24 // implementation, but completely pre-parses the Cid metadata.
25 // CidStruct is a tad quicker in case of repeatedly accessed fields,
26 // but requires more reshuffling to parse and to serialize.
27 // CidStruct is not usable as a map key, because it contains a Multihash
28 // reference, which is a slice, and thus not "comparable" as a primitive.
29 //
30 // Beware of zero-valued CidStruct: it is difficult to distinguish an
31 // incorrectly-initialized "invalid" CidStruct from one representing a v0 cid.
32 type CidStruct struct {
33 version uint64
34 codec uint64
35 hash mh.Multihash
36 }
37
38 // EmptyCidStruct is a constant for a zero/uninitialized/sentinelvalue cid;
39 // it is declared mainly for readability in checks for sentinel values.
40 //
41 // Note: it's not actually a const; the compiler does not allow const structs.
42 var EmptyCidStruct = CidStruct{}
43
44 func (c CidStruct) Version() uint64 {
45 return c.version
46 }
47
48 func (c CidStruct) Multicodec() uint64 {
49 return c.codec
50 }
51
52 func (c CidStruct) Multihash() mh.Multihash {
53 return c.hash
54 }
55
56 // String returns the default string representation of a Cid.
57 // Currently, Base58 is used as the encoding for the multibase string.
58 func (c CidStruct) String() string {
59 switch c.Version() {
60 case 0:
61 return c.Multihash().B58String()
62 case 1:
63 mbstr, err := mbase.Encode(mbase.Base58BTC, c.Bytes())
64 if err != nil {
65 panic("should not error with hardcoded mbase: " + err.Error())
66 }
67 return mbstr
68 default:
69 panic("not possible to reach this point")
70 }
71 }
72
73 // Bytes produces a raw binary format of the CID.
74 func (c CidStruct) Bytes() []byte {
75 switch c.version {
76 case 0:
77 return []byte(c.hash)
78 case 1:
79 // two 8 bytes (max) numbers plus hash
80 buf := make([]byte, 2*binary.MaxVarintLen64+len(c.hash))
81 n := binary.PutUvarint(buf, c.version)
82 n += binary.PutUvarint(buf[n:], c.codec)
83 cn := copy(buf[n:], c.hash)
84 if cn != len(c.hash) {
85 panic("copy hash length is inconsistent")
86 }
87 return buf[:n+len(c.hash)]
88 default:
89 panic("not possible to reach this point")
90 }
91 }
92
93 // Prefix builds and returns a Prefix out of a Cid.
94 func (c CidStruct) Prefix() Prefix {
95 dec, _ := mh.Decode(c.hash) // assuming we got a valid multiaddr, this will not error
96 return Prefix{
97 MhType: dec.Code,
98 MhLength: dec.Length,
99 Version: c.version,
100 Codec: c.codec,
101 }
102 }
103
104 //==================================
105 // parsers & validators & factories
106 //==================================
107
108 // CidStructParse takes a binary byte slice, parses it, and returns either
109 // a valid CidStruct, or the zero CidStruct and an error.
110 //
111 // For CidV1, the data buffer is in the form:
112 //
113 // <version><codec-type><multihash>
114 //
115 // CidV0 are also supported. In particular, data buffers starting
116 // with length 34 bytes, which starts with bytes [18,32...] are considered
117 // binary multihashes.
118 //
119 // The multicodec bytes are not parsed to verify they're a valid varint;
120 // no further reification is performed.
121 //
122 // Multibase encoding should already have been unwrapped before parsing;
123 // if you have a multibase-enveloped string, use CidStructDecode instead.
124 //
125 // CidStructParse is the inverse of Cid.Bytes().
126 func CidStructParse(data []byte) (CidStruct, error) {
127 if len(data) == 34 && data[0] == 18 && data[1] == 32 {
128 h, err := mh.Cast(data)
129 if err != nil {
130 return EmptyCidStruct, err
131 }
132 return CidStruct{
133 codec: DagProtobuf,
134 version: 0,
135 hash: h,
136 }, nil
137 }
138
139 vers, n := binary.Uvarint(data)
140 if err := uvError(n); err != nil {
141 return EmptyCidStruct, err
142 }
143
144 if vers != 0 && vers != 1 {
145 return EmptyCidStruct, fmt.Errorf("invalid cid version number: %d", vers)
146 }
147
148 codec, cn := binary.Uvarint(data[n:])
149 if err := uvError(cn); err != nil {
150 return EmptyCidStruct, err
151 }
152
153 rest := data[n+cn:]
154 h, err := mh.Cast(rest)
155 if err != nil {
156 return EmptyCidStruct, err
157 }
158
159 return CidStruct{
160 version: vers,
161 codec: codec,
162 hash: h,
163 }, nil
164 }