google / google/zerocopy

Add witness type for the size of a memory region

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

Description

EDIT: Maybe we don't need this since we're solving a similar problem with the [`Ptr` type](https://github.com/google/zerocopy/pull/406)?

---

Rust restricts allocations to lengths that fit in an `isize`, and correspondingly requires that most pointer arithmetic doesn't overflow an `isize`. A lot of our code has to reason about this invariant, and currently it's spread across the codebase in a lot of safety comments, but not enforced at the type level.

We should introduce a type that makes this easier:

```rust
struct AllocSize(isize); // invariant: always non-negative

impl AllocSize {
fn from_val(t: &T) -> AllocSize {
// SAFETY: No Rust object can have a size larger than `isize`.
unsafe { AllocSize::new_unchecked(mem::size_of_val(t)) }
}

/// # Safety
///
/// `size` must not overflow `isize`.
unsafe fn new_unchecked(size: usize) -> AllocSize { AllocSize(size as isize) }
}
```

This will allow us to make it clear when a function requires a value which represents an allocation size (today, many such functions just take `usize`), and will require callers who don't _already_ have an `AllocSize` to make it clear that they're claiming to uphold an invariant manually by needing to construct one.

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.