11 releases

0.2.0 Oct 11, 2024
0.2.0-beta.0 Jul 8, 2023
0.1.8 Dec 30, 2022
0.1.7 Nov 14, 2022

#11 in #tagged-pointers

Download history 24/week @ 2024-07-03 38/week @ 2024-07-24 14/week @ 2024-07-31 1/week @ 2024-09-04 676/week @ 2024-09-11 473/week @ 2024-09-18 30/week @ 2024-09-25 3/week @ 2024-10-02 217/week @ 2024-10-09 10/week @ 2024-10-16

272 downloads per month
Used in enum-ptr

MIT/Apache

14KB
262 lines

Enum Ptr

crates.io docs.rs

This crate provides a custom derive macro EnumPtr to generate bridges between an enum T and Compact<T> with minimum cost. Compact<T> is the compact representation of T, and it is only one pointer wide. In other words, this crate is a library for defining tagged pointers in ergonomic way, even supporting different pointer types (&, Box, Arc, etc) as different enum variants.

For example, the following code

use enum_ptr::EnumPtr;

#[derive(EnumPtr)]
#[repr(C, usize)]
enum Foo<'a> {
    A(&'a i32),
    B(Box<i32>),
}

will generate

impl<'a> From<Foo<'a>> for Compact<Foo<'a>> {
    // ...
}

impl<'a> From<Compact<Foo<'a>>> for Foo<'a> {
    // ...
}

Since &i32 and Box<i32> are aligned by 4 bytes, the lowest 2 bits of them are always zeros. Compact<Foo<'a>> utilizes these bits to store the tag (discriminant).

Features

  • No need to write unsafe pointer operations
  • Supports various types and can be extended
  • Supports no_std
  • Minimum type conversion cost
  • Passes cargo +nightly miri test with strict provenance enabled.

Testing

$ cargo test
$ cargo +nightly miri test

Credits

  • Thanks to @oxalica for reviewing this crate and providing a lot of helpful suggestions.

License

This project is licensed under either of

at your option.

Dependencies

~0.6–1MB
~24K SLoC