Advertisement
Guest User

Untitled

a guest
Jul 21st, 2019
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.72 KB | None | 0 0
  1. use std::cmp::PartialOrd;
  2. use std::ops::{Drop, Index, IndexMut};
  3.  
  4. #[repr(C)]
  5. pub struct CountPrefixedArray<C, T>
  6. where C: Into<usize> + Copy
  7. {
  8. pub(crate) count: C,
  9. pub(crate) items: T,
  10. }
  11.  
  12. impl<C, T> CountPrefixedArray<C, T>
  13. where
  14. C: Into<usize> + Copy,
  15. {
  16. fn extra_size_required(count: C) -> usize {
  17. std::mem::size_of::<T>() * (count.into() - 1)
  18. }
  19. }
  20.  
  21. impl<C, T> Index<usize> for CountPrefixedArray<C, T>
  22. where C: Into<usize> + Copy
  23. {
  24. type Output = T;
  25.  
  26. fn index(&self, index: usize) -> &Self::Output {
  27. if index >= self.count.into() {
  28. panic!("index out of bounds");
  29. }
  30.  
  31. unsafe { &*(&self.items as *const T).offset(index as isize) }
  32. }
  33. }
  34.  
  35. impl<C, T> IndexMut<usize> for CountPrefixedArray<C, T>
  36. where C: Into<usize> + Copy
  37. {
  38. fn index_mut(&mut self, index: usize) -> &mut Self::Output {
  39. if index >= self.count.into() {
  40. panic!("index out of bounds");
  41. }
  42.  
  43. unsafe { &mut *(&mut self.items as *mut T).offset(index as isize) }
  44. }
  45. }
  46.  
  47. #[repr(C)]
  48. struct Foo {
  49. bar: u64,
  50. baz: CountPrefixedArray<usize, u8>,
  51. }
  52.  
  53. impl Foo {
  54. fn new(items: &[u8]) -> Box<Foo> {
  55. let required_size = std::mem::size_of::<Self>()
  56. + CountPrefixedArray::<usize, u8>::extra_size_required(items.len());
  57.  
  58. let data = vec![0u8; required_size].into_boxed_slice();
  59. let mut ret = unsafe { Box::from_raw(Box::into_raw(data) as *mut Self) };
  60. ret.baz.count = items.len();
  61.  
  62. for (idx, val) in items.iter().enumerate() {
  63. ret.baz[idx] = *val;
  64. }
  65.  
  66. ret
  67. }
  68. }
  69.  
  70. fn main() {
  71. let mut data = Foo::new(&[0, 1, 2, 3, 4, 5]);
  72. for i in 0..data.baz.count {
  73. println!("{:?}", data.baz[i])
  74. }
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement