Skip to content

feat(containers): add function to decode Vec with given body len#245

Open
kskalski wants to merge 1 commit intoanza-xyz:masterfrom
kskalski:ks/decode_vec_body
Open

feat(containers): add function to decode Vec with given body len#245
kskalski wants to merge 1 commit intoanza-xyz:masterfrom
kskalski:ks/decode_vec_body

Conversation

@kskalski
Copy link
Contributor

It's often useful to decode just vector's body with known length (which in hand-tuned serialization formats may be stored in other fields or implied from previously decoded data).

Add function wincode::containers::Vec::<T, SeqLen>::decode_body_with_len::<ConfigCore>(reader, len) that does:

  • prealloc check based on SeqLen<ConfigCore>
  • allocate vector with enough capacity
  • copy into properly sized slice of space capacity
  • set len of allocated vec

T: SchemaRead<'de, C>,
{
Len::prealloc_check::<T>(len)?;
let mut vec: vec::Vec<T::Dst> = vec::Vec::with_capacity(len);
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maybe a better idea would be to provide Box<[T]> decoding instead - Vec should be trivial to create from box and with Box::<[T]>::new_uninit_slice we get exactly the requested capacity

@kskalski kskalski marked this pull request as ready for review March 18, 2026 09:10
@kskalski kskalski requested a review from cpubot March 18, 2026 09:10
Len: SeqLen<C>,
T: SchemaRead<'de, C>,
{
Len::prealloc_check::<T>(len)?;

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shouldn't this use Len::read_prealloc_check::<T::Dst>(reader.by_ref())? ?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No, read_prealloc_check reads the length from the reader and the point of this API is to use len provided in fn parameter instead of reading it. We still want to validate the length against the limit defined by Len: SeqLen<C>, the call here does exactly (and only) that.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah sorry, I got confused I meant Len::prealloc_check::<T::Dst>(reader.by_ref())?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh, it should be Len::prealloc_check::<T::Dst>(len)?, right.

@kskalski kskalski force-pushed the ks/decode_vec_body branch from 3f47340 to 35352dc Compare March 18, 2026 15:33
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants