google / google/zerocopy

Cloning DSTs by bytes

Open
#2,275 4 comments 0 reactions 0 assignees View on GitHub
customer-request
Dominant language
Rust
Stars
2.6k
Forks
179
Avg merge
1d 19h
Merged PRs (30d)
29

Description

Working with DSTs is much improved but is still challenging - especially owned DSTs. Being able to simply perform a bytewise clone into a `Box` would be very helpful. I propose it be derived via `ByteClone`.

While you _can_ `impl Clone for Box` due to [it being `#[fundamental]`](https://stackoverflow.com/a/59023737) and `derive(ByteClone)` probably should, there's no built-in trait for `&self -> Box`. So, this should also define a local `ByteClone` trait or something similar to generically define this.

Sample:

```rust
// In zerocopy:
pub trait ByteClone: KnownLayout + IntoBytes + FromBytes {
fn byte_clone(&self) -> Self where Self: Sized;
fn byte_clone_box(&self) -> Box;
}

// In local crate:
#[derive(ByteClone, IntoBytes, FromBytes, Immutable, KnownLayout)]
#[repr(C)]
struct Foo([u8]);

// Generates:

// This `for<'a>` trick is useful for macros to conditionally implement functionality
// on a concrete type dependent on a maybe-implemented trait.
impl Clone for Foo where for<'a> Foo: Sized {
fn clone(&self) -> Self { self.byte_clone() }
}

impl ByteClone for Foo {
fn byte_clone(&self) -> Self where for<'a> Self: Sized {
Self::read_from_bytes(self.as_bytes()).unwrap()
}

fn byte_clone_box(&self) -> Box {
Foo::read_box_from_bytes(self.as_bytes()).unwrap()
}
}

impl Clone for Box {
fn clone(&self) -> Self {
::byte_clone_box(self.as_bytes())
}
}

```

- This requires #2258 and the ability to construct a `Box` from existing bytes for `?Sized`.
- Like in #2274, this bytewise clone can also optimize better than field-wise derived clone for `Sized + !Copy` types.
- Naming: `fn byte_clone` or `fn clone_bytes`? I like the readability of `verb-noun`, especially with `clone_bytes_to_box` instead of `byte_clone_box`. If `clone_bytes` is preferred, then should the trait be named `CloneBytes`? ~Then https://github.com/google/zerocopy/issues/2274#issuecomment-2622909611 should apply for consistency.~ `ByteHash` is already implemented.

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.