Refine handling of container state synchronisation
When a container is closed, the outer container's buffer state is
synchronised with the inner container's state.
This was previously done via:
```
CborError cbor_encoder_close_container(CborEncoder *encoder, const CborEncoder *containerEncoder)
{
if (encoder->end)
encoder->data.ptr = containerEncoder->data.ptr;
else
encoder->data.bytes_needed = containerEncoder->data.bytes_needed;
encoder->end = containerEncoder->end;
...
return CborNoError;
}
```
However, strictly speaking the inner container could have updated `end` to be `NULL` if
the buffer was too small. In that case, the outer container should carry over `bytes_needed`
and not `ptr`. However, the logic was using the outer container's "stale" view of `end`.
However, generally `sizeof(ptr)` and `sizeof(bytes_needed)` are the same, and these values
exist in a union. Therefore, the correct values where still being copied.
This change moves the synchronisation of `end` to ahead of the synchronisation of `data`.
It additionally, actually avoids this potential error by simply synchronising the full `data`
structure, thereby avoiding the conditional logic. Simplifying the code to simply:
```
encoder->end = containerEncoder->end;
encoder->data = containerEncoder->data;
```
diff --git a/src/cborencoder.c b/src/cborencoder.c
index 928c871..d5c590e 100644
--- a/src/cborencoder.c
+++ b/src/cborencoder.c
@@ -540,11 +540,10 @@
*/
CborError cbor_encoder_close_container(CborEncoder *encoder, const CborEncoder *containerEncoder)
{
- if (encoder->end)
- encoder->data.ptr = containerEncoder->data.ptr;
- else
- encoder->data.bytes_needed = containerEncoder->data.bytes_needed;
+ // synchronise buffer state with that of the container
encoder->end = containerEncoder->end;
+ encoder->data = containerEncoder->data;
+
if (containerEncoder->flags & CborIteratorFlag_UnknownLength)
return append_byte_to_buffer(encoder, BreakByte);
@@ -553,6 +552,7 @@
if (!encoder->end)
return CborErrorOutOfMemory; /* keep the state */
+
return CborNoError;
}