github.com/bingoohuang/gg@v0.0.0-20240325092523-45da7dee9335/pkg/sqlparse/tidbparser/dependency/util/codec/decimal.go (about) 1 // Copyright 2015 PingCAP, 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 "fmt" 18 19 "github.com/bingoohuang/gg/pkg/sqlparse/tidbparser/dependency/types" 20 "github.com/juju/errors" 21 ) 22 23 // EncodeDecimal encodes a decimal into a byte slice which can be sorted lexicographically later. 24 func EncodeDecimal(b []byte, dec *types.MyDecimal, precision, frac int) []byte { 25 if precision == 0 { 26 precision, frac = dec.PrecisionAndFrac() 27 } 28 b = append(b, byte(precision), byte(frac)) 29 bin, err := dec.ToBin(precision, frac) 30 if err != nil { 31 panic(fmt.Sprintf("should not happen, precision %d, frac %d %v", precision, frac, err)) 32 } 33 b = append(b, bin...) 34 return b 35 } 36 37 // DecodeDecimal decodes bytes to decimal. 38 func DecodeDecimal(b []byte) ([]byte, *types.MyDecimal, error) { 39 if len(b) < 3 { 40 return b, nil, errors.New("insufficient bytes to decode value") 41 } 42 precision := int(b[0]) 43 frac := int(b[1]) 44 b = b[2:] 45 dec := new(types.MyDecimal) 46 binSize, err := dec.FromBin(b, precision, frac) 47 b = b[binSize:] 48 if err != nil { 49 return b, nil, errors.Trace(err) 50 } 51 return b, dec, nil 52 }