Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use std::cmp::PartialOrd;
- use std::ops::{Drop, Index, IndexMut};
- #[repr(C)]
- pub struct CountPrefixedArray<C, T>
- where C: Into<usize> + Copy
- {
- pub(crate) count: C,
- pub(crate) items: T,
- }
- impl<C, T> CountPrefixedArray<C, T>
- where
- C: Into<usize> + Copy,
- {
- fn extra_size_required(count: C) -> usize {
- std::mem::size_of::<T>() * (count.into() - 1)
- }
- }
- impl<C, T> Index<usize> for CountPrefixedArray<C, T>
- where C: Into<usize> + Copy
- {
- type Output = T;
- fn index(&self, index: usize) -> &Self::Output {
- if index >= self.count.into() {
- panic!("index out of bounds");
- }
- unsafe { &*(&self.items as *const T).offset(index as isize) }
- }
- }
- impl<C, T> IndexMut<usize> for CountPrefixedArray<C, T>
- where C: Into<usize> + Copy
- {
- fn index_mut(&mut self, index: usize) -> &mut Self::Output {
- if index >= self.count.into() {
- panic!("index out of bounds");
- }
- unsafe { &mut *(&mut self.items as *mut T).offset(index as isize) }
- }
- }
- #[repr(C)]
- struct Foo {
- bar: u64,
- baz: CountPrefixedArray<usize, u8>,
- }
- impl Foo {
- fn new(items: &[u8]) -> Box<Foo> {
- let required_size = std::mem::size_of::<Self>()
- + CountPrefixedArray::<usize, u8>::extra_size_required(items.len());
- let data = vec![0u8; required_size].into_boxed_slice();
- let mut ret = unsafe { Box::from_raw(Box::into_raw(data) as *mut Self) };
- ret.baz.count = items.len();
- for (idx, val) in items.iter().enumerate() {
- ret.baz[idx] = *val;
- }
- ret
- }
- }
- fn main() {
- let mut data = Foo::new(&[0, 1, 2, 3, 4, 5]);
- for i in 0..data.baz.count {
- println!("{:?}", data.baz[i])
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement