spider-gazelle / bindata

BinData - Parsing Binary Data in Crystal Lang
MIT License
48 stars 5 forks source link

Added `verify` arg, for things such as checksums #1

Closed mattrberry closed 4 years ago

mattrberry commented 4 years ago

I was recently using this package, and realized that I wanted a convenient, build-in way to do verification of fields. My first thought was something along the lines of after_initialize similar to JSON::Serializable, but that didn't seem to fit into the pure simplicity of this project.

Instead, I've opted for the following.

class VerifyData < BinData
  endian big

  uint8 :size
  bytes :bytes, length: ->{ size }
  uint8 :checksum, verify: ->{ checksum == bytes.reduce(0) { |acc, i| acc + i } }
end

This change allows verification to happen inline, raising an appropriate, descriptive exception if the verification fails.

At this point, this PR is missing documentation and more extensive testing, and primarly serves as a RFC from the owner.

Let me know what you think! If you like it, I'll go ahead and wrap up documentation and some more thorough testing. If you have anything different you'd like to see, let me know!