Skip to content

Instantly share code, notes, and snippets.

@hansihe
Last active April 3, 2017 16:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hansihe/f8c4fa0b59bfd9044ec677e9639489f0 to your computer and use it in GitHub Desktop.
Save hansihe/f8c4fa0b59bfd9044ec677e9639489f0 to your computer and use it in GitHub Desktop.
Anon explaination

Say you have a type as such:

["container", [
  {
    "name": "random_field",
    "type": "u8"
  },
  {
    "name": "tag_field",
    "type": "u8"
  },
  {
    "name": "inner",
    "type": ["switch", {
      "compareTo": "tag_field",
      "fields": {
        "0": ["container", [
          {
            "name": "inner_field",
            "type": "u8"
          }
        ]],
        "1": ["container", [
          {
            "name": "other_inner_field",
            "type": "u8"
          }
        ]]
      },
    }]
  }
]]

Depending on the value of tag_field, this will be deserialized into one of two variants:

{
  "random_field": 0,
  "tag_field": 0,
  "inner": {
    "inner_field": 0
  }
}

or

{
  "random_field": 0,
  "tag_field": 1,
  "inner": {
    "other_inner_field": 0
  }
}

When using this, writing data.inner.inner_field and data.inner.other_inner_field can be a bit tedious, especially when composing types together.

This is the reason why anon exists on container fields.

It allows you to write a type like this:

["container", [
  {
    "name": "random_field",
    "type": "u8"
  },
  {
    "name": "tag_field",
    "type": "u8"
  },
  {
    "anon": true,
    "type": ["switch", {
      "compareTo": "tag_field",
      "fields": {
        "0": ["container", [
          {
            "name": "inner_field",
            "type": "u8"
          }
        ]],
        "1": ["container", [
          {
            "name": "other_inner_field",
            "type": "u8"
          }
        ]]
      },
    }]
  }
]]

Now, both inner_field and other_inner_field will be placed directly in the enclosing container. When accessing them, you only need to do this: data.inner_field and `data.other_inner_field``

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment