safe_buffer/
list.rs

1pub trait MoveTo<T> {
2    fn at(&mut self, pos: usize) -> &mut T;
3    fn move_to(&mut self, pos: usize);
4}
5
6impl<'a, T: 'a, A: Allocator> MoveTo<T> for std::collections::linked_list::CursorMut<'a, T, A> {
7    fn at(&mut self, pos: usize) -> &mut T {
8        self.move_to(pos);
9        self.current().unwrap()
10    }
11
12    fn move_to(&mut self, pos: usize) {
13        // if we are on the ghost element, find the correct end to start at
14        let current = match self.index() {
15            Some(i) => i,
16            None => {
17                let length = self.as_list().len();
18                if length == 0 { return; }
19
20                // choose where to start
21                if pos < length - pos {
22                    self.move_next();
23                    0
24                } else {
25                    self.move_prev();
26                    length - 1
27                }
28            }
29        };
30
31        let diff = current as isize - pos as isize;
32        if diff == 0 { return; }
33
34        // we always reach the correct index, since the cursor is circular
35        // however we try to move in the correct direction to reduce calls!
36        while self.index() != Some(pos) {
37            if diff < 0 {
38                self.move_next();
39            } else {
40                self.move_prev();
41            }
42        }
43
44        assert_eq!(self.index().unwrap(), pos);
45    }
46}