first implementation
This commit is contained in:
48
cid.go
Normal file
48
cid.go
Normal file
@@ -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)]
|
||||
}
|
||||
40
cid_test.go
Normal file
40
cid_test.go
Normal file
@@ -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")
|
||||
}
|
||||
}
|
||||
14
package.json
Normal file
14
package.json
Normal file
@@ -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"
|
||||
}
|
||||
Reference in New Issue
Block a user