google / google/zerocopy

Make as much of zerocopy as possible work in a const context

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

Description

Currently, most of zerocopy's abstractions don't work in a const context for one reason or another. We should change that as much as possible.

This is a blocker for [ICU4X using zerocopy](https://github.com/unicode-org/icu4x/issues/2798).

## Trait methods

One large subset of the API is the set of trait methods. Most or all of these don't rely on calling other trait methods, but effectively just use the trait bound to guarantee that the operation is sound. This entire subset in principle ought to be representable as bare functions, and many of them would likely be convertible into `const fn`s. We could of course keep the trait methods as well, and just implement them in terms of the functions.

This approach has two big downsides:
- It would effectively duplicate a large subset of our API surface
- We would probably want to remove the bare functions in a future release once all of the trait methods could themselves be const (it's not clear to me how far off this is)

## `TryFromBytes`

Our derive for `TryFromBytes` automatically derives the `is_bit_valid` method. In order to support `const` `TryFromBytes`, we would need to:
- Emit an inherent `#[doc(hidden)] pub fn __zerocopy_is_bit_valid(...) -> bool`
- Rewrite our impl of `TryFromBytes::is_bit_valid` to call this function
- Possibly provide an attribute to allow renaming that function for macro hygiene reasons
- Note: It's unclear whether this would work at all since other const code needs to be able to call the function at a well-known name
- If it doesn't work on our MSRV, we could just make it an optional `zerocopy-derive` feature (which is exposed via `zerocopy` with a feature of the same or similar name)

Note a very fundamental limitation: There would be no way to support generic types (e.g., `#[derive(TryFromBytes)] struct Foo(T)`) because the only way to invoke the function would be to name the type it operates on (e.g., `Foo::__zerocopy_is_bit_valid(...)`). This also means that the public API would need to be a macro in order to emit the appropriate code.

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.