@@ -21,6 +21,7 @@ package cid
21
21
22
22
import (
23
23
"bytes"
24
+ "encoding"
24
25
"encoding/binary"
25
26
"encoding/json"
26
27
"errors"
@@ -167,6 +168,11 @@ func NewCidV1(codecType uint64, mhash mh.Multihash) Cid {
167
168
return Cid {string (buf [:n + hashlen ])}
168
169
}
169
170
171
+ var _ encoding.BinaryMarshaler = Cid {}
172
+ var _ encoding.BinaryUnmarshaler = (* Cid )(nil )
173
+ var _ encoding.TextMarshaler = Cid {}
174
+ var _ encoding.TextUnmarshaler = (* Cid )(nil )
175
+
170
176
// Cid represents a self-describing content addressed
171
177
// identifier. It is formed by a Version, a Codec (which indicates
172
178
// a multicodec-packed content type) and a Multihash.
@@ -314,6 +320,28 @@ func Cast(data []byte) (Cid, error) {
314
320
return Cid {string (data [0 : n + cn + len (h )])}, nil
315
321
}
316
322
323
+ // UnmarshalBinary is equivalent to Cast(). It implements the
324
+ // encoding.BinaryUnmarshaler interface.
325
+ func (c * Cid ) UnmarshalBinary (data []byte ) error {
326
+ casted , err := Cast (data )
327
+ if err != nil {
328
+ return err
329
+ }
330
+ c .str = casted .str
331
+ return nil
332
+ }
333
+
334
+ // UnmarshalText is equivalent to Decode(). It implements the
335
+ // encoding.TextUnmarshaler interface.
336
+ func (c * Cid ) UnmarshalText (text []byte ) error {
337
+ decodedCid , err := Decode (string (text ))
338
+ if err != nil {
339
+ return err
340
+ }
341
+ c .str = decodedCid .str
342
+ return nil
343
+ }
344
+
317
345
// Version returns the Cid version.
318
346
func (c Cid ) Version () uint64 {
319
347
if len (c .str ) == 34 && c .str [0 ] == 18 && c .str [1 ] == 32 {
@@ -404,6 +432,18 @@ func (c Cid) Bytes() []byte {
404
432
return []byte (c .str )
405
433
}
406
434
435
+ // MarshalBinary is equivalent to Bytes(). It implements the
436
+ // encoding.BinaryMarshaler interface.
437
+ func (c Cid ) MarshalBinary () ([]byte , error ) {
438
+ return c .Bytes (), nil
439
+ }
440
+
441
+ // MarshalText is equivalent to String(). It implements the
442
+ // encoding.TextMarshaler interface.
443
+ func (c Cid ) MarshalText () ([]byte , error ) {
444
+ return []byte (c .String ()), nil
445
+ }
446
+
407
447
// Equals checks that two Cids are the same.
408
448
// In order for two Cids to be considered equal, the
409
449
// Version, the Codec and the Multihash must match.
0 commit comments