Skip to content

Commit c49bb8f

Browse files
sgebbiethiagomacieira
authored andcommitted
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; ```
1 parent 71ce609 commit c49bb8f

File tree

1 file changed

+4
-4
lines changed

1 file changed

+4
-4
lines changed

src/cborencoder.c

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -540,11 +540,10 @@ CborError cbor_encoder_create_map(CborEncoder *encoder, CborEncoder *mapEncoder,
540540
*/
541541
CborError cbor_encoder_close_container(CborEncoder *encoder, const CborEncoder *containerEncoder)
542542
{
543-
if (encoder->end)
544-
encoder->data.ptr = containerEncoder->data.ptr;
545-
else
546-
encoder->data.bytes_needed = containerEncoder->data.bytes_needed;
543+
// synchronise buffer state with that of the container
547544
encoder->end = containerEncoder->end;
545+
encoder->data = containerEncoder->data;
546+
548547
if (containerEncoder->flags & CborIteratorFlag_UnknownLength)
549548
return append_byte_to_buffer(encoder, BreakByte);
550549

@@ -553,6 +552,7 @@ CborError cbor_encoder_close_container(CborEncoder *encoder, const CborEncoder *
553552

554553
if (!encoder->end)
555554
return CborErrorOutOfMemory; /* keep the state */
555+
556556
return CborNoError;
557557
}
558558

0 commit comments

Comments
 (0)