tinycbor
tinycbor copied to clipboard
Ability to reset an encoder
Added a method that allows for resetting an encoder (Start writing from the beginning of its allocated buffer space.). This is very useful when you quickly want to discard everything that has currently been encoded by that encoder.
Also, a mixup in the documentation was adjusted (cborencoder.c).
Thank you for the contribution. Let me see if I understand your use-case: you want to use the buffer like a circular buffer, so you can discard what has already been used and simply continue on, without discarding the state?
I think it's a valid use-case, but I have a couple of issues:
- I don't know if I want to store the pointer in the
CborEncoder
structure. Would it make sense to pass the pointer tocbor_encoder_reset
instead? - Maybe call it simply
cbor_encoder_set_buffer
and take both the new begin pointer and size? That way, you can relocate to a new buffer instead of overwriting. - Need to check if there's any API that backtracks and tries to read a byte already written. I don't think they exist anymore, but we need to be sure.
The reason I put a start pointer in the CborEncoder struct was for a scenario where you are somewhere in the code where you don’t have necessarliy have access to a reference to the buffer you are encoding to.
I actually think both a cbor_encoder_reset and a cbor_encoder_set_buffer function could be useful and be used in different scenarios.
If you're somewhere down in the code and don't have the original pointer, how do you know it's ok to reset? The only point in resetting would be after you've read the data out and sent it to the next layer (socket, file, encryption, etc.). For that, you need the begin pointer again.
In my use case, I want to reset before I’ve read it out. Essentially, I have something encoded that I have decided I want to discard, and start over with that encoded message.
Maybe I’m not clear or maybe it’s not good practice?
Your change resets the buffer but does not reset the state. It doesn't make sense to discard the data previously written, since you need it o make sense of what will come next.
I see. If I then would have access to the buffer reference, in the case of cbor_encoder_set_buffer
, would something like this be sufficient or do you also require some state handling?
void cbor_encoder_set_buffer(CborEncoder *enoder, uint8_t *buffer, size_t size)
{
encoder->data.ptr = buffer;
encoder->end = buffer + size;
}
This function is fine. We just need to document that it does not reset the state. If you want a clean state, you can just use cbor_encoder_init
again.