Skip to content

Commit

Permalink
feat: optimize cid.Prefix
Browse files Browse the repository at this point in the history
We call this frequently and having to allocate here is really unfortunate.
  • Loading branch information
Stebalien committed Jul 23, 2020
1 parent 85cd308 commit f7cb4c9
Showing 1 changed file with 22 additions and 5 deletions.
27 changes: 22 additions & 5 deletions cid.go
Original file line number Diff line number Diff line change
Expand Up @@ -518,12 +518,29 @@ func (c Cid) Loggable() map[string]interface{} {

// Prefix builds and returns a Prefix out of a Cid.
func (c Cid) Prefix() Prefix {
dec, _ := mh.Decode(c.Hash()) // assuming we got a valid multiaddr, this will not error
if c.Version() == 0 {
return Prefix{
MhType: mh.SHA2_256,
MhLength: 32,
Version: 0,
Codec: DagProtobuf,
}
}

offset := 0
version, n, _ := uvarint(c.str[offset:])
offset += n
codec, n, _ := uvarint(c.str[offset:])
offset += n
mhtype, n, _ := uvarint(c.str[offset:])
offset += n
mhlen, _, _ := uvarint(c.str[offset:])

return Prefix{
MhType: dec.Code,
MhLength: dec.Length,
Version: c.Version(),
Codec: c.Type(),
MhType: mhtype,
MhLength: int(mhlen),
Version: version,
Codec: codec,
}
}

Expand Down

0 comments on commit f7cb4c9

Please sign in to comment.