Skip to content

Commit

Permalink
Merge pull request #135 from jtraglia/epoch-json-marshal-funcs
Browse files Browse the repository at this point in the history
Add Marshaling functions for Epoch
  • Loading branch information
mcdee authored May 6, 2024
2 parents 68ba357 + ed02a7f commit 3e81eac
Showing 1 changed file with 38 additions and 0 deletions.
38 changes: 38 additions & 0 deletions spec/phase0/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,47 @@

package phase0

import (
"bytes"
"fmt"
"strconv"

"github.com/pkg/errors"
)

// Epoch is an epoch number.
type Epoch uint64

// UnmarshalJSON implements json.Unmarshaler.
func (e *Epoch) UnmarshalJSON(input []byte) error {
if len(input) == 0 {
return errors.New("input missing")
}
if len(input) < 3 {
return errors.New("input malformed")
}

if !bytes.HasPrefix(input, []byte{'"'}) {
return errors.New("invalid prefix")
}
if !bytes.HasSuffix(input, []byte{'"'}) {
return errors.New("invalid suffix")
}

val, err := strconv.ParseUint(string(input[1:len(input)-1]), 10, 64)
if err != nil {
return errors.Wrapf(err, "invalid value %s", string(input[1:len(input)-1]))
}
*e = Epoch(val)

return nil
}

// MarshalJSON implements json.Marshaler.
func (e Epoch) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%d"`, e)), nil
}

// CommitteeIndex is a committee index at a slot.
type CommitteeIndex uint64

Expand Down

0 comments on commit 3e81eac

Please sign in to comment.