gagliardetto / binary

Encoding/decoding in Borsh and other formats.
Apache License 2.0
20 stars 11 forks source link

binary

Borsh

Decoding borsh

 dec := bin.NewBorshDecoder(data)
 var meta token_metadata.Metadata
 err = dec.Decode(&meta)
 if err != nil {
   panic(err)
 }

Encoding borsh

buf := new(bytes.Buffer)
enc := bin.NewBorshEncoder(buf)
err := enc.Encode(meta)
if err != nil {
  panic(err)
}
// fmt.Print(buf.Bytes())

Optional Types

type Person struct {
    Name string
    Age  uint8 `bin:"optional"`
}

Rust equivalent:

struct Person {
    name: String,
    age: Option<u8>
}

Enum Types

type MyEnum struct {
    Enum  bin.BorshEnum `borsh_enum:"true"`
    One   bin.EmptyVariant
    Two   uint32
    Three int16
}

Rust equivalent:

enum MyEnum {
    One,
    Two(u32),
    Three(i16),
}

Exported vs Unexported Fields

In this example, the two field will be skipped by the encoder/decoder because the field is not exported.

type MyStruct struct {
    One   string
    two   uint32
    Three int16
}

Skip Decoding/Encoding Attributes

Encoding/Decoding of exported fields can be skipped using the borsh_skip tag.

type MyStruct struct {
    One   string
    Two   uint32 `borsh_skip:"true"`
    Three int16
}