From f7cb4c91eb6f0815b6dbfa9bbefbf59597af1e32 Mon Sep 17 00:00:00 2001 From: Steven Allen Date: Wed, 22 Jul 2020 19:45:20 -0700 Subject: [PATCH] feat: optimize cid.Prefix We call this frequently and having to allocate here is really unfortunate. --- cid.go | 27 ++++++++++++++++++++++----- 1 file changed, 22 insertions(+), 5 deletions(-) diff --git a/cid.go b/cid.go index f59c76c..1268f39 100644 --- a/cid.go +++ b/cid.go @@ -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, } } -- GitLab