github.com/whtcorpsinc/MilevaDB-Prod@v0.0.0-20211104133533-f57f4be3b597/soliton/codec/decimal.go (about) 1 // Copyright 2020 WHTCORPS INC, Inc. 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 // See the License for the specific language governing permissions and 12 // limitations under the License. 13 14 package codec 15 16 import ( 17 "github.com/whtcorpsinc/errors" 18 "github.com/whtcorpsinc/failpoint" 19 "github.com/whtcorpsinc/milevadb/types" 20 ) 21 22 // EncodeDecimal encodes a decimal into a byte slice which can be sorted lexicographically later. 23 func EncodeDecimal(b []byte, dec *types.MyDecimal, precision, frac int) ([]byte, error) { 24 if precision == 0 { 25 precision, frac = dec.PrecisionAndFrac() 26 } 27 b = append(b, byte(precision), byte(frac)) 28 b, err := dec.WriteBin(precision, frac, b) 29 return b, errors.Trace(err) 30 } 31 32 func valueSizeOfDecimal(dec *types.MyDecimal, precision, frac int) int { 33 if precision == 0 { 34 precision, frac = dec.PrecisionAndFrac() 35 } 36 return types.DecimalBinSize(precision, frac) + 2 37 } 38 39 // DecodeDecimal decodes bytes to decimal. 40 func DecodeDecimal(b []byte) ([]byte, *types.MyDecimal, int, int, error) { 41 failpoint.Inject("errorInDecodeDecimal", func(val failpoint.Value) { 42 if val.(bool) { 43 failpoint.Return(b, nil, 0, 0, errors.New("gofail error")) 44 } 45 }) 46 47 if len(b) < 3 { 48 return b, nil, 0, 0, errors.New("insufficient bytes to decode value") 49 } 50 precision := int(b[0]) 51 frac := int(b[1]) 52 b = b[2:] 53 dec := new(types.MyDecimal) 54 binSize, err := dec.FromBin(b, precision, frac) 55 b = b[binSize:] 56 if err != nil { 57 return b, nil, precision, frac, errors.Trace(err) 58 } 59 return b, dec, precision, frac, nil 60 }