Skip to content

Commit

Permalink
Add JSON marshalling for fee dimensions (#1622)
Browse files Browse the repository at this point in the history
  • Loading branch information
aaronbuchwald authored Oct 2, 2024
1 parent 7e53003 commit 404e74f
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 0 deletions.
33 changes: 33 additions & 0 deletions fees/dimension.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ package fees

import (
"encoding/binary"
"encoding/json"
"errors"
"fmt"
"strconv"
Expand Down Expand Up @@ -140,6 +141,38 @@ func (d *Dimensions) UnmarshalText(b []byte) error {
return nil
}

type DimensionJSON struct {
Bandwidth uint64 `json:"bandwidth"`
Compute uint64 `json:"compute"`
StorageRead uint64 `json:"storageRead"`
StorageAllocate uint64 `json:"storageAllocate"`
StorageWrite uint64 `json:"storageWrite"`
}

func (d Dimensions) MarshalJSON() ([]byte, error) {
dimensionJSON := DimensionJSON{
Bandwidth: d[Bandwidth],
Compute: d[Compute],
StorageRead: d[StorageRead],
StorageAllocate: d[StorageAllocate],
StorageWrite: d[StorageWrite],
}
return json.Marshal(dimensionJSON)
}

func (d *Dimensions) UnmarshalJSON(b []byte) error {
dimensionJSON := DimensionJSON{}
if err := json.Unmarshal(b, &dimensionJSON); err != nil {
return err
}
d[Bandwidth] = dimensionJSON.Bandwidth
d[Compute] = dimensionJSON.Compute
d[StorageRead] = dimensionJSON.StorageRead
d[StorageAllocate] = dimensionJSON.StorageAllocate
d[StorageWrite] = dimensionJSON.StorageWrite
return nil
}

func UnpackDimensions(raw []byte) (Dimensions, error) {
if len(raw) != DimensionsLen {
return Dimensions{}, fmt.Errorf("%w: found=%d wanted=%d", ErrWrongDimensionSize, len(raw), DimensionsLen)
Expand Down
18 changes: 18 additions & 0 deletions fees/dimension_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,3 +25,21 @@ func TestDimensionsMarshalText(t *testing.T) {
require.NoError(parsedDimText.UnmarshalText(dimTextBytes))
require.Equal(dim, parsedDimText)
}

func TestDimensionsMarshalJSON(t *testing.T) {
require := require.New(t)
var dim Dimensions
dim[Bandwidth] = 1
dim[Compute] = 2
dim[StorageRead] = 3
dim[StorageAllocate] = 4
dim[StorageWrite] = 5

dimJSONBytes, err := dim.MarshalJSON()
require.NoError(err)
require.JSONEq(`{"bandwidth":1,"compute":2,"storageRead":3,"storageAllocate":4,"storageWrite":5}`, string(dimJSONBytes))

var parsedDimJSON Dimensions
require.NoError(parsedDimJSON.UnmarshalJSON(dimJSONBytes))
require.Equal(dim, parsedDimJSON)
}

0 comments on commit 404e74f

Please sign in to comment.