key.go 1.46 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
	cid "github.com/ipfs/go-cid"
	"github.com/ipfs/go-datastore"
8
	"github.com/multiformats/go-base32"
9
	mh "github.com/multiformats/go-multihash"
10 11
)

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

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

25 26 27 28 29 30 31 32 33 34 35 36 37 38
// MultihashToDsKey creates a Key from the given Multihash.
func MultihashToDsKey(k mh.Multihash) datastore.Key {
	return NewKeyFromBinary(k)
}

// DsKeyToMultihash converts a dsKey to the corresponding Multihash.
func DsKeyToMultihash(dsKey datastore.Key) (mh.Multihash, error) {
	kb, err := BinaryFromDsKey(dsKey)
	if err != nil {
		return nil, err
	}
	return mh.Cast(kb)
}

39
// CidToDsKey creates a Key from the given Cid.
40
func CidToDsKey(k cid.Cid) datastore.Key {
41
	return MultihashToDsKey(k.Hash())
42 43
}

44
// DsKeyToCid converts the given Key to its corresponding Cid.
45
func DsKeyToCid(dsKey datastore.Key) (cid.Cid, error) {
46
	hash, err := DsKeyToMultihash(dsKey)
47
	if err != nil {
48
		return cid.Cid{}, nil
49
	}
50
	return cid.NewCidV1(cid.Raw, hash), nil
51
}