1 | use core::ops::{Add, AddAssign, Sub, SubAssign}; |
2 | |
3 | #[derive (Debug)] |
4 | pub struct MachineCursor<'a, T, F> { |
5 | data: &'a [T], |
6 | pred: F, |
7 | pos: usize, |
8 | } |
9 | |
10 | impl<'a, T, F> MachineCursor<'a, T, F> |
11 | where |
12 | F: Fn(&[T], usize) -> bool, |
13 | { |
14 | pub fn new(data: &'a [T], pred: F) -> Self { |
15 | let pos = (0..data.len()) |
16 | .find(|i| pred(data, *i)) |
17 | .unwrap_or(data.len()); |
18 | Self { data, pred, pos } |
19 | } |
20 | |
21 | fn advance1(&mut self) { |
22 | self.pos = (self.pos + 1..self.data.len()) |
23 | .find(|q| (self.pred)(self.data, *q)) |
24 | .unwrap_or(self.data.len()); |
25 | } |
26 | |
27 | fn recede1(&mut self) { |
28 | self.pos = (0..self.pos) |
29 | .rev() |
30 | .find(|q| (self.pred)(self.data, *q)) |
31 | .unwrap_or(0); |
32 | } |
33 | |
34 | pub fn index(&self) -> usize { |
35 | self.pos |
36 | } |
37 | |
38 | pub fn end(&self) -> Self |
39 | where |
40 | F: Clone, |
41 | { |
42 | Self { |
43 | data: self.data, |
44 | pred: self.pred.clone(), |
45 | pos: self.data.len(), |
46 | } |
47 | } |
48 | } |
49 | |
50 | impl<'a, T, F> Add<usize> for MachineCursor<'a, T, F> |
51 | where |
52 | F: Fn(&[T], usize) -> bool, |
53 | { |
54 | type Output = Self; |
55 | |
56 | fn add(mut self, rhs: usize) -> Self::Output { |
57 | for _ in 0..rhs { |
58 | self.advance1(); |
59 | } |
60 | self |
61 | } |
62 | } |
63 | |
64 | impl<'a, T, F> Sub<usize> for MachineCursor<'a, T, F> |
65 | where |
66 | F: Fn(&[T], usize) -> bool, |
67 | { |
68 | type Output = Self; |
69 | |
70 | fn sub(mut self, rhs: usize) -> Self::Output { |
71 | for _ in 0..rhs { |
72 | self.recede1(); |
73 | } |
74 | self |
75 | } |
76 | } |
77 | |
78 | impl<'a, T, F> AddAssign<usize> for MachineCursor<'a, T, F> |
79 | where |
80 | F: Fn(&[T], usize) -> bool, |
81 | { |
82 | fn add_assign(&mut self, rhs: usize) { |
83 | for _ in 0..rhs { |
84 | self.advance1(); |
85 | } |
86 | } |
87 | } |
88 | |
89 | impl<'a, T, F> SubAssign<usize> for MachineCursor<'a, T, F> |
90 | where |
91 | F: Fn(&[T], usize) -> bool, |
92 | { |
93 | fn sub_assign(&mut self, rhs: usize) { |
94 | for _ in 0..rhs { |
95 | self.recede1(); |
96 | } |
97 | } |
98 | } |
99 | |
100 | impl<'a, T, F> PartialEq for MachineCursor<'a, T, F> { |
101 | fn eq(&self, other: &Self) -> bool { |
102 | self.pos == other.pos |
103 | } |
104 | } |
105 | |
106 | impl<'a, T, F> Clone for MachineCursor<'a, T, F> |
107 | where |
108 | F: Clone, |
109 | { |
110 | fn clone(&self) -> Self { |
111 | Self { |
112 | data: self.data, |
113 | pred: self.pred.clone(), |
114 | pos: self.pos, |
115 | } |
116 | } |
117 | } |
118 | |
119 | impl<'a, T, F> Copy for MachineCursor<'a, T, F> where F: Copy {} |
120 | |