Skip to content

Commit

Permalink
Reorder
Browse files Browse the repository at this point in the history
  • Loading branch information
nathan-artie committed Jun 25, 2024
1 parent 6baa771 commit 9810de0
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,6 +8,25 @@ 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
}

func encodeBigInt(value *big.Int) []byte {
data := value.Bytes() // [Bytes] returns the absolute value of the number.

Expand Down Expand Up @@ -44,25 +63,6 @@ func encodeBigInt(value *big.Int) []byte {
return data
}

// 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
}

func decodeBigInt(data []byte) *big.Int {
bigInt := new(big.Int)

Expand Down

0 comments on commit 9810de0

Please sign in to comment.