Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Store arbitrary types on [u8; N]? #285

Open
changhe3 opened this issue Aug 19, 2022 · 1 comment
Open

Store arbitrary types on [u8; N]? #285

changhe3 opened this issue Aug 19, 2022 · 1 comment

Comments

@changhe3
Copy link

changhe3 commented Aug 19, 2022

This can be useful for controlling the size of your type when storing some generic type on SmallVec.

struct Container<T> {
   inner: SmallVec<CappedArray<T, 64>> // at most 64 bytes regardless of the size of T
}
use aligned::Aligned;
use core::marker::PhantomData;
use smallvec::Array;

pub struct CappedArray<T, const BYTES: usize> {
    _inner: Aligned<T, [u8; BYTES]>,
    _marker: PhantomData<T>,
}

unsafe impl<T, const BYTES: usize> Array for CappedArray<T, BYTES> {
    type Item = T;

    fn size() -> usize {
        BYTES / core::mem::size_of::<T>()
    }
}

#[cfg(test)]
mod tests {
    extern crate alloc;

    use alloc::boxed::Box;
    use smallvec::SmallVec;

    use super::*;

    #[test]
    fn test_simple() {
        let mut vec = SmallVec::<CappedArray<_, 32>>::new();
        assert!(vec.inline_size() == 4);
        vec.extend((0..4).map(Box::new));
        assert!(!vec.spilled());
        vec.extend((4..8).map(Box::new));
        assert!(vec.spilled());
    }

    #[test]
    fn test_capped_extra() {
        let mut vec = SmallVec::<CappedArray<_, 34>>::new();
        assert!(vec.inline_size() == 4);
        vec.extend((0..4).map(Box::new));
        assert!(!vec.spilled());
        vec.extend((4..8).map(Box::new));
        assert!(vec.spilled());
    }

    #[test]
    fn test_capped_short() {
        let mut vec = SmallVec::<CappedArray<_, 30>>::new();
        assert!(vec.inline_size() == 3);
        vec.extend((0..4).map(Box::new));
        assert!(vec.spilled());
        vec.extend((4..8).map(Box::new));
        assert!(vec.spilled());
    }
}

As expected, only the first test is passed.

@changhe3
Copy link
Author

changhe3 commented Aug 19, 2022

Ok there is this check:

rust-smallvec/src/lib.rs

Lines 564 to 567 in 7fa951f

assert!(
mem::size_of::<A>() == A::size() * mem::size_of::<A::Item>()
&& mem::align_of::<A>() >= mem::align_of::<A::Item>()
);

Not sure if this is possible to satisfy without full const-generics features. I wonder if mem::size_of::<A>() == A::size() * mem::size_of::<A::Item>() could be relaxed to mem::size_of::<A>() >= A::size() * mem::size_of::<A::Item>()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant