Guest User

Untitled

a guest
Oct 17th, 2018
156
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.28 KB | None | 0 0
  1. use std::ptr;
  2. use std::sync::atomic::{ AtomicPtr, Ordering };
  3.  
  4. struct List<T> {
  5. head: AtomicPtr<Node<T>>,
  6. }
  7.  
  8. impl<T> List<T> {
  9. pub fn new() -> Self {
  10. let first = Node::new(None);
  11. List {
  12. head: AtomicPtr::new(first),
  13. }
  14. }
  15.  
  16. pub fn head(self) -> Node<T> {
  17. *Box::from(self.head)
  18. }
  19.  
  20. pub fn tail(self) -> List<T> {
  21. List {
  22. head: self.head().next
  23. }
  24. }
  25. }
  26.  
  27. struct Node<T> {
  28. value: Option<T>,
  29. next: AtomicPtr<Node<T>>,
  30. }
  31.  
  32. impl<T> From<AtomicPtr<Node<T>>> for Box<Node<T>> {
  33. fn from(aptr: AtomicPtr<Node<T>>) -> Box<Node<T>> {
  34. let ptr = ptr::null_mut();
  35. loop {
  36. aptr.swap(ptr, Ordering::SeqCst);
  37. if ptr == ptr::null_mut() {
  38. continue;
  39. } else {
  40. break;
  41. }
  42. }
  43. unsafe {
  44. Box::from_raw(ptr)
  45. }
  46. }
  47. }
  48.  
  49. impl<T> Node<T> {
  50. pub fn new(value: Option<T>) -> *mut Self {
  51. let b = Box::new(Node {
  52. value,
  53. next: AtomicPtr::new(ptr::null_mut()),
  54. });
  55. Box::into_raw(b)
  56. }
  57. }
  58.  
  59. #[cfg(test)]
  60. mod tests {
  61. use super::*;
  62.  
  63. #[test]
  64. fn empty_list() {
  65. let lst: List<f64> = List::new();
  66. assert_eq!(lst.head().value, None);
  67. }
  68. }
Add Comment
Please, Sign In to add comment