Skip to content

back_to_the_buffer cannot easily be used recursively #36

@tom-a-wagner

Description

@tom-a-wagner

As the title says, back_to_the_buffer can not easily be used from within another back_to_the_buffer call, which makes it hard to serialize some nested formats.

The default/recommended way to use back_to_the_buffer would be to use gen(<serializer>) inside the gen closure like in the docs.

back_to_the_buffer(
    4,
    move |buf| gen(string("test"), buf), // < this line
    move |buf, len| gen_simple(be_u32(len as u32), buf)
)

However, this wraps buf in a second WriteContext, so that the serializer is called with a WriteContext<WriteContext<W: Write + BackToTheBuffer>>.
With this, we can no longer call back_to_the_buffer again, since it requires a WriteContext<W: Write + BackToTheBuffer>.

It took me quite a while to come up with this solution: (adapted to the doc example)

back_to_the_buffer(
    4,
    move |buf| {
        let begin = buf.position;
        (string("test")(buf)).map(|wctx| {
            let pos = wctx.position;
            (wctx, pos - begin)
        })
    },
    move |buf, len| gen_simple(be_u32(len as u32), buf)
)

Now back_to_the_buffer could be called again in the stringcombinator.

Could this be fixed/made easier in a nice way?
If not, maybe this example could at least be added to the docs so that others don't run into the same wall as I did.

Thanks!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions