github.com/whtcorpsinc/MilevaDB-Prod@v0.0.0-20211104133533-f57f4be3b597/soliton/codec/float.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  	"math"
    18  
    19  	"github.com/whtcorpsinc/errors"
    20  )
    21  
    22  func encodeFloatToCmpUint64(f float64) uint64 {
    23  	u := math.Float64bits(f)
    24  	if f >= 0 {
    25  		u |= signMask
    26  	} else {
    27  		u = ^u
    28  	}
    29  	return u
    30  }
    31  
    32  func decodeCmpUintToFloat(u uint64) float64 {
    33  	if u&signMask > 0 {
    34  		u &= ^signMask
    35  	} else {
    36  		u = ^u
    37  	}
    38  	return math.Float64frombits(u)
    39  }
    40  
    41  // EncodeFloat encodes a float v into a byte slice which can be sorted lexicographically later.
    42  // EncodeFloat guarantees that the encoded value is in ascending order for comparison.
    43  func EncodeFloat(b []byte, v float64) []byte {
    44  	u := encodeFloatToCmpUint64(v)
    45  	return EncodeUint(b, u)
    46  }
    47  
    48  // DecodeFloat decodes a float from a byte slice generated with EncodeFloat before.
    49  func DecodeFloat(b []byte) ([]byte, float64, error) {
    50  	b, u, err := DecodeUint(b)
    51  	return b, decodeCmpUintToFloat(u), errors.Trace(err)
    52  }
    53  
    54  // EncodeFloatDesc encodes a float v into a byte slice which can be sorted lexicographically later.
    55  // EncodeFloatDesc guarantees that the encoded value is in descending order for comparison.
    56  func EncodeFloatDesc(b []byte, v float64) []byte {
    57  	u := encodeFloatToCmpUint64(v)
    58  	return EncodeUintDesc(b, u)
    59  }
    60  
    61  // DecodeFloatDesc decodes a float from a byte slice generated with EncodeFloatDesc before.
    62  func DecodeFloatDesc(b []byte) ([]byte, float64, error) {
    63  	b, u, err := DecodeUintDesc(b)
    64  	return b, decodeCmpUintToFloat(u), errors.Trace(err)
    65  }