google / google/zerocopy

`FromBytes::insert_vec_from_bytes`

Open
#2,243 0 comments 1 reaction 0 assignees View on GitHub
Dominant language
Rust
Stars
2.6k
Forks
179
Avg merge
1d 19h
Merged PRs (30d)
29

Description

`FromBytes::insert_vec_from_bytes` is like `FromZeros::insert_vec_zeroed`, but accepts `bytes: &[u8]` to copy instead of an `additional: usize` zeroed elements to insert. It's an optimization of:

```rust
if bytes.len().checked_rem(size_of::()).unwrap_or(bytes.len()) != 0 {
return Err(/* bytes.len() is not a multiple of the size of T */);
}
let additional = bytes.len().checked_div(size_of::()).unwrap_or(0);
T::insert_vec_zeroed(&mut values, position, additional)?;
// The panic should be optimized away due to the above rem check.
values[position..position + additional].as_mut_bytes().copy_from_slice(bytes);
```

- It should not have a zeroing memory step.
- The capacity * `size_of::()` of the returned `Vec` should match the size of the input to ensure `into_boxed_slice` doesn't need to realloc.
- `bytes` does not need to be aligned, same as `read_from_bytes`.
- Note that if T is a ZST, then the only valid input for `bytes` is `&[]`, which is a no-op.
- `extend_vec_from_bytes` is also included in this design, with no `position` parameter.
- `FromBytes::new_vec_from_bytes(bytes: &[u8])` copies into a new `Vec`
- Open question: should it panic when `position > v.len()` given #2242?
- Open question: what's the best `Err` return type?

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.