Skip to content
Myr

line_buffer.rs

This file

Path

crates/searcher/src/line_buffer.rs

965 lines · 34.4 KiB · Rust

Last changed by

searcher: fix regression with `--line-buffered` flagAndrew Gallantbefore adoptiond47663b

History of this file

Take it

1use std::io;23use bstr::ByteSlice;45/// The default buffer capacity that we use for the line buffer.6pub(crate) const DEFAULT_BUFFER_CAPACITY: usize = 64 * (1 << 10); // 64 KB78/// The behavior of a searcher in the face of long lines and big contexts.9///10/// When searching data incrementally using a fixed size buffer, this controls11/// the amount of *additional* memory to allocate beyond the size of the buffer12/// to accommodate lines (which may include the lines in a context window, when13/// enabled) that do not fit in the buffer.14///15/// The default is to eagerly allocate without a limit.16#[derive(Clone, Copy, Debug)]17pub(crate) enum BufferAllocation {18    /// Attempt to expand the size of the buffer until either at least the next19    /// line fits into memory or until all available memory is exhausted.20    ///21    /// This is the default.22    Eager,23    /// Limit the amount of additional memory allocated to the given size. If24    /// a line is found that requires more memory than is allowed here, then25    /// stop reading and return an error.26    Error(usize),27}2829impl Default for BufferAllocation {30    fn default() -> BufferAllocation {31        BufferAllocation::Eager32    }33}3435/// Create a new error to be used when a configured allocation limit has been36/// reached.37pub(crate) fn alloc_error(limit: usize) -> io::Error {38    let msg = format!("configured allocation limit ({}) exceeded", limit);39    io::Error::new(io::ErrorKind::Other, msg)40}4142/// The behavior of binary detection in the line buffer.43///44/// Binary detection is the process of _heuristically_ identifying whether a45/// given chunk of data is binary or not, and then taking an action based on46/// the result of that heuristic. The motivation behind detecting binary data47/// is that binary data often indicates data that is undesirable to search48/// using textual patterns. Of course, there are many cases in which this isn't49/// true, which is why binary detection is disabled by default.50#[derive(Clone, Copy, Debug, Eq, PartialEq)]51pub(crate) enum BinaryDetection {52    /// No binary detection is performed. Data reported by the line buffer may53    /// contain arbitrary bytes.54    None,55    /// The given byte is searched in all contents read by the line buffer. If56    /// it occurs, then the data is considered binary and the line buffer acts57    /// as if it reached EOF. The line buffer guarantees that this byte will58    /// never be observable by callers.59    Quit(u8),60    /// The given byte is searched in all contents read by the line buffer. If61    /// it occurs, then it is replaced by the line terminator. The line buffer62    /// guarantees that this byte will never be observable by callers.63    Convert(u8),64}6566impl Default for BinaryDetection {67    fn default() -> BinaryDetection {68        BinaryDetection::None69    }70}7172impl BinaryDetection {73    /// Returns true if and only if the detection heuristic demands that74    /// the line buffer stop read data once binary data is observed.75    fn is_quit(&self) -> bool {76        match *self {77            BinaryDetection::Quit(_) => true,78            _ => false,79        }80    }81}8283/// The configuration of a buffer. This contains options that are fixed once84/// a buffer has been constructed.85#[derive(Clone, Copy, Debug)]86struct Config {87    /// The number of bytes to attempt to read at a time.88    capacity: usize,89    /// The line terminator.90    lineterm: u8,91    /// The behavior for handling long lines.92    buffer_alloc: BufferAllocation,93    /// When set, the presence of the given byte indicates binary content.94    binary: BinaryDetection,95}9697impl Default for Config {98    fn default() -> Config {99        Config {100            capacity: DEFAULT_BUFFER_CAPACITY,101            lineterm: b'\n',102            buffer_alloc: BufferAllocation::default(),103            binary: BinaryDetection::default(),104        }105    }106}107108/// A builder for constructing line buffers.109#[derive(Clone, Debug, Default)]110pub(crate) struct LineBufferBuilder {111    config: Config,112}113114impl LineBufferBuilder {115    /// Create a new builder for a buffer.116    pub(crate) fn new() -> LineBufferBuilder {117        LineBufferBuilder { config: Config::default() }118    }119120    /// Create a new line buffer from this builder's configuration.121    pub(crate) fn build(&self) -> LineBuffer {122        LineBuffer {123            config: self.config,124            buf: vec![0; self.config.capacity],125            pos: 0,126            last_lineterm: 0,127            end: 0,128            absolute_byte_offset: 0,129            binary_byte_offset: None,130        }131    }132133    /// Set the default capacity to use for a buffer.134    ///135    /// In general, the capacity of a buffer corresponds to the amount of data136    /// to hold in memory, and the size of the reads to make to the underlying137    /// reader.138    ///139    /// This is set to a reasonable default and probably shouldn't be changed140    /// unless there's a specific reason to do so.141    pub(crate) fn capacity(142        &mut self,143        capacity: usize,144    ) -> &mut LineBufferBuilder {145        self.config.capacity = capacity;146        self147    }148149    /// Set the line terminator for the buffer.150    ///151    /// Every buffer has a line terminator, and this line terminator is used152    /// to determine how to roll the buffer forward. For example, when a read153    /// to the buffer's underlying reader occurs, the end of the data that is154    /// read is likely to correspond to an incomplete line. As a line buffer,155    /// callers should not access this data since it is incomplete. The line156    /// terminator is how the line buffer determines the part of the read that157    /// is incomplete.158    ///159    /// By default, this is set to `b'\n'`.160    pub(crate) fn line_terminator(161        &mut self,162        lineterm: u8,163    ) -> &mut LineBufferBuilder {164        self.config.lineterm = lineterm;165        self166    }167168    /// Set the maximum amount of additional memory to allocate for long lines.169    ///170    /// In order to enable line oriented search, a fundamental requirement is171    /// that, at a minimum, each line must be able to fit into memory. This172    /// setting controls how big that line is allowed to be. By default, this173    /// is set to `BufferAllocation::Eager`, which means a line buffer will174    /// attempt to allocate as much memory as possible to fit a line, and will175    /// only be limited by available memory.176    ///177    /// Note that this setting only applies to the amount of *additional*178    /// memory to allocate, beyond the capacity of the buffer. That means that179    /// a value of `0` is sensible, and in particular, will guarantee that a180    /// line buffer will never allocate additional memory beyond its initial181    /// capacity.182    pub(crate) fn buffer_alloc(183        &mut self,184        behavior: BufferAllocation,185    ) -> &mut LineBufferBuilder {186        self.config.buffer_alloc = behavior;187        self188    }189190    /// Whether to enable binary detection or not. Depending on the setting,191    /// this can either cause the line buffer to report EOF early or it can192    /// cause the line buffer to clean the data.193    ///194    /// By default, this is disabled. In general, binary detection should be195    /// viewed as an imperfect heuristic.196    pub(crate) fn binary_detection(197        &mut self,198        detection: BinaryDetection,199    ) -> &mut LineBufferBuilder {200        self.config.binary = detection;201        self202    }203}204205/// A line buffer reader efficiently reads a line oriented buffer from an206/// arbitrary reader.207#[derive(Debug)]208pub(crate) struct LineBufferReader<'b, R> {209    rdr: R,210    line_buffer: &'b mut LineBuffer,211}212213impl<'b, R: io::Read> LineBufferReader<'b, R> {214    /// Create a new buffered reader that reads from `rdr` and uses the given215    /// `line_buffer` as an intermediate buffer.216    ///217    /// This does not change the binary detection behavior of the given line218    /// buffer.219    pub(crate) fn new(220        rdr: R,221        line_buffer: &'b mut LineBuffer,222    ) -> LineBufferReader<'b, R> {223        line_buffer.clear();224        LineBufferReader { rdr, line_buffer }225    }226227    /// The absolute byte offset which corresponds to the starting offsets228    /// of the data returned by `buffer` relative to the beginning of the229    /// underlying reader's contents. As such, this offset does not generally230    /// correspond to an offset in memory. It is typically used for reporting231    /// purposes. It can also be used for counting the number of bytes that232    /// have been searched.233    pub(crate) fn absolute_byte_offset(&self) -> u64 {234        self.line_buffer.absolute_byte_offset()235    }236237    /// If binary data was detected, then this returns the absolute byte offset238    /// at which binary data was initially found.239    pub(crate) fn binary_byte_offset(&self) -> Option<u64> {240        self.line_buffer.binary_byte_offset()241    }242243    /// Fill the contents of this buffer by discarding the part of the buffer244    /// that has been consumed. The free space created by discarding the245    /// consumed part of the buffer is then filled with new data from the246    /// reader.247    ///248    /// If EOF is reached, then `false` is returned. Otherwise, `true` is249    /// returned. (Note that if this line buffer's binary detection is set to250    /// `Quit`, then the presence of binary data will cause this buffer to251    /// behave as if it had seen EOF at the first occurrence of binary data.)252    ///253    /// This forwards any errors returned by the underlying reader, and will254    /// also return an error if the buffer must be expanded past its allocation255    /// limit, as governed by the buffer allocation strategy.256    pub(crate) fn fill(&mut self) -> Result<bool, io::Error> {257        self.line_buffer.fill(&mut self.rdr)258    }259260    /// Return the contents of this buffer.261    pub(crate) fn buffer(&self) -> &[u8] {262        self.line_buffer.buffer()263    }264265    /// Return the buffer as a BStr, used for convenient equality checking266    /// in tests only.267    #[cfg(test)]268    fn bstr(&self) -> &bstr::BStr {269        self.buffer().as_bstr()270    }271272    /// Consume the number of bytes provided. This must be less than or equal273    /// to the number of bytes returned by `buffer`.274    pub(crate) fn consume(&mut self, amt: usize) {275        self.line_buffer.consume(amt);276    }277278    /// Consumes the remainder of the buffer. Subsequent calls to `buffer` are279    /// guaranteed to return an empty slice until the buffer is refilled.280    ///281    /// This is a convenience function for `consume(buffer.len())`.282    #[cfg(test)]283    fn consume_all(&mut self) {284        self.line_buffer.consume_all();285    }286}287288/// A line buffer manages a (typically fixed) buffer for holding lines.289///290/// Callers should create line buffers sparingly and reuse them when possible.291/// Line buffers cannot be used directly, but instead must be used via the292/// LineBufferReader.293#[derive(Clone, Debug)]294pub(crate) struct LineBuffer {295    /// The configuration of this buffer.296    config: Config,297    /// The primary buffer with which to hold data.298    buf: Vec<u8>,299    /// The current position of this buffer. This is always a valid sliceable300    /// index into `buf`, and its maximum value is the length of `buf`.301    pos: usize,302    /// The end position of searchable content in this buffer. This is either303    /// set to just after the final line terminator in the buffer, or to just304    /// after the end of the last byte emitted by the reader when the reader305    /// has been exhausted.306    last_lineterm: usize,307    /// The end position of the buffer. This is always greater than or equal to308    /// last_lineterm. The bytes between last_lineterm and end, if any, always309    /// correspond to a partial line.310    end: usize,311    /// The absolute byte offset corresponding to `pos`. This is most typically312    /// not a valid index into addressable memory, but rather, an offset that313    /// is relative to all data that passes through a line buffer (since314    /// construction or since the last time `clear` was called).315    ///316    /// When the line buffer reaches EOF, this is set to the position just317    /// after the last byte read from the underlying reader. That is, it318    /// becomes the total count of bytes that have been read.319    absolute_byte_offset: u64,320    /// If binary data was found, this records the absolute byte offset at321    /// which it was first detected.322    binary_byte_offset: Option<u64>,323}324325impl LineBuffer {326    /// Set the binary detection method used on this line buffer.327    ///328    /// This permits dynamically changing the binary detection strategy on329    /// an existing line buffer without needing to create a new one.330    pub(crate) fn set_binary_detection(&mut self, binary: BinaryDetection) {331        self.config.binary = binary;332    }333334    /// Reset this buffer, such that it can be used with a new reader.335    fn clear(&mut self) {336        self.pos = 0;337        self.last_lineterm = 0;338        self.end = 0;339        self.absolute_byte_offset = 0;340        self.binary_byte_offset = None;341    }342343    /// The absolute byte offset which corresponds to the starting offsets344    /// of the data returned by `buffer` relative to the beginning of the345    /// reader's contents. As such, this offset does not generally correspond346    /// to an offset in memory. It is typically used for reporting purposes,347    /// particularly in error messages.348    ///349    /// This is reset to `0` when `clear` is called.350    fn absolute_byte_offset(&self) -> u64 {351        self.absolute_byte_offset352    }353354    /// If binary data was detected, then this returns the absolute byte offset355    /// at which binary data was initially found.356    fn binary_byte_offset(&self) -> Option<u64> {357        self.binary_byte_offset358    }359360    /// Return the contents of this buffer.361    fn buffer(&self) -> &[u8] {362        &self.buf[self.pos..self.last_lineterm]363    }364365    /// Return the contents of the free space beyond the end of the buffer as366    /// a mutable slice.367    fn free_buffer(&mut self) -> &mut [u8] {368        &mut self.buf[self.end..]369    }370371    /// Consume the number of bytes provided. This must be less than or equal372    /// to the number of bytes returned by `buffer`.373    fn consume(&mut self, amt: usize) {374        assert!(amt <= self.buffer().len());375        self.pos += amt;376        self.absolute_byte_offset += amt as u64;377    }378379    /// Consumes the remainder of the buffer. Subsequent calls to `buffer` are380    /// guaranteed to return an empty slice until the buffer is refilled.381    ///382    /// This is a convenience function for `consume(buffer.len())`.383    #[cfg(test)]384    fn consume_all(&mut self) {385        let amt = self.buffer().len();386        self.consume(amt);387    }388389    /// Fill the contents of this buffer by discarding the part of the buffer390    /// that has been consumed. The free space created by discarding the391    /// consumed part of the buffer is then filled with new data from the given392    /// reader.393    ///394    /// Callers should provide the same reader to this line buffer in395    /// subsequent calls to fill. A different reader can only be used396    /// immediately following a call to `clear`.397    ///398    /// If EOF is reached, then `false` is returned. Otherwise, `true` is399    /// returned. (Note that if this line buffer's binary detection is set to400    /// `Quit`, then the presence of binary data will cause this buffer to401    /// behave as if it had seen EOF.)402    ///403    /// This forwards any errors returned by `rdr`, and will also return an404    /// error if the buffer must be expanded past its allocation limit, as405    /// governed by the buffer allocation strategy.406    fn fill<R: io::Read>(&mut self, mut rdr: R) -> Result<bool, io::Error> {407        // If the binary detection heuristic tells us to quit once binary data408        // has been observed, then we no longer read new data and reach EOF409        // once the current buffer has been consumed.410        if self.config.binary.is_quit() && self.binary_byte_offset.is_some() {411            return Ok(!self.buffer().is_empty());412        }413414        self.roll();415        assert_eq!(self.pos, 0);416        loop {417            self.ensure_capacity()?;418            let readlen = rdr.read(self.free_buffer().as_bytes_mut())?;419            if readlen == 0 {420                // We're only done reading for good once the caller has421                // consumed everything.422                self.last_lineterm = self.end;423                return Ok(!self.buffer().is_empty());424            }425426            // Get a mutable view into the bytes we've just read. These are427            // the bytes that we do binary detection on, and also the bytes we428            // search to find the last line terminator. We need a mutable slice429            // in the case of binary conversion.430            let oldend = self.end;431            self.end += readlen;432            let newbytes = &mut self.buf[oldend..self.end];433434            // Binary detection.435            match self.config.binary {436                BinaryDetection::None => {} // nothing to do437                BinaryDetection::Quit(byte) => {438                    if let Some(i) = newbytes.find_byte(byte) {439                        self.end = oldend + i;440                        self.last_lineterm = self.end;441                        self.binary_byte_offset =442                            Some(self.absolute_byte_offset + self.end as u64);443                        // If the first byte in our buffer is a binary byte,444                        // then our buffer is empty and we should report as445                        // such to the caller.446                        return Ok(self.pos < self.end);447                    }448                }449                BinaryDetection::Convert(byte) => {450                    if let Some(i) =451                        replace_bytes(newbytes, byte, self.config.lineterm)452                    {453                        // Record only the first binary offset.454                        if self.binary_byte_offset.is_none() {455                            self.binary_byte_offset = Some(456                                self.absolute_byte_offset457                                    + (oldend + i) as u64,458                            );459                        }460                    }461                }462            }463464            // Update our `last_lineterm` positions if we read one.465            if let Some(i) = newbytes.rfind_byte(self.config.lineterm) {466                self.last_lineterm = oldend + i + 1;467                return Ok(true);468            }469            // At this point, if we couldn't find a line terminator, then we470            // don't have a complete line. Therefore, we try to read more!471        }472    }473474    /// Roll the unconsumed parts of the buffer to the front.475    ///476    /// This operation is idempotent.477    ///478    /// After rolling, `last_lineterm` and `end` point to the same location,479    /// and `pos` is always set to `0`.480    fn roll(&mut self) {481        if self.pos == self.end {482            self.pos = 0;483            self.last_lineterm = 0;484            self.end = 0;485            return;486        }487488        let roll_len = self.end - self.pos;489        self.buf.copy_within(self.pos..self.end, 0);490        self.pos = 0;491        self.last_lineterm = roll_len;492        self.end = roll_len;493    }494495    /// Ensures that the internal buffer has a non-zero amount of free space496    /// in which to read more data. If there is no free space, then more is497    /// allocated. If the allocation must exceed the configured limit, then498    /// this returns an error.499    fn ensure_capacity(&mut self) -> Result<(), io::Error> {500        if !self.free_buffer().is_empty() {501            return Ok(());502        }503        // `len` is used for computing the next allocation size. The capacity504        // is permitted to start at `0`, so we make sure it's at least `1`.505        let len = std::cmp::max(1, self.buf.len());506        let additional = match self.config.buffer_alloc {507            BufferAllocation::Eager => len * 2,508            BufferAllocation::Error(limit) => {509                let used = self.buf.len() - self.config.capacity;510                let n = std::cmp::min(len * 2, limit - used);511                if n == 0 {512                    return Err(alloc_error(self.config.capacity + limit));513                }514                n515            }516        };517        assert!(additional > 0);518        let newlen = self.buf.len() + additional;519        self.buf.resize(newlen, 0);520        assert!(!self.free_buffer().is_empty());521        Ok(())522    }523}524525/// Replaces `src` with `replacement` in bytes, and return the offset of the526/// first replacement, if one exists.527fn replace_bytes(528    mut bytes: &mut [u8],529    src: u8,530    replacement: u8,531) -> Option<usize> {532    if src == replacement {533        return None;534    }535    let first_pos = bytes.find_byte(src)?;536    bytes[first_pos] = replacement;537    bytes = &mut bytes[first_pos + 1..];538    while let Some(i) = bytes.find_byte(src) {539        bytes[i] = replacement;540        bytes = &mut bytes[i + 1..];541542        // To search for adjacent `src` bytes we use a different strategy.543        // Since binary data tends to have long runs of NUL terminators,544        // it is faster to compare one-byte-at-a-time than to stop and start545        // memchr (through `find_byte`) for every byte in a sequence.546        while bytes.get(0) == Some(&src) {547            bytes[0] = replacement;548            bytes = &mut bytes[1..];549        }550    }551    Some(first_pos)552}553554#[cfg(test)]555mod tests {556    use bstr::ByteVec;557558    use super::*;559560    const SHERLOCK: &'static str = "\561For the Doctor Watsons of this world, as opposed to the Sherlock562Holmeses, success in the province of detective work must always563be, to a very large extent, the result of luck. Sherlock Holmes564can extract a clew from a wisp of straw or a flake of cigar ash;565but Doctor Watson has to have it taken out for him and dusted,566and exhibited clearly, with a label attached.\567";568569    fn s(slice: &str) -> String {570        slice.to_string()571    }572573    fn replace_str(574        slice: &str,575        src: u8,576        replacement: u8,577    ) -> (String, Option<usize>) {578        let mut dst = Vec::from(slice);579        let result = replace_bytes(&mut dst, src, replacement);580        (dst.into_string().unwrap(), result)581    }582583    #[test]584    fn replace() {585        assert_eq!(replace_str("", b'b', b'z'), (s(""), None));586        assert_eq!(replace_str("a", b'a', b'a'), (s("a"), None));587        assert_eq!(replace_str("a", b'b', b'z'), (s("a"), None));588        assert_eq!(replace_str("abc", b'b', b'z'), (s("azc"), Some(1)));589        assert_eq!(replace_str("abb", b'b', b'z'), (s("azz"), Some(1)));590        assert_eq!(replace_str("aba", b'a', b'z'), (s("zbz"), Some(0)));591        assert_eq!(replace_str("bbb", b'b', b'z'), (s("zzz"), Some(0)));592        assert_eq!(replace_str("bac", b'b', b'z'), (s("zac"), Some(0)));593    }594595    #[test]596    fn buffer_basics1() {597        let bytes = "homer\nlisa\nmaggie";598        let mut linebuf = LineBufferBuilder::new().build();599        let mut rdr = LineBufferReader::new(bytes.as_bytes(), &mut linebuf);600601        assert!(rdr.buffer().is_empty());602603        assert!(rdr.fill().unwrap());604        assert_eq!(rdr.bstr(), "homer\nlisa\n");605        assert_eq!(rdr.absolute_byte_offset(), 0);606        rdr.consume(5);607        assert_eq!(rdr.absolute_byte_offset(), 5);608        rdr.consume_all();609        assert_eq!(rdr.absolute_byte_offset(), 11);610611        assert!(rdr.fill().unwrap());612        assert_eq!(rdr.bstr(), "maggie");613        rdr.consume_all();614615        assert!(!rdr.fill().unwrap());616        assert_eq!(rdr.absolute_byte_offset(), bytes.len() as u64);617        assert_eq!(rdr.binary_byte_offset(), None);618    }619620    #[test]621    fn buffer_basics2() {622        let bytes = "homer\nlisa\nmaggie\n";623        let mut linebuf = LineBufferBuilder::new().build();624        let mut rdr = LineBufferReader::new(bytes.as_bytes(), &mut linebuf);625626        assert!(rdr.fill().unwrap());627        assert_eq!(rdr.bstr(), "homer\nlisa\nmaggie\n");628        rdr.consume_all();629630        assert!(!rdr.fill().unwrap());631        assert_eq!(rdr.absolute_byte_offset(), bytes.len() as u64);632        assert_eq!(rdr.binary_byte_offset(), None);633    }634635    #[test]636    fn buffer_basics3() {637        let bytes = "\n";638        let mut linebuf = LineBufferBuilder::new().build();639        let mut rdr = LineBufferReader::new(bytes.as_bytes(), &mut linebuf);640641        assert!(rdr.fill().unwrap());642        assert_eq!(rdr.bstr(), "\n");643        rdr.consume_all();644645        assert!(!rdr.fill().unwrap());646        assert_eq!(rdr.absolute_byte_offset(), bytes.len() as u64);647        assert_eq!(rdr.binary_byte_offset(), None);648    }649650    #[test]651    fn buffer_basics4() {652        let bytes = "\n\n";653        let mut linebuf = LineBufferBuilder::new().build();654        let mut rdr = LineBufferReader::new(bytes.as_bytes(), &mut linebuf);655656        assert!(rdr.fill().unwrap());657        assert_eq!(rdr.bstr(), "\n\n");658        rdr.consume_all();659660        assert!(!rdr.fill().unwrap());661        assert_eq!(rdr.absolute_byte_offset(), bytes.len() as u64);662        assert_eq!(rdr.binary_byte_offset(), None);663    }664665    #[test]666    fn buffer_empty() {667        let bytes = "";668        let mut linebuf = LineBufferBuilder::new().build();669        let mut rdr = LineBufferReader::new(bytes.as_bytes(), &mut linebuf);670671        assert!(!rdr.fill().unwrap());672        assert_eq!(rdr.absolute_byte_offset(), bytes.len() as u64);673        assert_eq!(rdr.binary_byte_offset(), None);674    }675676    #[test]677    fn buffer_zero_capacity() {678        let bytes = "homer\nlisa\nmaggie";679        let mut linebuf = LineBufferBuilder::new().capacity(0).build();680        let mut rdr = LineBufferReader::new(bytes.as_bytes(), &mut linebuf);681682        while rdr.fill().unwrap() {683            rdr.consume_all();684        }685        assert_eq!(rdr.absolute_byte_offset(), bytes.len() as u64);686        assert_eq!(rdr.binary_byte_offset(), None);687    }688689    #[test]690    fn buffer_small_capacity() {691        let bytes = "homer\nlisa\nmaggie";692        let mut linebuf = LineBufferBuilder::new().capacity(1).build();693        let mut rdr = LineBufferReader::new(bytes.as_bytes(), &mut linebuf);694695        let mut got = vec![];696        while rdr.fill().unwrap() {697            got.push_str(rdr.buffer());698            rdr.consume_all();699        }700        assert_eq!(bytes, got.as_bstr());701        assert_eq!(rdr.absolute_byte_offset(), bytes.len() as u64);702        assert_eq!(rdr.binary_byte_offset(), None);703    }704705    #[test]706    fn buffer_limited_capacity1() {707        let bytes = "homer\nlisa\nmaggie";708        let mut linebuf = LineBufferBuilder::new()709            .capacity(1)710            .buffer_alloc(BufferAllocation::Error(5))711            .build();712        let mut rdr = LineBufferReader::new(bytes.as_bytes(), &mut linebuf);713714        assert!(rdr.fill().unwrap());715        assert_eq!(rdr.bstr(), "homer\n");716        rdr.consume_all();717718        assert!(rdr.fill().unwrap());719        assert_eq!(rdr.bstr(), "lisa\n");720        rdr.consume_all();721722        // This returns an error because while we have just enough room to723        // store maggie in the buffer, we *don't* have enough room to read one724        // more byte, so we don't know whether we're at EOF or not, and725        // therefore must give up.726        assert!(rdr.fill().is_err());727728        // We can mush on though!729        assert_eq!(rdr.bstr(), "m");730        rdr.consume_all();731732        assert!(rdr.fill().unwrap());733        assert_eq!(rdr.bstr(), "aggie");734        rdr.consume_all();735736        assert!(!rdr.fill().unwrap());737    }738739    #[test]740    fn buffer_limited_capacity2() {741        let bytes = "homer\nlisa\nmaggie";742        let mut linebuf = LineBufferBuilder::new()743            .capacity(1)744            .buffer_alloc(BufferAllocation::Error(6))745            .build();746        let mut rdr = LineBufferReader::new(bytes.as_bytes(), &mut linebuf);747748        assert!(rdr.fill().unwrap());749        assert_eq!(rdr.bstr(), "homer\n");750        rdr.consume_all();751752        assert!(rdr.fill().unwrap());753        assert_eq!(rdr.bstr(), "lisa\n");754        rdr.consume_all();755756        // We have just enough space.757        assert!(rdr.fill().unwrap());758        assert_eq!(rdr.bstr(), "maggie");759        rdr.consume_all();760761        assert!(!rdr.fill().unwrap());762    }763764    #[test]765    fn buffer_limited_capacity3() {766        let bytes = "homer\nlisa\nmaggie";767        let mut linebuf = LineBufferBuilder::new()768            .capacity(1)769            .buffer_alloc(BufferAllocation::Error(0))770            .build();771        let mut rdr = LineBufferReader::new(bytes.as_bytes(), &mut linebuf);772773        assert!(rdr.fill().is_err());774        assert_eq!(rdr.bstr(), "");775    }776777    #[test]778    fn buffer_binary_none() {779        let bytes = "homer\nli\x00sa\nmaggie\n";780        let mut linebuf = LineBufferBuilder::new().build();781        let mut rdr = LineBufferReader::new(bytes.as_bytes(), &mut linebuf);782783        assert!(rdr.buffer().is_empty());784785        assert!(rdr.fill().unwrap());786        assert_eq!(rdr.bstr(), "homer\nli\x00sa\nmaggie\n");787        rdr.consume_all();788789        assert!(!rdr.fill().unwrap());790        assert_eq!(rdr.absolute_byte_offset(), bytes.len() as u64);791        assert_eq!(rdr.binary_byte_offset(), None);792    }793794    #[test]795    fn buffer_binary_quit1() {796        let bytes = "homer\nli\x00sa\nmaggie\n";797        let mut linebuf = LineBufferBuilder::new()798            .binary_detection(BinaryDetection::Quit(b'\x00'))799            .build();800        let mut rdr = LineBufferReader::new(bytes.as_bytes(), &mut linebuf);801802        assert!(rdr.buffer().is_empty());803804        assert!(rdr.fill().unwrap());805        assert_eq!(rdr.bstr(), "homer\nli");806        rdr.consume_all();807808        assert!(!rdr.fill().unwrap());809        assert_eq!(rdr.absolute_byte_offset(), 8);810        assert_eq!(rdr.binary_byte_offset(), Some(8));811    }812813    #[test]814    fn buffer_binary_quit2() {815        let bytes = "\x00homer\nlisa\nmaggie\n";816        let mut linebuf = LineBufferBuilder::new()817            .binary_detection(BinaryDetection::Quit(b'\x00'))818            .build();819        let mut rdr = LineBufferReader::new(bytes.as_bytes(), &mut linebuf);820821        assert!(!rdr.fill().unwrap());822        assert_eq!(rdr.bstr(), "");823        assert_eq!(rdr.absolute_byte_offset(), 0);824        assert_eq!(rdr.binary_byte_offset(), Some(0));825    }826827    #[test]828    fn buffer_binary_quit3() {829        let bytes = "homer\nlisa\nmaggie\n\x00";830        let mut linebuf = LineBufferBuilder::new()831            .binary_detection(BinaryDetection::Quit(b'\x00'))832            .build();833        let mut rdr = LineBufferReader::new(bytes.as_bytes(), &mut linebuf);834835        assert!(rdr.buffer().is_empty());836837        assert!(rdr.fill().unwrap());838        assert_eq!(rdr.bstr(), "homer\nlisa\nmaggie\n");839        rdr.consume_all();840841        assert!(!rdr.fill().unwrap());842        assert_eq!(rdr.absolute_byte_offset(), bytes.len() as u64 - 1);843        assert_eq!(rdr.binary_byte_offset(), Some(bytes.len() as u64 - 1));844    }845846    #[test]847    fn buffer_binary_quit4() {848        let bytes = "homer\nlisa\nmaggie\x00\n";849        let mut linebuf = LineBufferBuilder::new()850            .binary_detection(BinaryDetection::Quit(b'\x00'))851            .build();852        let mut rdr = LineBufferReader::new(bytes.as_bytes(), &mut linebuf);853854        assert!(rdr.buffer().is_empty());855856        assert!(rdr.fill().unwrap());857        assert_eq!(rdr.bstr(), "homer\nlisa\nmaggie");858        rdr.consume_all();859860        assert!(!rdr.fill().unwrap());861        assert_eq!(rdr.absolute_byte_offset(), bytes.len() as u64 - 2);862        assert_eq!(rdr.binary_byte_offset(), Some(bytes.len() as u64 - 2));863    }864865    #[test]866    fn buffer_binary_quit5() {867        let mut linebuf = LineBufferBuilder::new()868            .binary_detection(BinaryDetection::Quit(b'u'))869            .build();870        let mut rdr = LineBufferReader::new(SHERLOCK.as_bytes(), &mut linebuf);871872        assert!(rdr.buffer().is_empty());873874        assert!(rdr.fill().unwrap());875        assert_eq!(876            rdr.bstr(),877            "\878For the Doctor Watsons of this world, as opposed to the Sherlock879Holmeses, s\880"881        );882        rdr.consume_all();883884        assert!(!rdr.fill().unwrap());885        assert_eq!(rdr.absolute_byte_offset(), 76);886        assert_eq!(rdr.binary_byte_offset(), Some(76));887        assert_eq!(SHERLOCK.as_bytes()[76], b'u');888    }889890    #[test]891    fn buffer_binary_convert1() {892        let bytes = "homer\nli\x00sa\nmaggie\n";893        let mut linebuf = LineBufferBuilder::new()894            .binary_detection(BinaryDetection::Convert(b'\x00'))895            .build();896        let mut rdr = LineBufferReader::new(bytes.as_bytes(), &mut linebuf);897898        assert!(rdr.buffer().is_empty());899900        assert!(rdr.fill().unwrap());901        assert_eq!(rdr.bstr(), "homer\nli\nsa\nmaggie\n");902        rdr.consume_all();903904        assert!(!rdr.fill().unwrap());905        assert_eq!(rdr.absolute_byte_offset(), bytes.len() as u64);906        assert_eq!(rdr.binary_byte_offset(), Some(8));907    }908909    #[test]910    fn buffer_binary_convert2() {911        let bytes = "\x00homer\nlisa\nmaggie\n";912        let mut linebuf = LineBufferBuilder::new()913            .binary_detection(BinaryDetection::Convert(b'\x00'))914            .build();915        let mut rdr = LineBufferReader::new(bytes.as_bytes(), &mut linebuf);916917        assert!(rdr.buffer().is_empty());918919        assert!(rdr.fill().unwrap());920        assert_eq!(rdr.bstr(), "\nhomer\nlisa\nmaggie\n");921        rdr.consume_all();922923        assert!(!rdr.fill().unwrap());924        assert_eq!(rdr.absolute_byte_offset(), bytes.len() as u64);925        assert_eq!(rdr.binary_byte_offset(), Some(0));926    }927928    #[test]929    fn buffer_binary_convert3() {930        let bytes = "homer\nlisa\nmaggie\n\x00";931        let mut linebuf = LineBufferBuilder::new()932            .binary_detection(BinaryDetection::Convert(b'\x00'))933            .build();934        let mut rdr = LineBufferReader::new(bytes.as_bytes(), &mut linebuf);935936        assert!(rdr.buffer().is_empty());937938        assert!(rdr.fill().unwrap());939        assert_eq!(rdr.bstr(), "homer\nlisa\nmaggie\n\n");940        rdr.consume_all();941942        assert!(!rdr.fill().unwrap());943        assert_eq!(rdr.absolute_byte_offset(), bytes.len() as u64);944        assert_eq!(rdr.binary_byte_offset(), Some(bytes.len() as u64 - 1));945    }946947    #[test]948    fn buffer_binary_convert4() {949        let bytes = "homer\nlisa\nmaggie\x00\n";950        let mut linebuf = LineBufferBuilder::new()951            .binary_detection(BinaryDetection::Convert(b'\x00'))952            .build();953        let mut rdr = LineBufferReader::new(bytes.as_bytes(), &mut linebuf);954955        assert!(rdr.buffer().is_empty());956957        assert!(rdr.fill().unwrap());958        assert_eq!(rdr.bstr(), "homer\nlisa\nmaggie\n\n");959        rdr.consume_all();960961        assert!(!rdr.fill().unwrap());962        assert_eq!(rdr.absolute_byte_offset(), bytes.len() as u64);963        assert_eq!(rdr.binary_byte_offset(), Some(bytes.len() as u64 - 2));964    }965}