Skip to content

Commit

Permalink
Scientific un-/marshalling
Browse files Browse the repository at this point in the history
  • Loading branch information
alpe committed Oct 27, 2024
1 parent 26c746a commit b4bf27b
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 3 deletions.
34 changes: 32 additions & 2 deletions math/dec.go
Original file line number Diff line number Diff line change
Expand Up @@ -400,12 +400,42 @@ func (x Dec) Reduce() (Dec, int) {
return y, n
}

// Marshal serializes the decimal value into a byte slice in text format.
// This method represents the decimal in a portable and compact scientific notation.
// Based on the exponent value, the number is formatted into decimal: -d.ddddE±dd, decimal exponent, exponent digits
//
// For example, the following transformations are made:
// - 0 -> 0E+0
// - 123 -> 1.23E+3
// - -0.001 -> -1E-3
// - -0.000000001 -> -1E-9
//
// Returns:
// - A byte slice of the decimal in text format.
// - An error if the decimal cannot be reduced or marshaled properly.
func (x Dec) Marshal() ([]byte, error) {
panic("not implemented")
var d apd.Decimal
if _, _, err := dec128Context.Reduce(&d, &x.dec); err != nil {
return nil, ErrInvalidDec.Wrap(err.Error())
}

return []byte(d.Text('E')), nil
}

// Unmarshal parses a byte slice containing a text-formatted decimal and stores the result in the receiver.
// It returns an error if the byte slice does not represent a valid decimal.
func (x *Dec) Unmarshal(data []byte) error {
panic("not implemented")
result, err := NewDecFromString(string(data))
if err != nil {
return ErrInvalidDec.Wrap(err.Error())
}

if result.dec.Form != apd.Finite {
return ErrInvalidDec.Wrap("unknown decimal form")
}

x.dec = result.dec
return nil
}

// MarshalTo encodes the receiver into the provided byte slice and returns the number of bytes written and any error encountered.
Expand Down
1 change: 0 additions & 1 deletion math/dec_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1312,7 +1312,6 @@ func must[T any](r T, err error) T {
}

func TestMarshalUnmarshal(t *testing.T) {
t.Skip("not supported, yet")
specs := map[string]struct {
x Dec
exp string
Expand Down

0 comments on commit b4bf27b

Please sign in to comment.