sealmove / binarylang

Binary parser/encoder DSL
MIT License
59 stars 0 forks source link

Fancy operations and how to implement them #30

Open arkanoid87 opened 1 year ago

arkanoid87 commented 1 year ago

The more I use binarylang the more I like it, there's no way back now :)

I have to deal with fields that are not supported out of the box by binarylang and requires further processing after decoding, so I'm ending up writing some operations, like reading strings containing hex encoded bytes in little-endian order into integers

for example for uint8 and uint16

func fromLeHexInt8*(leInt: uint8): string =
  result = leInt.toHex
  assert result.len == 2

func toLeHexInt8*(s: string): uint8 =
  assert s.len == 2
  s.parseHexInt().uint8

func fromLeHexInt16*(leInt: uint16): string =
  let buffer = 0u16
  bigEndian16(buffer.addr, leInt.addr)
  result = buffer.toHex
  assert result.len == 4

func toLeHexInt16*(s: string): uint16 =
  assert s.len == 4
  let leInt = s.parseHexInt().uint16
  bigEndian16(result.addr, leInt.addr)

# -------------------------------

template leHex8Get*(parse, parsed, output: untyped) =
  parse
  output = toLeHexInt8(parsed)

template leHex8Put*(encode, encoded, output: untyped) =
  output = fromLeHexInt8(encoded)
  encode

template leHex16Get*(parse, parsed, output: untyped) =
  parse
  output = toLeHexInt16(parsed)

template leHex16Put*(encode, encoded, output: untyped) =
  output = fromLeHexInt16(encoded)
  encode

in binarylang open for contributions in this direction, to cover more common cases like this, or is it intended to stay lean and clean and let users provide their own ops?

thanks

sealmove commented 1 year ago

Hello @arkanoid87!

Thank you for using binarylang! The answer to your question is "both". You should make an MR with your template definitions. They will become part of the binarylang template library.