github.com/stafiprotocol/go-substrate-rpc-client@v1.4.7/subkey/compact.go (about) 1 // Copyright 2018 Jsgenesis 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package subkey 16 17 import ( 18 "bytes" 19 "encoding/binary" 20 "errors" 21 ) 22 23 func compactUint(v uint64) ([]byte, error) { 24 // This code was copied over and adapted with many thanks from Joystream/parity-codec-go:withreflect@develop 25 var buf bytes.Buffer 26 if v < 1<<30 { 27 switch { 28 case v < 1<<6: 29 return []byte{byte(v) << 2}, nil 30 case v < 1<<14: 31 err := binary.Write(&buf, binary.LittleEndian, uint16(v<<2)+1) 32 if err != nil { 33 return nil, err 34 } 35 default: 36 err := binary.Write(&buf, binary.LittleEndian, uint32(v<<2)+2) 37 if err != nil { 38 return nil, err 39 } 40 } 41 return buf.Bytes(), nil 42 } 43 44 n := byte(0) 45 limit := uint64(1 << 32) 46 for v >= limit && limit > 256 { // when overflows, limit will be < 256 47 n++ 48 limit <<= 8 49 } 50 if n > 4 { 51 return nil, errors.New("assertion error: n>4 needed to compact-encode uint64") 52 } 53 54 err := buf.WriteByte((n << 2) + 3) 55 if err != nil { 56 return nil, err 57 } 58 59 b := make([]byte, 8) 60 binary.LittleEndian.PutUint64(b, v) 61 _, err = buf.Write(b[:4+n]) 62 if err != nil { 63 return nil, err 64 } 65 return buf.Bytes(), nil 66 }