key.go 1.02 KB
Newer Older
1 2
// Package dshelp provides utilities for parsing and creating
// datastore keys used by go-ipfs
3 4 5
package dshelp

import (
6 7 8
	cid "github.com/ipfs/go-cid"
	"github.com/ipfs/go-datastore"
	"github.com/whyrusleeping/base32"
9 10
)

11 12
// NewKeyFromBinary creates a new key from a byte slice.
func NewKeyFromBinary(rawKey []byte) datastore.Key {
13 14 15
	buf := make([]byte, 1+base32.RawStdEncoding.EncodedLen(len(rawKey)))
	buf[0] = '/'
	base32.RawStdEncoding.Encode(buf[1:], rawKey)
16
	return datastore.RawKey(string(buf))
17
}
18

19 20
// BinaryFromDsKey returns the byte slice corresponding to the given Key.
func BinaryFromDsKey(k datastore.Key) ([]byte, error) {
21 22
	return base32.RawStdEncoding.DecodeString(k.String()[1:])
}
23

24
// CidToDsKey creates a Key from the given Cid.
25
func CidToDsKey(k cid.Cid) datastore.Key {
26
	return NewKeyFromBinary(k.Bytes())
27 28
}

29
// DsKeyToCid converts the given Key to its corresponding Cid.
30
func DsKeyToCid(dsKey datastore.Key) (cid.Cid, error) {
31 32
	kb, err := BinaryFromDsKey(dsKey)
	if err != nil {
33
		return cid.Cid{}, err
34 35 36
	}
	return cid.Cast(kb)
}