key.go 1.61 KB
Newer Older
1
// Package dshelp provides utilities for parsing and creating
tavit ohanian's avatar
tavit ohanian committed
2
// datastore keys used by go-dms3
3 4 5
package dshelp

import (
6
	"github.com/multiformats/go-base32"
7
	mh "github.com/multiformats/go-multihash"
8 9
	"gitlab.dms3.io/dms3/go-cid"
	"gitlab.dms3.io/dms3/go-datastore"
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
// MultihashToDsKey creates a Key from the given Multihash.
26 27 28
// If working with Cids, you can call cid.Hash() to obtain
// the multihash. Note that different CIDs might represent
// the same multihash.
29 30 31 32 33 34 35 36 37 38 39 40 41
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)
}

42
// DsKeyToCidV1Raw converts the given Key (which should be a raw multihash
43
// key) to a Cid V1 of the given type (see
44
// https://godoc.org/gitlab.dms3.io/dms3/go-cid#pkg-constants).
45
func DsKeyToCidV1(dsKey datastore.Key, codecType uint64) (cid.Cid, error) {
46
	hash, err := DsKeyToMultihash(dsKey)
47
	if err != nil {
48
		return cid.Cid{}, err
49
	}
50
	return cid.NewCidV1(codecType, hash), nil
51
}