1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
use {Cursor, PendingRef, Pointer, PointerData, Slice};
use std::marker::PhantomData;
use std::ops;


impl<'a, T> Slice<'a, T> {
    /// Check if the slice contains no elements.
    pub fn is_empty(&self) -> bool {
        self.slice.is_empty()
    }

    /// Get a reference by pointer. Returns None if an element
    /// is outside of the slice.
    pub fn get(&'a self, pointer: &Pointer<T>) -> Option<&'a T> {
        debug_assert_eq!(pointer.data.get_storage_id(), self.offset.get_storage_id());
        let index = pointer.data.get_index().wrapping_sub(self.offset.get_index());
        self.slice.get(index as usize)
    }

    /// Get a mutable reference by pointer. Returns None if an element
    /// is outside of the slice.
    pub fn get_mut(&'a mut self, pointer: &Pointer<T>) -> Option<&'a mut T> {
        debug_assert_eq!(pointer.data.get_storage_id(), self.offset.get_storage_id());
        let index = pointer.data.get_index().wrapping_sub(self.offset.get_index());
        self.slice.get_mut(index as usize)
    }
}

/// Item of the streaming iterator.
///
/// [`Cursor`](struct.Cursor.html) and `CursorItem` are extremely useful
/// when you need to iterate over [`Pointers`](struct.Pointer.html) in storage
/// with ability to get other component in the same storage during iterating.
///
/// # Examples
/// Unfortunately, you can't use common `for` loop,
/// but you can use `while let` statement:
///
/// ```rust
/// # let mut storage: froggy::Storage<i32> = froggy::Storage::new();
/// let mut cursor = storage.cursor();
/// while let Some(item) = cursor.next() {
///    // ... your code
/// }
///
/// ```
/// While iterating, you can [`pin`](struct.CursorItem.html#method.pin) item
/// with Pointer.
///
/// ```rust
/// # use froggy::WeakPointer;
/// #[derive(Debug, PartialEq)]
/// struct Node {
///    pointer: Option<WeakPointer<Node>>,
/// }
/// //...
/// # fn do_something(_: &Node) {}
/// # fn try_main() -> Result<(), froggy::DeadComponentError> {
/// # let mut storage = froggy::Storage::new();
/// # let ptr1 = storage.create(Node { pointer: None });
/// # let ptr2 = storage.create(Node { pointer: None });
/// # storage[&ptr1].pointer = Some(ptr2.downgrade());
/// # storage[&ptr2].pointer = Some(ptr1.downgrade());
/// let mut cursor = storage.cursor();
/// while let Some((left, mut item, _)) = cursor.next() {
///    // let's look for the other Node
///    match item.pointer {
///        Some(ref pointer) => {
///            let ref pointer = pointer.upgrade()?;
///            if let Some(ref other_node) = left.get(pointer) {
///                do_something(other_node);
///            }
///        },
///        None => {},
///    }
/// }
/// # Ok(())
/// # }
/// # fn main() { try_main(); }
#[derive(Debug)]
pub struct CursorItem<'a, T: 'a> {
    item: &'a mut T,
    pending: &'a PendingRef,
    data: PointerData,
}

impl<'a, T> ops::Deref for CursorItem<'a, T> {
    type Target = T;
    fn deref(&self) -> &T {
        self.item
    }
}

impl<'a, T> ops::DerefMut for CursorItem<'a, T> {
    fn deref_mut(&mut self) -> &mut T {
        self.item
    }
}

impl<'a, T> CursorItem<'a, T> {
    /// Pin the item with a strong pointer.
    pub fn pin(&self) -> Pointer<T> {
        let epoch = {
            let mut pending = self.pending.lock();
            pending.add_ref.push(self.data.get_index());
            pending.get_epoch(self.data.get_index())
        };
        Pointer {
            data: self.data.with_epoch(epoch),
            pending: self.pending.clone(),
            marker: PhantomData,
        }
    }
}

impl<'a, T> Cursor<'a, T> {
    fn split(&mut self, index: usize) -> (Slice<T>, CursorItem<T>, Slice<T>) {
        let data = PointerData::new(index, 0, self.storage_id);
        let (left, item, right) = self.storage.split(data);
        let item = CursorItem {
            item, data,
            pending: self.pending,
        };
        (left, item, right)
    }

    /// Advance the stream to the next item.
    pub fn next(&mut self) -> Option<(Slice<T>, CursorItem<T>, Slice<T>)> {
        loop {
            let id = self.index;
            self.index += 1;
            match self.storage.meta.get(id) {
                None => {
                    self.index = id; // prevent the bump of the index
                    return None;
                },
                Some(&0) => (),
                Some(_) => return Some(self.split(id)),
            }
        }
    }

    /// Advance the stream to the previous item.
    pub fn prev(&mut self) -> Option<(Slice<T>, CursorItem<T>, Slice<T>)> {
        loop {
            if self.index == 0 {
                return None
            }
            self.index -= 1;
            let id = self.index;
            debug_assert!(id < self.storage.meta.len());
            if *unsafe { self.storage.meta.get_unchecked(id) } != 0 {
                return Some(self.split(id));
            }
        }
    }
}