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
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
pub use super::charcursor::*;
use crate::stepper::*;

// DocStepper

// Where we define the impl on.
#[derive(Clone, Debug)]
pub struct DocStepper<'a, S: Schema> {
    pub(crate) char_cursor: Option<CharCursor<S>>,
    pub(crate) stack: Vec<(isize, &'a [DocElement<S>])>,
}

// DocStepper impls

impl<'a, S: Schema> PartialEq for DocStepper<'a, S> {
    fn eq(&self, b: &DocStepper<'a, S>) -> bool {
        let a = self;
        (a.char_cursor.as_ref().map(|c| c.value()) == b.char_cursor.as_ref().map(|c| c.value())
            && a.stack == b.stack)
    }
}

impl<'a, S: Schema> DocStepper<'a, S> {
    pub fn new<'b>(span: &'b [DocElement<S>]) -> DocStepper<'b, S> {
        let mut stepper = DocStepper {
            char_cursor: None,
            stack: Vec::with_capacity(8),
        };
        stepper.stack.push((0, span));
        stepper.char_cursor_update();
        stepper
    }

    /// After an internal method changes what head will return, this method should be called.
    /// If head is a string, create a char_cursor on the first character of the string.
    /// If head is a group, clear the char_cursor.
    // TODO rename char_cursor_reset ?
    // TODO Make this pub(crate) once walkers.rs doesn't repend on it.
    pub fn char_cursor_update(&mut self) {
        self.char_cursor = if let Some(&DocText(ref styles, ref text)) = self.head_raw() {
            Some(CharCursor::from_docstring(text, styles.to_owned()))
        } else {
            None
        };
    }

    pub fn char_index(&self) -> Option<usize> {
        self.char_cursor
            .as_ref()
            .map(|cc| cc.left().map(|s| s.char_len()).unwrap_or(0))
    }

    /// Move to the last character - 1 of the current string, or clear the
    /// cursor if we've reached a group.
    pub(crate) fn char_cursor_update_prev(&mut self) {
        let cursor = match self.head() {
            Some(DocText(ref styles, ref text)) => {
                let mut cursor = CharCursor::from_docstring_end(text, styles.to_owned());
                cursor.value_sub(1);
                Some(cursor)
            }
            _ => None,
        };
        self.char_cursor = cursor;
    }

    pub fn char_cursor_expect(&self) -> &CharCursor<S> {
        self.char_cursor
            .as_ref()
            .expect("Expected a generated char cursor")
    }

    fn char_cursor_expect_add(&mut self, add: usize) {
        self.char_cursor
            .as_mut()
            .expect("Expected a generated char cursor")
            .value_add(add);
    }

    fn char_cursor_expect_sub(&mut self, sub: usize) {
        self.char_cursor
            .as_mut()
            .expect("Expected a generated char cursor")
            .value_sub(sub);
    }

    // TODO hack around lifetime woes? in walkers.rs:to_writer
    pub unsafe fn raw_index(&self) -> (Option<usize>, Vec<isize>) {
        (
            self.char_cursor.as_ref().map(|cc| cc.value()),
            self.stack.iter().map(|(x, ..)| *x).collect::<Vec<_>>(),
        )
    }

    // Current row in the stack is a DocSpan reference and an index.
    // What DocElement the index points to is the "head". If the head points
    // to a DocText, we also create a char_cursor to index into the string.

    pub(crate) fn current<'h>(&'h self) -> &'h (isize, &'a [DocElement<S>]) {
        self.stack.last().unwrap()
    }

    pub fn parent_attrs(&self) -> &S::GroupProperties {
        let (index, ref list) = &self.stack[self.stack.len() - 2];
        if let DocGroup(ref attrs, ..) = &list[*index as usize] {
            attrs
        } else {
            unreachable!();
        }
    }

    pub(crate) fn head_index(&self) -> usize {
        self.current().0 as usize
    }

    pub(crate) fn head_index_add(&mut self, add: usize) {
        self.stack.last_mut().unwrap().0 += add as isize;
        self.char_cursor_update();
    }

    pub(crate) fn head_index_sub(&mut self, sub: usize) {
        self.stack.last_mut().unwrap().0 -= sub as isize;
        self.char_cursor_update();
    }

    pub(crate) fn head_raw<'h>(&'h self) -> Option<&'a DocElement<S>> {
        self.current().1.get(self.head_index())
    }

    pub(crate) fn unhead_raw<'h>(&'h self) -> Option<&'a DocElement<S>> {
        // If we've split a string, don't modify the index.
        if self
            .char_cursor
            .as_ref()
            .map(|c| c.value() > 0)
            .unwrap_or(false)
        {
            return self.head_raw();
        }

        self.current().1.get(self.head_index() - 1)
    }

    // Cursor Public API

    pub fn next(&mut self) {
        self.head_index_add(1);
        // TODO @aggressive_opt this is called in head_index_add, right?
        // self.char_cursor_update();
    }

    pub fn prev(&mut self) {
        self.head_index_sub(1);
        self.char_cursor_update_prev();
    }

    pub fn head<'h>(&'h self) -> Option<&'h DocElement<S>> {
        match self.head_raw() {
            Some(&DocText(..)) => {
                // Expect cursor is at a string of length 1 at least
                // (meaning cursor has not passed to the end of the string)
                Some(
                    self.char_cursor_expect()
                        .right_element()
                        .expect("Encountered empty DocString"),
                )
            }
            Some(ref value) => Some(value),
            None => None,
        }
    }

    pub fn unhead<'h>(&'h self) -> Option<&'h DocElement<S>> {
        if let Some(&DocText(..)) = self.head_raw() {
            // .left may be empty, so allow fall-through (don't .unwrap())
            if let Some(docstring) = self.char_cursor_expect().left_element() {
                return Some(docstring);
            }
        }

        self.current().1.get((self.head_index() - 1) as usize)
    }

    pub fn peek(&self) -> Option<DocElement<S>> {
        match self.current().1.get((self.head_index() + 1) as usize) {
            Some(text @ &DocText(..)) => {
                // Pass along new text node
                Some(text.clone())
            }
            Some(value) => Some(value.clone()),
            None => None,
        }
    }

    pub fn unskip(&mut self, mut skip: usize) {
        while skip > 0 {
            match self.head_raw() {
                Some(DocText(..)) => {
                    if self.char_cursor_expect().value() > 0 {
                        self.char_cursor_expect_sub(1);
                        skip -= 1;
                    } else {
                        self.prev();
                        skip -= 1;
                    }
                }
                Some(DocGroup(..)) | None => {
                    self.prev();
                    skip -= 1;
                }
            }
        }
    }

    pub fn skip(&mut self, mut skip: usize) {
        if let Some(ref char_cursor) = &self.char_cursor {
            let remaining = char_cursor.index_from_end();
            if remaining == skip {
                self.next();
                return;
            } else if remaining > skip {
                self.char_cursor_expect_add(skip);
                return;
            } else {
                // remaining < skip, fall-through to loop
            }
        }

        while skip > 0 {
            let head = if let Some(head) = self.head_raw() {
                head
            } else {
                return;
            };

            match head {
                DocText(_, ref text) => {
                    let remaining = text.char_len();
                    if skip >= remaining {
                        skip -= remaining;
                    } else {
                        self.char_cursor_expect_add(skip);
                        return;
                    }
                }
                DocGroup(..) => {
                    skip -= 1;
                }
            }
            self.next();
        }
    }

    /// The number of elements to skip until the end of the current group
    /// the stepper is tracking were reached. After that, head() returns None
    /// and exit() should be called.
    pub fn skip_len(&self) -> usize {
        self.current().1[self.head_index()..].to_vec().skip_len()
    }

    // Cursor stack operations.

    pub fn at_root(&self) -> bool {
        self.stack.len() <= 1
    }

    pub fn is_back_done(&self) -> bool {
        self.at_root() && self.unhead_raw().is_none()
    }

    pub fn is_done(&self) -> bool {
        self.at_root() && self.head_raw().is_none()
    }

    pub fn unenter(&mut self) -> &mut Self {
        self.stack.pop();
        self.char_cursor_update();
        self
    }

    pub fn enter(&mut self) -> &mut Self {
        let index = self.stack.last().map(|x| x.0 as usize).unwrap();
        if let &DocGroup(_, ref inner) = self.stack.last().map(|x| &x.1[index]).unwrap() {
            self.stack.push((0, inner));
        } else {
            panic!("DocStepper::enter() called on inappropriate element");
        }
        self.char_cursor_update();
        self
    }

    pub fn unexit(&mut self) {
        self.prev();
        self.enter();
        self.head_index_add(self.current().1.len());
    }

    pub fn exit(&mut self) {
        self.unenter();
        self.next();
    }

    pub(crate) fn exit_with_attrs(&mut self) -> S::GroupProperties {
        self.unenter();
        let attrs = if let Some(&DocGroup(ref attrs, ..)) = self.head_raw() {
            attrs.clone()
        } else {
            unreachable!();
        };
        self.next();
        attrs
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::rtf::*;

    fn test_doc_0() -> Doc<RtfSchema> {
        doc![DocGroup(Attrs::Header(1), [DocText("Cool"),]),]
    }

    #[test]
    fn docstepper_middle() {
        let doc = test_doc_0();
        let mut stepper = DocStepper::new(&doc.0);
        stepper.enter();
        stepper.skip(2);
        assert_eq!(
            stepper.head().unwrap(),
            &DocText(StyleSet::new(), DocString::from_str("ol"))
        );
    }

    #[test]
    #[should_panic]
    fn docstepper_peek_too_far_0() {
        let doc = test_doc_0();
        let mut stepper = DocStepper::new(&doc.0);
        stepper.enter();
        stepper.skip(2);
        stepper.peek().unwrap();
    }

    #[test]
    #[should_panic]
    fn docstepper_peek_too_far_1() {
        let doc = test_doc_0();
        let mut stepper = DocStepper::new(&doc.0);
        stepper.enter();
        stepper.skip(4);
        stepper.peek().unwrap();
    }

    #[test]
    #[should_panic]
    fn docstepper_peek_too_far_2() {
        let doc = test_doc_0();
        let mut stepper = DocStepper::new(&doc.0);
        stepper.enter();
        stepper.peek().unwrap();
    }

    #[test]
    fn docstepper_deep_0() {
        let doc = test_doc_0();
        let mut stepper = DocStepper::new(&doc.0);
        stepper.enter();
        stepper.skip(3);
        stepper.unskip(3);
        stepper.unenter();
        stepper.enter();
        stepper.skip(3);
        assert_eq!(stepper.peek().is_none(), true);
    }
}