weave 0.3.1

Weave delta file storage. Inspired by the storage format of SCCS, this crate allows multiple revisions of a file to be stored efficiently in a single file.
Documentation
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
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
//! Weave parsing

use crate::{header::Header, Error, NamingConvention, Result};
use flate2::read::GzDecoder;
use log::info;
use std::{
    cell::RefCell,
    fs::File,
    io::{BufRead, BufReader, Lines, Read},
    mem,
    rc::Rc,
};

/// A Sink is a place that a parsed weave can be sent to.  The insert/delete/end commands match
/// those in the weave file, and `plain` are the lines of data.  With each plain is a flag
/// indicating if that line should be included in the output (all lines are called, so that updates
/// can use this same code).  All methods return a result, with the Err value stopping the parse.
/// Note that the default implementations just return success, and ignore the result.
pub trait Sink {
    /// Begin an insert sequence for the given delta.
    fn insert(&mut self, _delta: usize) -> Result<()> {
        Ok(())
    }

    /// Begin a delete sequence.
    fn delete(&mut self, _delta: usize) -> Result<()> {
        Ok(())
    }

    /// End a previous insert or delete.
    fn end(&mut self, _delta: usize) -> Result<()> {
        Ok(())
    }

    /// A single line of plain text from the weave.  `keep` indicates if the line should be
    /// included in the requested delta.
    fn plain(&mut self, _text: &str, _keep: bool) -> Result<()> {
        Ok(())
    }
}

/// The PullParser returns the entries as nodes.  These are equivalent to
/// the values in Sink.
#[derive(Debug)]
pub enum Entry {
    /// Begin an insert sequence for the given delta.
    Insert { delta: usize },

    /// Begin a delete sequence.
    Delete { delta: usize },

    /// End a previous insert or delete.
    End { delta: usize },

    /// A single line of plaintext from the weave.  `keep` indicates if the
    /// line should be included in the requested delta.
    Plain { text: String, keep: bool },

    /// A control message.  Doesn't currently contain any data, which can be added later if needed.
    Control,
}

/// A Parser is used to process a weave file.  This is a wrapper around the pull parser that
/// invokes a push parser.
pub struct Parser<S: Sink, B> {
    /// The pull parser.
    pull: PullParser<B>,

    /// The sink to be given each line record in the weave file.
    sink: Rc<RefCell<S>>,

    /// A single pending line, kept from the last invocation.
    pending: Option<String>,

    /// Tracking the line number.
    lineno: usize,
}

impl<S: Sink> Parser<S, BufReader<Box<dyn Read>>> {
    /// Construct a parser, based on the main file of the naming convention.
    pub fn new(
        naming: &dyn NamingConvention,
        sink: S,
        delta: usize,
    ) -> Result<Parser<S, BufReader<Box<dyn Read>>>> {
        let rd = if naming.is_compressed() {
            let fd = File::open(naming.main_file())?;
            Box::new(GzDecoder::new(fd)) as Box<dyn Read>
        } else {
            Box::new(File::open(naming.main_file())?) as Box<dyn Read>
        };
        let lines = BufReader::new(rd).lines();
        Parser::new_raw(lines, Rc::new(RefCell::new(sink)), delta)
    }
}

impl<S: Sink, B: BufRead> Parser<S, B> {
    /// Construct a new Parser, reading from the given Reader, giving records to the given Sink,
    /// and aiming for the specified `delta`.  This is not the intended constructor, normal users
    /// should use `new`.  (This is public, for testing).
    pub fn new_raw(
        source: Lines<B>,
        sink: Rc<RefCell<S>>,
        delta: usize,
    ) -> Result<Parser<S, B>> {
        let pull = PullParser::new_raw(source, delta)?;
        Ok(Parser {
            pull,
            sink,
            pending: None,
            lineno: 0,
        })
    }

    /// Run the parser until we either reach the given line number, or the end of the weave.  Lines
    /// are numbered from 1, so calling with a lineno of zero will run the parser until the end of
    /// the input.  Returns Ok(0) for the end of input, Ok(n) for stopping at line n (which should
    /// always be the same as the passed in lineno, or Err if there is an error.
    pub fn parse_to(&mut self, lineno: usize) -> Result<usize> {
        // Handle any pending input line.  Pending lines only happen while keeping.
        if let Some(text) = mem::replace(&mut self.pending, None) {
            self.sink.borrow_mut().plain(&text, true)?;
        }

        loop {
            match self.pull.next() {
                Some(Ok(Entry::Plain { text, keep })) => {
                    if keep {
                        self.lineno += 1;
                        if self.lineno == lineno {
                            // This is the desired stopping point, hold onto this line, and return
                            // to the caller.
                            self.pending = Some(text);
                            return Ok(lineno);
                        }
                    }

                    self.sink.borrow_mut().plain(&text, keep)?;
                }
                Some(Ok(Entry::Insert { delta })) => {
                    self.sink.borrow_mut().insert(delta)?;
                }
                Some(Ok(Entry::Delete { delta })) => {
                    self.sink.borrow_mut().delete(delta)?;
                }
                Some(Ok(Entry::End { delta })) => {
                    self.sink.borrow_mut().end(delta)?;
                }
                Some(Ok(Entry::Control)) => (),
                Some(Err(err)) => {
                    return Err(err);
                }
                None => {
                    return Ok(0);
                }
            }
        }
    }


    /// Get the header read from this weave file.
    pub fn get_header(&self) -> &Header {
        &self.pull.header
    }

    /// Consume the parser, returning the header.
    pub fn into_header(self) -> Header {
        self.pull.into_header()
    }

    /// Get a copy of the sink.
    pub fn get_sink(&self) -> Rc<RefCell<S>> {
        self.sink.clone()
    }
}

/*
/// A PullIterator returns entities in a weave file, extracting either
/// everything, or only a specific delta.
pub struct PullIterator<B> {
    /// The lines of the input.
    source: Lines<B>,

    /// The desired delta to retrieve.
    delta: usize,

    /// The delta state is kept sorted with the newest (largest) delta at
    /// element 0.
    delta_state: Vec<OneDelta>,

    /// Indicates we are currently keeping lines.
    keeping: bool,

    /// The current line number.
    lineno: usize,

    /// The header extracted from the file.
    header: Header,
}
*/

/// The pull parser is the intended way of reading from weave files.  After opening a particular
/// delta with [`PullParser::new`], the parser can be used as an iterator, to return [`Entry`] values.  In
/// particular, the entries for [`Entry::Plain`] where `keep` is true will be the lines of the
/// weave that comprise the expected delta.
pub struct PullParser<B> {
    /// The lines of the input.
    source: Lines<B>,

    /// The desired delta to retrieve.
    delta: usize,

    /// The delta state is kept sorted with the newest (largest) delta at element 0.
    delta_state: Vec<OneDelta>,

    /// Indicates that we are currently "keeping" lines.
    keeping: bool,

    /// The header extracted from the file.
    header: Header,
}

impl PullParser<BufReader<Box<dyn Read>>> {
    /// Construct a parser, based on the main file of the naming
    /// convention.
    pub fn new(
        naming: &dyn NamingConvention,
        delta: usize,
    ) -> Result<PullParser<BufReader<Box<dyn Read>>>> {
        let rd = if naming.is_compressed() {
            let fd = File::open(naming.main_file())?;
            Box::new(GzDecoder::new(fd)) as Box<dyn Read>
        } else {
            Box::new(File::open(naming.main_file())?) as Box<dyn Read>
        };
        let lines = BufReader::new(rd).lines();
        PullParser::new_raw(lines, delta)
    }
}

impl<B: BufRead> PullParser<B> {
    /// Construct a new Parser, reading from the given Reader.  The parser
    /// will act as an iterator.  This is the intended constructor, normal
    /// users should use `new`.  (This is public for testing).
    pub fn new_raw(mut source: Lines<B>, delta: usize) -> Result<PullParser<B>> {
        if let Some(line) = source.next() {
            let line = line?;
            let header = Header::decode(&line)?;

            Ok(PullParser {
                source,
                delta,
                delta_state: vec![],
                keeping: false,
                header,
            })
        } else {
            Err(Error::EmptyWeave)
        }
    }

    /// Remove the given numbered state.
    fn pop(&mut self, delta: usize) {
        // The binary search is reversed, so the largest are first.
        let pos = match self
            .delta_state
            .binary_search_by(|ent| delta.cmp(&ent.delta))
        {
            Ok(pos) => pos,
            Err(_) => unreachable!(),
        };

        self.delta_state.remove(pos);
    }

    /// Add a new state.  It will be inserted in the proper place in the array, based on the delta
    /// number.
    fn push(&mut self, delta: usize, mode: StateMode) {
        match self
            .delta_state
            .binary_search_by(|ent| delta.cmp(&ent.delta))
        {
            Ok(_) => panic!("Duplicate state in push"),
            Err(pos) => self.delta_state.insert(pos, OneDelta { delta, mode }),
        }
    }

    /// Update the keep field, based on the current state.
    fn update_keep(&mut self) {
        info!("Update: {:?}", self.delta_state);
        for st in &self.delta_state {
            match st.mode {
                StateMode::Keep => {
                    self.keeping = true;
                    return;
                }
                StateMode::Skip => {
                    self.keeping = false;
                    return;
                }
                _ => (),
            }
        }

        // This shouldn't be reached if there are any more context lines, but we may get here when
        // we reach the end of the input.
        self.keeping = false;
    }

    /// Get the header read from this weave file.
    pub fn get_header(&self) -> &Header {
        &self.header
    }

    /// Consume the parser, returning the header.
    pub fn into_header(self) -> Header {
        self.header
    }
}

impl<B: BufRead> Iterator for PullParser<B> {
    type Item = Result<Entry>;

    fn next(&mut self) -> Option<Result<Entry>> {
        // At this level, there is a 1:1 correspondence between weave input
        // lines and those returned.
        let line = match self.source.next() {
            None => return None,
            Some(Ok(line)) => line,
            Some(Err(e)) => return Some(Err(From::from(e))),
        };

        info!("line: {:?}", line);

        // Detect the first character, without borrowing.
        let textual = match line.bytes().next() {
            None => true,
            Some(ch) if ch != b'\x01' => true,
            _ => false,
        };

        if textual {
            return Some(Ok(Entry::Plain {
                text: line,
                keep: self.keeping,
            }));
        }

        let linebytes = line.as_bytes();

        if linebytes.len() < 4 {
            return Some(Ok(Entry::Control));
        }

        if linebytes[1] != b'I' && linebytes[1] != b'D' && linebytes[1] != b'E' {
            return Some(Ok(Entry::Control));
        };

        // TODO: Don't panic, but fail.
        let this_delta: usize = line[3..].parse().unwrap();

        match linebytes[1] {
            b'E' => {
                self.pop(this_delta);
                self.update_keep();
                Some(Ok(Entry::End { delta: this_delta }))
            }
            b'I' => {
                if self.delta >= this_delta {
                    self.push(this_delta, StateMode::Keep);
                } else {
                    self.push(this_delta, StateMode::Skip);
                }
                self.update_keep();

                Some(Ok(Entry::Insert { delta: this_delta }))
            }
            b'D' => {
                if self.delta >= this_delta {
                    self.push(this_delta, StateMode::Skip);
                } else {
                    self.push(this_delta, StateMode::Next);
                }
                self.update_keep();

                Some(Ok(Entry::Delete { delta: this_delta }))
            }
            _ => unreachable!(),
        }
    }
}

#[derive(Copy, Clone, Eq, PartialEq, Debug)]
enum StateMode {
    Keep,
    Skip,
    Next,
}

#[derive(Debug)]
struct OneDelta {
    delta: usize,
    mode: StateMode,
}