commit 258ab793f1fb1f95e90f29c46240b7d686408429 Author: Jeromy Date: Fri Aug 26 17:56:12 2016 -0700 first implementation diff --git a/cid.go b/cid.go new file mode 100644 index 0000000..785a74b --- /dev/null +++ b/cid.go @@ -0,0 +1,48 @@ +package cid + +import ( + "encoding/binary" + mh "github.com/jbenet/go-multihash" + mbase "github.com/multiformats/go-multibase" +) + +type Cid struct { + Version uint64 + Type uint64 + Hash mh.Multihash +} + +func Decode(v string) (*Cid, error) { + _, data, err := mbase.Decode(v) + if err != nil { + return nil, err + } + + return Cast(data) +} + +func Cast(data []byte) (*Cid, error) { + vers, n := binary.Uvarint(data) + codec, cn := binary.Uvarint(data[n:]) + + rest := data[n+cn:] + h, err := mh.Cast(rest) + if err != nil { + return nil, err + } + + return &Cid{ + Version: vers, + Type: codec, + Hash: h, + }, nil +} + +func (c *Cid) Bytes() []byte { + buf := make([]byte, 8+len(c.Hash)) + n := binary.PutUvarint(buf, c.Version) + n += binary.PutUvarint(buf[n:], c.Type) + copy(buf[n:], c.Hash) + + return buf[:n+len(c.Hash)] +} diff --git a/cid_test.go b/cid_test.go new file mode 100644 index 0000000..8d274e3 --- /dev/null +++ b/cid_test.go @@ -0,0 +1,40 @@ +package cid + +import ( + "bytes" + "testing" + + mh "github.com/jbenet/go-multihash" +) + +func TestBasicMarshaling(t *testing.T) { + h, err := mh.Sum([]byte("TEST"), mh.SHA3, 4) + if err != nil { + t.Fatal(err) + } + + cid := &Cid{ + Type: 7, + Version: 1, + Hash: h, + } + + data := cid.Bytes() + + out, err := Cast(data) + if err != nil { + t.Fatal(err) + } + + if out.Type != cid.Type { + t.Fatal("mismatch on type") + } + + if out.Version != cid.Version { + t.Fatal("mismatch on version") + } + + if !bytes.Equal(out.Hash, cid.Hash) { + t.Fatal("multihash mismatch") + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..073b9e5 --- /dev/null +++ b/package.json @@ -0,0 +1,14 @@ +{ + "author": "whyrusleeping", + "bugs": { + "url": "https://github.com/multiformats/go-cid" + }, + "gx": { + "dvcsimport": "github.com/multiformats/go-cid" + }, + "gxVersion": "0.8.0", + "language": "go", + "license": "", + "name": "go-cid", + "version": "0.0.0" +}