Skip to content

Commit

Permalink
minor update to documentation
Browse files Browse the repository at this point in the history
  • Loading branch information
fardream committed Nov 17, 2022
1 parent 46654c7 commit a31a2d9
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 4 deletions.
24 changes: 21 additions & 3 deletions bcs/encode.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,15 @@ func NewEncoder(w io.Writer) *Encoder {
}

// Encode a value v into the encoder.
//
// - If the value is [Marshaler], then the corresponding
// MarshalBCS implementation will be called.
// - If the value is [Enum], then it will be special handled for enum.
func (e *Encoder) Encode(v any) error {
return e.encode(reflect.ValueOf(v))
}

// encode a value with the tagValue.
// tagValue can be optional or ignore, and tagValue should not be passed onto
// sub encodings.
// encode a value
func (e *Encoder) encode(v reflect.Value) error {
kind := v.Kind()

Expand Down Expand Up @@ -73,6 +75,7 @@ func (e *Encoder) encode(v reflect.Value) error {
}
}

// encodeEnum encodes an [Enum]
func (e *Encoder) encodeEnum(v reflect.Value) error {
t := v.Type()

Expand Down Expand Up @@ -195,6 +198,11 @@ func (e *Encoder) encodeStruct(v reflect.Value) error {
//
// Pointers are serialized as the type they point to. Nil pointers will be serialized
// as zero value of the type they point to unless it's marked as `optional`.
//
// During marshalling process, how v is marshalled depends on if v implemented [Marshaler] or [Enum]
// 1. First priority is [Marshaler]
// 2. Then, check if value v is [Enum]
// 3. Then, run the standard process.
func Marshal(v any) ([]byte, error) {
var b bytes.Buffer
e := NewEncoder(&b)
Expand All @@ -205,3 +213,13 @@ func Marshal(v any) ([]byte, error) {

return b.Bytes(), nil
}

// MustMarshal [Marshal] v, [panic] if error.
func MustMarshal(v any) []byte {
result, err := Marshal(v)
if err != nil {
panic(err)
}

return result
}
4 changes: 3 additions & 1 deletion bcs/enum.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,10 @@ package bcs
// V1 *uint16 `bcs:"-"` // ignored, so variant 1 is invalid
// V2 int `bcs:"-"` // cannot be set to nil, so variant 2 is invalid
// V3 *uint8 // variant 3
// v4 uint32 // ignored
// v4 uint32 // Unexported, so ignored.
// }
// // IsBcsEnum doesn't do anything besides indicating this is an Enum for BCS.
// func (a AEnum) IsBcsEnum() {}
//
// If there are mulitple non-nil fields when marshalling, the first one encountered will be serialized.
//
Expand Down

0 comments on commit a31a2d9

Please sign in to comment.