From 9bd0bd0c242ad37927c8ec51781fcbbb515b106f Mon Sep 17 00:00:00 2001 From: Jeff Wendling Date: Tue, 31 Mar 2020 14:30:39 -0600 Subject: [PATCH] private/currency: add strictcsv support to microunit Change-Id: Iad2f6a07f189f2faa1d13bdb82dfa320921f6938 --- private/currency/microunit.go | 14 ++++++++++++++ private/currency/microunit_test.go | 20 ++++++++++++++++++++ 2 files changed, 34 insertions(+) diff --git a/private/currency/microunit.go b/private/currency/microunit.go index 71007dfc3..89d70c90f 100644 --- a/private/currency/microunit.go +++ b/private/currency/microunit.go @@ -5,6 +5,7 @@ package currency import ( "math" + "strconv" "github.com/shopspring/decimal" "github.com/zeebo/errs" @@ -59,3 +60,16 @@ func MicroUnitFromDecimal(d decimal.Decimal) (MicroUnit, error) { } return MicroUnit{v: m.IntPart()}, nil } + +// MarshalCSV does the custom marshaling of MicroUnits. +func (m MicroUnit) MarshalCSV() (string, error) { return strconv.FormatInt(m.v, 10), nil } + +// UnmarshalCSV reads the MicroUnit in CSV form. +func (m *MicroUnit) UnmarshalCSV(s string) (err error) { + v, err := strconv.ParseInt(s, 10, 64) + if err != nil { + return err + } + m.v = v + return nil +} diff --git a/private/currency/microunit_test.go b/private/currency/microunit_test.go index 25e1a8ce0..ed7861e31 100644 --- a/private/currency/microunit_test.go +++ b/private/currency/microunit_test.go @@ -7,6 +7,8 @@ import ( "testing" "github.com/stretchr/testify/require" + + "storj.io/common/strictcsv" ) func TestMicroUnitToFloatString(t *testing.T) { @@ -18,3 +20,21 @@ func TestMicroUnitFromFloatString(t *testing.T) { require.NoError(t, err) require.Equal(t, NewMicroUnit(12340), m) } + +func TestMicroUnitCSV(t *testing.T) { + type row struct { + Foo MicroUnit `csv:"foo"` + Bar MicroUnit `csv:"bar"` + } + exp := row{ + Foo: NewMicroUnit(1), + Bar: NewMicroUnit(2), + } + + csv, err := strictcsv.MarshalString(exp) + require.NoError(t, err) + + var got row + require.NoError(t, strictcsv.UnmarshalString(csv, &got)) + require.Equal(t, exp, got) +}