AndrewSpittlemeister / bytechomp

A pure python declarative custom binary protocol parser & generator using dataclasses and type hinting. Like Pydantic for binary protocols.
MIT License
38 stars 7 forks source link

Optional fields #1

Open elkarouh opened 1 year ago

elkarouh commented 1 year ago

Hi,

I wondered how you would handle an optional field, indicated by a presence flag?

Regards

AndrewSpittlemeister commented 1 year ago

In it's current form, it isn't able to handle optional fields. It is only able to handle static message structures. I do have in my future plans (i.e. when I get around to working on this project more) to have parameterized fields. I think what you are talking about would fit this description. This is where a field is parameterized in some way by a field that has been parsed before it. This should be possible to implement, just would need to add some logic to the parsing to be able to look back at previous fields.

With that being said, I think how this would be implemented from a user's perspective might look something like this:

from typing import Optional
from bytechomp import dataclass, Annotated

@dataclass
class InnerMessage:
    key: str
    val: str

class OuterMessage:
    identity: str
    tag: bool
    inner: Annotated[Optional[InnerMessage], "tag"]

This would signal to the parser that a previously defined field at the same level in nested data structure should be used to continue parsing the inner data structure or just stop and populate it with a None.

I keep myself pretty busy with full-time work and getting a Master's degree, but I do catch some free time every once and a while. That being said, pull requests are always welcome and encouraged.