#capacity #manually-drop #peckr #packed-box

no-std peckr

Rust pointer type that allows packing additional data along with the underlying memory offset

3 unstable releases

new 0.6.1 Apr 11, 2025
0.6.0 Apr 8, 2025
0.5.0 Apr 8, 2025

#12 in #capacity

Download history 248/week @ 2025-04-05

252 downloads per month

MIT license

19KB
319 lines

peckr

Rust pointer type that allows packing additional data along with the underlying memory offset.


lib.rs:

Pointer type that allows packing additional data along with the underlying memory offset.

Example usage

To demonstrate the usage of this crate, we shall define an EitherBox abstraction that does not require additional storage to keep track of its variant, other than one bit that is stored inline with the memory offset of the packed pointer.

use std::mem::ManuallyDrop;

use peckr::PackedBox;

union EitherUnion<L, R> {
    left: ManuallyDrop<L>,
    right: ManuallyDrop<R>,
}

struct EitherBox<L, R> {
    inner: PackedBox<1, EitherUnion<L, R>>,
}

enum Either<L, R> {
    Left(L),
    Right(R),
}

impl<L, R> EitherBox<L, R> {
    fn left(value: L) -> Self {
        let inner = PackedBox::new(EitherUnion {
            left: ManuallyDrop::new(value),
        })
        .unwrap();
        Self { inner }
    }

    fn right(value: R) -> Self {
        let mut inner = PackedBox::new(EitherUnion {
            right: ManuallyDrop::new(value),
        })
        .unwrap();
        inner.set_bit_high(0);
        Self { inner }
    }

    fn get_ref(&self) -> Either<&L, &R> {
        match self.inner.get_bit(0) {
            false => Either::Left(unsafe { &self.inner.left }),
            true => Either::Right(unsafe { &self.inner.right }),
        }
    }
}

No runtime deps

Features