private/currency: add strictcsv support to microunit

Change-Id: Iad2f6a07f189f2faa1d13bdb82dfa320921f6938
This commit is contained in:
Jeff Wendling 2020-03-31 14:30:39 -06:00
parent 0a69da4ff1
commit 9bd0bd0c24
2 changed files with 34 additions and 0 deletions

View File

@ -5,6 +5,7 @@ package currency
import ( import (
"math" "math"
"strconv"
"github.com/shopspring/decimal" "github.com/shopspring/decimal"
"github.com/zeebo/errs" "github.com/zeebo/errs"
@ -59,3 +60,16 @@ func MicroUnitFromDecimal(d decimal.Decimal) (MicroUnit, error) {
} }
return MicroUnit{v: m.IntPart()}, nil 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
}

View File

@ -7,6 +7,8 @@ import (
"testing" "testing"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"storj.io/common/strictcsv"
) )
func TestMicroUnitToFloatString(t *testing.T) { func TestMicroUnitToFloatString(t *testing.T) {
@ -18,3 +20,21 @@ func TestMicroUnitFromFloatString(t *testing.T) {
require.NoError(t, err) require.NoError(t, err)
require.Equal(t, NewMicroUnit(12340), m) 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)
}