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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
use crate::error::{Error, ErrorKind, Result};
use std::io::{Read, Seek, SeekFrom};

const DEFAULT_CHUNK_SIZE: usize = 1024;

/// Seeker that can seek the occurences of a given byte slice within a stream of bytes.
///
/// # Examples
///
/// ```
/// use byteseeker::ByteSeeker;
/// use std::io::Cursor;
///
/// let bytes = [b'0', b'\n', b'0'];
/// let mut cursor = Cursor::new(bytes);
/// let mut seeker = ByteSeeker::new(&mut cursor);
///
/// assert_eq!(seeker.seek(b"0").unwrap(), 0);
/// assert_eq!(seeker.seek_nth(b"0", 1).unwrap(), 2);
///
/// // After resetting, we can seek from the other direction.
/// seeker.reset();
/// assert_eq!(seeker.seek_back(b"0").unwrap(), 2);
/// assert_eq!(seeker.seek_nth_back(b"0", 1).unwrap(), 0);
/// ```
///
/// The `ByteSeeker` uses a internal buffer to read a chunk of bytes into memory to search the
/// occurences of a given byte slice. You can specify the capacity of the interal buffer by
/// initializing a `ByteSeeker` using `ByteSeeker::with_capacity`, if you are seeking within a
/// pretty small or pretty large stream. The default capacity of the internal buffer is default to
/// `1024` currently.
///
/// It's worth noting that seeking a byte slice whose length is greater than the `capacity` of the
/// calling `ByteSeeker` is not allowed.
#[derive(Debug)]
pub struct ByteSeeker<'a, RS: 'a + Read + Seek> {
    inner: &'a mut RS,
    buf: Vec<u8>,
    len: usize,
    cap: usize,
    state: State,
}

#[derive(Clone, Copy, Debug)]
struct State {
    lpos: usize,
    rpos: usize,
    done: bool,
    last: bool,
}

#[derive(Clone, Copy, Debug)]
pub enum Dir {
    Start,
    End,
}

impl<'a, RS: 'a + Read + Seek> ByteSeeker<'a, RS> {
    /// Creates a new `ByteSeeker` that wraps a byte stream that implements `Read` and `Seek`.
    ///
    /// # Examples
    ///
    /// ```
    /// use byteseeker::ByteSeeker;
    /// use std::io::Cursor;
    ///
    /// let bytes = [1, 2, 3];
    /// let mut cursor = Cursor::new(bytes);
    /// let mut seeker = ByteSeeker::new(&mut cursor);
    /// ```
    pub fn new(stream: &'a mut RS) -> Self {
        ByteSeeker::with_capacity(stream, DEFAULT_CHUNK_SIZE)
    }

    /// Creates a new `ByteSeeker` that wraps a byte stream that implements `Read` and `Seek`, and
    /// sets the `capacity` of its internal buffer to the given capacity.
    ///
    /// # Examples
    ///
    /// ```
    /// use byteseeker::ByteSeeker;
    /// use std::io::Cursor;
    ///
    /// let bytes = [1, 2, 3];
    /// let mut cursor = Cursor::new(bytes);
    /// let mut seeker = ByteSeeker::with_capacity(&mut cursor, 3);
    /// ```
    pub fn with_capacity(stream: &'a mut RS, cap: usize) -> Self {
        // SAFETY: safe because `SeekFrom::End(0)` cannot return error.
        let len = stream.seek(SeekFrom::End(0)).unwrap() as usize;
        stream.seek(SeekFrom::Start(0)).unwrap();

        let rpos = if len == 0 { 0 } else { len - 1 };
        let state = State {
            lpos: 0,
            rpos: rpos,
            last: false,
            done: false,
        };

        Self {
            len,
            cap,
            state,
            inner: stream,
            buf: vecu8(DEFAULT_CHUNK_SIZE),
        }
    }

    /// Returns the length of the underlying byte stream.
    ///
    /// # Examples
    ///
    /// ```
    /// use byteseeker::ByteSeeker;
    /// use std::io::Cursor;
    ///
    /// let bytes = "lorem ipsum".as_bytes();
    /// let mut cursor = Cursor::new(bytes);
    /// let mut seeker = ByteSeeker::new(&mut cursor);
    ///
    /// assert_eq!(seeker.len(), 11);
    /// ```
    pub fn len(&self) -> usize {
        self.len
    }

    /// Returns the capacity of this `ByteSeeker`.
    ///
    /// # Examples
    ///
    /// ```
    /// use byteseeker::ByteSeeker;
    /// use std::io::Cursor;
    ///
    /// let bytes = "lorem ipsum".as_bytes();
    /// let mut cursor = Cursor::new(bytes);
    /// let mut seeker = ByteSeeker::with_capacity(&mut cursor, 11);
    ///
    /// assert_eq!(seeker.capacity(), 11);
    /// ```
    pub fn capacity(&self) -> usize {
        self.cap
    }

    /// Resets the state of the `ByteSeeker` to its original, so you can reuse this initialized
    /// `ByteSeeker` as it was newly created.
    ///
    /// # Examples
    ///
    /// ```
    /// use byteseeker::ByteSeeker;
    /// use std::io::Cursor;
    ///
    /// let bytes = [b'0', b'\n', b'0'];
    /// let mut cursor = Cursor::new(bytes);
    /// let mut seeker = ByteSeeker::new(&mut cursor);
    ///
    /// assert_eq!(seeker.seek(b"0").unwrap(), 0);
    /// assert_eq!(seeker.seek(b"0").unwrap(), 2);
    ///
    /// // The `reset` here is equivalent to:
    /// // let mut seeker = ByteSeeker::new(&mut cursor);
    /// seeker.reset();
    /// assert_eq!(seeker.seek_back(b"0").unwrap(), 2);
    /// assert_eq!(seeker.seek_back(b"0").unwrap(), 0);
    /// ```
    pub fn reset(&mut self) {
        self.inner.seek(SeekFrom::Start(0)).unwrap();

        let rpos = if self.len == 0 { 0 } else { self.len - 1 };
        self.state = State {
            lpos: 0,
            rpos: rpos,
            last: false,
            done: false,
        }
    }

    /// Searches for the given bytes **forwards**, and returns the offset (ralative to the start
    /// of the underlying byte stream) if the given bytes were found.
    ///
    /// If the initialized `ByteSeeker` haven't been called before, `seek` will start from
    /// the beginning; Otherwise, it will start from the last found `seek` position + 1.
    ///
    /// The `ByteSeeker` is stateful, which means you can call `seek` multiple times until
    /// reaching the end of the underlying byte stream.
    ///
    /// # Errors
    ///
    /// If the given bytes were not found, an error variant of `ErrorKind::ByteNotFound` will be
    /// returned. If any other I/O errors were encountered, an error variant of `ErrorKind::Io`
    /// will be returned.
    ///
    /// # Examples
    ///
    /// ```
    /// use byteseeker::ByteSeeker;
    /// use std::io::Cursor;
    ///
    /// let bytes = [b'0', b'\n', b'\n', b'\n'];
    /// let mut cursor = Cursor::new(bytes);
    /// let mut seeker = ByteSeeker::new(&mut cursor);
    ///
    /// assert_eq!(seeker.seek(b"0").unwrap(), 0);
    /// assert_eq!(seeker.seek(b"\n\n").unwrap(), 1);
    /// assert_eq!(seeker.seek(b"\n\n").is_err(), true);
    /// ```
    pub fn seek(&mut self, bytes: &[u8]) -> Result<usize> {
        self.buf_seek(bytes, Dir::Start)
    }

    /// Searches for the given bytes **backwards**, and returns the offset (ralative to the start
    /// of the underlying byte stream) if the given bytes were found.
    ///
    /// If the initialized `ByteSeeker` haven't been called before, `seek` will start from
    /// the end; Otherwise, it will start from the last found `seek` position - 1.
    ///
    /// The `ByteSeeker` is stateful, which means you can call `seek_back` multiple times until
    /// reaching the end of the underlying byte stream.
    ///
    /// # Errors
    ///
    /// If the given bytes were not found, an error variant of `ErrorKind::ByteNotFound` will be
    /// returned. If any other I/O errors were encountered, an error variant of `ErrorKind::Io`
    /// will be returned.
    ///
    /// # Examples
    ///
    /// ```
    /// use byteseeker::ByteSeeker;
    /// use std::io::Cursor;
    ///
    /// let bytes = [b'0', b'\n', b'\n', b'\n'];
    /// let mut cursor = Cursor::new(bytes);
    /// let mut seeker = ByteSeeker::new(&mut cursor);
    ///
    /// assert_eq!(seeker.seek_back(b"\n\n").unwrap(), 2);
    /// assert_eq!(seeker.seek_back(b"\n\n").is_err(), true);
    /// ```
    pub fn seek_back(&mut self, bytes: &[u8]) -> Result<usize> {
        self.buf_seek(bytes, Dir::End)
    }

    /// Seeks the nth occurence of the given bytes **forwards**, and returns the offset (ralative
    /// to the start of the underlying byte stream) if the given bytes were found.
    ///
    /// If the initialized `ByteSeeker` haven't been called before, `seek_nth`
    /// will start from the beginning; Otherwise, it will start from the last found `seek`
    /// position + 1.
    ///
    /// The `ByteSeeker` is stateful, which means you can call `seek_nth` multiple times until
    /// reaching the end of the underlying byte stream.
    ///
    /// # Errors
    ///
    /// If the given bytes were not found, an error variant of `ErrorKind::ByteNotFound` will be
    /// returned. If any other I/O errors were encountered, an error variant of `ErrorKind::Io`
    /// will be returned.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::io::Cursor;
    /// use byteseeker::ByteSeeker;
    ///
    /// let mut bytes = [b'\n', b'\n', b'\n', b'\n', b'\n'];
    /// let mut cursor = Cursor::new(bytes);
    /// let mut seeker = ByteSeeker::new(&mut cursor);
    /// assert_eq!(seeker.seek_nth(b"\n\n", 2).unwrap(), 2);
    /// assert_eq!(seeker.seek_nth(b"\n\n", 2).is_err(), true);
    /// ```
    pub fn seek_nth(&mut self, bytes: &[u8], nth: usize) -> Result<usize> {
        let mut counter = nth;
        loop {
            let pos = self.seek(bytes)?;
            match counter.checked_sub(1) {
                None => {
                    return Err(Error::new(ErrorKind::ByteNotFound));
                }
                Some(0) => {
                    return Ok(pos);
                }
                Some(n) => {
                    counter = n;
                }
            }
        }
    }

    /// Seeks the nth occurence of the given bytes **backwards**, and returns the offset (ralative
    /// to the start of the underlying byte stream) if the given bytes were found.
    ///
    /// If the initialized `ByteSeeker` haven't been called before, `seek_nth_back`
    /// will start from the end; Otherwise, it will start from the last found `seek` position - 1.
    ///
    /// The `ByteSeeker` is stateful, which means you can call `seek_nth_back` multiple times until
    /// reaching the end of the underlying byte stream.
    ///
    /// # Errors
    ///
    /// If the given bytes were not found, an error variant of `ErrorKind::ByteNotFound` will be
    /// returned. If any other I/O errors were encountered, an error variant of `ErrorKind::Io`
    /// will be returned.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::io::Cursor;
    /// use byteseeker::ByteSeeker;
    ///
    /// let mut bytes = [b'\n', b'\n', b'\n', b'\n', b'\n'];
    /// let mut cursor = Cursor::new(bytes);
    /// let mut seeker = ByteSeeker::new(&mut cursor);
    /// assert_eq!(seeker.seek_nth_back(b"\n\n", 2).unwrap(), 1);
    /// assert_eq!(seeker.seek_nth_back(b"\n\n", 2).is_err(), true);
    /// ```
    pub fn seek_nth_back(&mut self, bytes: &[u8], nth: usize) -> Result<usize> {
        let mut counter = nth;
        loop {
            let pos = self.seek_back(bytes)?;
            match counter.checked_sub(1) {
                None => {
                    return Err(Error::new(ErrorKind::ByteNotFound));
                }
                Some(0) => {
                    return Ok(pos);
                }
                Some(n) => {
                    counter = n;
                }
            }
        }
    }

    /// Gets a mutable reference to the underlying reader.
    ///
    /// It is inadvisable to directly read from the underlying reader.
    ///
    /// # Examples
    ///
    /// ```
    /// use byteseeker::ByteSeeker;
    /// use std::io::{Cursor, Read};
    ///
    /// let bytes = [b'0', b'\n', b'\n', b'\n'];
    /// let mut cursor = Cursor::new(bytes);
    /// let mut seeker = ByteSeeker::new(&mut cursor);
    /// assert_eq!(seeker.seek(b"\n").unwrap(), 1);
    ///
    /// let mut reader = seeker.get_mut();
    /// let mut buf = Vec::new();
    /// let _ = reader.read_to_end(&mut buf);
    /// assert_eq!(&buf, &[b'\n', b'\n']);
    /// ```
    pub fn get_mut(&mut self) -> &mut RS {
        self.inner
    }
}

impl<'a, RS: 'a + Read + Seek> ByteSeeker<'a, RS> {
    fn buf_seek(&mut self, bytes: &[u8], dir: Dir) -> Result<usize> {
        if self.state.done {
            return Err(Error::new(ErrorKind::ByteNotFound));
        }

        let bytes_len = bytes.len();
        if bytes_len == 0 || bytes_len > self.cap {
            return Err(Error::new(ErrorKind::UnsupportedLength));
        }

        use std::cmp::Ordering::*;
        match self.len.cmp(&bytes_len) {
            Less => {
                self.state.done = true;
                return Err(Error::new(ErrorKind::ByteNotFound));
            }
            Equal => {
                self.state.done = true;
                let mut buf = vecu8(bytes_len);
                self.inner.read_exact(&mut buf)?;
                if bytes == &buf {
                    return Ok(0);
                } else {
                    return Err(Error::new(ErrorKind::ByteNotFound));
                }
            }
            Greater => match dir {
                Dir::Start => loop {
                    if self.state.done {
                        return Err(Error::new(ErrorKind::ByteNotFound));
                    }

                    let remaining = self.len - self.state.lpos;
                    let mut buf_len = self.buf.len();

                    if remaining < bytes_len {
                        return Err(Error::new(ErrorKind::ByteNotFound));
                    } else if remaining < buf_len {
                        self.buf.truncate(remaining);
                        buf_len = remaining;
                        self.state.last = true;
                    }
                    self.inner.read_exact(&mut self.buf)?;

                    if let Some(pos) = self.buf.iter().position(|&x| x == bytes[0]) {
                        let cpos = self.state.lpos + pos;
                        if self.match_in_place(cpos, bytes)? {
                            if cpos + bytes_len > self.len {
                                self.state.done = true;
                            } else {
                                self.state.lpos = self
                                    .inner
                                    .seek(SeekFrom::Start((cpos + bytes_len) as u64))?
                                    as usize;
                            }
                            return Ok(cpos);
                        } else if buf_len == remaining {
                            return Err(Error::new(ErrorKind::ByteNotFound));
                        }
                    } else {
                        if self.state.last {
                            self.state.done = true;
                            return Err(Error::new(ErrorKind::ByteNotFound));
                        } else {
                            self.state.lpos = self
                                .inner
                                .seek(SeekFrom::Start((self.state.lpos + buf_len) as u64))?
                                as usize;
                        }
                    }
                },
                Dir::End => loop {
                    if self.state.done {
                        return Err(Error::new(ErrorKind::ByteNotFound));
                    }

                    let remaining = self.state.rpos + 1;
                    let mut buf_len = self.buf.len();

                    if remaining < bytes_len {
                        return Err(Error::new(ErrorKind::ByteNotFound));
                    } else if remaining < buf_len {
                        self.buf.truncate(remaining);
                        buf_len = remaining;
                        self.state.last = true;
                    }

                    self.inner
                        .seek(SeekFrom::Start((remaining - buf_len) as u64))?
                        as usize;
                    self.inner.read_exact(&mut self.buf)?;

                    if let Some(pos) = self
                        .buf
                        .iter()
                        .rev()
                        .position(|&x| x == bytes[bytes_len - 1])
                    {
                        let cpos = self.state.rpos - pos - (bytes_len - 1);
                        if self.match_in_place(cpos, bytes)? {
                            if (cpos as isize) - 1 < 0 {
                                self.state.done = true;
                            } else {
                                self.state.rpos =
                                    self.inner.seek(SeekFrom::Start((cpos - 1) as u64))? as usize;
                            }
                            return Ok(cpos);
                        } else if buf_len == remaining {
                            return Err(Error::new(ErrorKind::ByteNotFound));
                        }
                    } else {
                        if self.state.last {
                            self.state.done = true;
                            return Err(Error::new(ErrorKind::ByteNotFound));
                        } else {
                            self.state.rpos = remaining - buf_len;
                        }
                    }
                },
            },
        }
    }

    fn match_in_place(&mut self, pos: usize, bytes: &[u8]) -> Result<bool> {
        self.inner.seek(SeekFrom::Start(pos as u64))?;
        let len = bytes.len();
        if pos + len > self.len {
            return Ok(false);
        }
        let mut buf = vecu8(len);
        self.inner.read_exact(&mut buf)?;
        self.inner.seek(SeekFrom::Start(pos as u64))?;
        if &buf == bytes {
            return Ok(true);
        } else {
            return Ok(false);
        }
    }
}

// Creates a `Vec<u8>` whose capacity and length are exactly the same.
fn vecu8(len: usize) -> Vec<u8> {
    let mut vec = Vec::with_capacity(len);
    unsafe {
        vec.set_len(len);
    }
    vec
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Cursor;

    #[test]
    fn test_vecu8() {
        let vec = vecu8(0);
        assert_eq!(vec.len(), 0);
        assert_eq!(vec.capacity(), 0);

        let vec = vecu8(42);
        assert_eq!(vec.len(), 42);
        assert_eq!(vec.capacity(), 42);
    }

    #[test]
    fn test_match_in_place() {
        let bytes: Vec<u8> = vec![0, 1, 2];
        let mut cursor = Cursor::new(bytes);
        let mut seeker = ByteSeeker::new(&mut cursor);
        assert_eq!(seeker.match_in_place(0, &[0]).unwrap(), true);
        assert_eq!(seeker.match_in_place(0, &[0, 1]).unwrap(), true);
        assert_eq!(seeker.match_in_place(0, &[0, 1, 2]).unwrap(), true);
        assert_eq!(seeker.match_in_place(0, &[0, 1, 2, 3]).unwrap(), false);
        assert_eq!(seeker.match_in_place(1, &[1]).unwrap(), true);
        assert_eq!(seeker.match_in_place(1, &[1, 2]).unwrap(), true);
        assert_eq!(seeker.match_in_place(1, &[1, 2, 3]).unwrap(), false);
    }
}