Skip to content

Commit

Permalink
Reorder the functions in debezium.decimal (#754)
Browse files Browse the repository at this point in the history
  • Loading branch information
nathan-artie authored Jun 25, 2024
1 parent 86b968f commit 92c0d3e
Showing 1 changed file with 19 additions and 19 deletions.
38 changes: 19 additions & 19 deletions lib/debezium/decimal.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,25 +8,6 @@ import (
"github.com/artie-labs/transfer/lib/typing/decimal"
)

// EncodeDecimal is used to encode a string representation of a number to `org.apache.kafka.connect.data.Decimal`.
func EncodeDecimal(value string, scale uint16) ([]byte, error) {
bigFloatValue := new(big.Float)
if _, success := bigFloatValue.SetString(value); !success {
return nil, fmt.Errorf("unable to use %q as a floating-point number", value)
}

scaledValue := new(big.Int).Exp(big.NewInt(10), big.NewInt(int64(scale)), nil)
bigFloatValue.Mul(bigFloatValue, new(big.Float).SetInt(scaledValue))

// Extract the scaled integer value.
bigIntValue := new(big.Int)
if _, success := bigIntValue.SetString(bigFloatValue.String(), 10); !success {
return nil, fmt.Errorf("unable to use %q as a floating-point number", value)
}

return encodeBigInt(bigIntValue), nil
}

// encodeBigInt encodes a [big.Int] into a byte slice using two's complement.
func encodeBigInt(bigIntValue *big.Int) []byte {
data := bigIntValue.Bytes() // [Bytes] returns the absolute value of the number.
Expand Down Expand Up @@ -85,6 +66,25 @@ func decodeBigInt(data []byte) *big.Int {
return bigInt
}

// EncodeDecimal is used to encode a string representation of a number to `org.apache.kafka.connect.data.Decimal`.
func EncodeDecimal(value string, scale uint16) ([]byte, error) {
bigFloatValue := new(big.Float)
if _, success := bigFloatValue.SetString(value); !success {
return nil, fmt.Errorf("unable to use %q as a floating-point number", value)
}

scaledValue := new(big.Int).Exp(big.NewInt(10), big.NewInt(int64(scale)), nil)
bigFloatValue.Mul(bigFloatValue, new(big.Float).SetInt(scaledValue))

// Extract the scaled integer value.
bigIntValue := new(big.Int)
if _, success := bigIntValue.SetString(bigFloatValue.String(), 10); !success {
return nil, fmt.Errorf("unable to use %q as a floating-point number", value)
}

return encodeBigInt(bigIntValue), nil
}

// DecodeDecimal is used to decode `org.apache.kafka.connect.data.Decimal`.
func DecodeDecimal(data []byte, precision *int, scale int) *decimal.Decimal {
// Convert the big integer to a big float
Expand Down

0 comments on commit 92c0d3e

Please sign in to comment.