33package dshelp
44
55import (
6- cid "github.com/ipfs/go-cid"
6+ "github.com/ipfs/go-cid"
77 "github.com/ipfs/go-datastore"
88 "github.com/multiformats/go-base32"
9+ mh "github.com/multiformats/go-multihash"
910)
1011
1112// NewKeyFromBinary creates a new key from a byte slice.
@@ -21,16 +22,30 @@ func BinaryFromDsKey(k datastore.Key) ([]byte, error) {
2122 return base32 .RawStdEncoding .DecodeString (k .String ()[1 :])
2223}
2324
24- // CidToDsKey creates a Key from the given Cid.
25- func CidToDsKey (k cid.Cid ) datastore.Key {
26- return NewKeyFromBinary (k .Bytes ())
25+ // MultihashToDsKey creates a Key from the given Multihash.
26+ // If working with Cids, you can call cid.Hash() to obtain
27+ // the multihash. Note that different CIDs might represent
28+ // the same multihash.
29+ func MultihashToDsKey (k mh.Multihash ) datastore.Key {
30+ return NewKeyFromBinary (k )
2731}
2832
29- // DsKeyToCid converts the given Key to its corresponding Cid .
30- func DsKeyToCid (dsKey datastore.Key ) (cid. Cid , error ) {
33+ // DsKeyToMultihash converts a dsKey to the corresponding Multihash .
34+ func DsKeyToMultihash (dsKey datastore.Key ) (mh. Multihash , error ) {
3135 kb , err := BinaryFromDsKey (dsKey )
36+ if err != nil {
37+ return nil , err
38+ }
39+ return mh .Cast (kb )
40+ }
41+
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/github.com/ipfs/go-cid#pkg-constants).
45+ func DsKeyToCidV1 (dsKey datastore.Key , codecType uint64 ) (cid.Cid , error ) {
46+ hash , err := DsKeyToMultihash (dsKey )
3247 if err != nil {
3348 return cid.Cid {}, err
3449 }
35- return cid .Cast ( kb )
50+ return cid .NewCidV1 ( codecType , hash ), nil
3651}
0 commit comments