Guest User

Untitled

a guest
Oct 18th, 2018
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.79 KB | None | 0 0
  1. const ELEMENTS_PER_PAGE: usize = 1024;
  2.  
  3. type Page<T> = ArrayVec<[T; ELEMENTS_PER_PAGE]>;
  4.  
  5. pub struct ConstVec<T> {
  6. // storage, which holds the actual pages
  7. pages: Mutex<Box<[*mut Page<T>]>>,
  8. // points to the storage. Used for wait-free access.
  9. pages_pointer: AtomicPtr<*mut Page<T>>,
  10. len: AtomicUsize,
  11. }
  12.  
  13. const fn page_index(index: usize) -> usize {
  14. index / ELEMENTS_PER_PAGE
  15. }
  16.  
  17. const fn element_index(index: usize) -> usize {
  18. index % ELEMENTS_PER_PAGE
  19. }
  20.  
  21. pub fn len(&self) -> usize {
  22. self.len.load(atomic::Ordering::Acquire) // 1
  23. }
  24.  
  25. pub fn push(&self, value: T) {
  26. let mut pages = self.pages.lock().unwrap();
  27.  
  28. let index = self.len.load(atomic::Ordering::Acquire); // 1
  29. let page_index = Self::page_index(index);
  30.  
  31. // do we need an new page?
  32. if page_index == pages.len() {
  33. // allocate a new vector, which will replace the old one
  34. // and copy old elements into it.
  35. let mut new_pages = Vec::with_capacity(page_index + 1);
  36. new_pages.extend(pages.iter().cloned());
  37. new_pages.push(Box::into_raw(Box::new(Page::new()))); // 2
  38.  
  39. // Update the pages pointer first. This will be used
  40. // to receive data. The pointers remains valid.
  41. self.pages_pointer
  42. .store(new_pages.as_mut_ptr(), atomic::Ordering::SeqCst); // 1
  43. // replace "vector"
  44. mem::replace(pages.deref_mut(), new_pages.into_boxed_slice());
  45. }
  46. unsafe {
  47. (*pages[page_index]).push(value); // 2
  48. }
  49. self.len.store(index + 1, atomic::Ordering::Release); // 1
  50. }
  51.  
  52. fn drop(&mut self) {
  53. for page_ptr in self.pages.lock().unwrap().iter() {
  54. unsafe { Box::from_raw(*page_ptr) }; // 2
  55. }
  56. }
Add Comment
Please, Sign In to add comment