buffer-redux-1.0.2/.cargo_vcs_info.json0000644000000001360000000000100134320ustar { "git": { "sha1": "a963936b6d60690b2724a82e0b5ea11b4fcc8500" }, "path_in_vcs": "" }buffer-redux-1.0.2/.github/dependabot.yml000064400000000000000000000002011046102023000164030ustar 00000000000000version: 2 updates: - package-ecosystem: cargo directory: "/" schedule: interval: monthly open-pull-requests-limit: 10 buffer-redux-1.0.2/.github/workflows/ci.yml000064400000000000000000000064311046102023000167410ustar 00000000000000name: CI on: pull_request: push: branches: - master env: RUST_BACKTRACE: 1 RUSTFLAGS: -Dwarnings jobs: build_and_test_nix: name: Build and test (Nix) runs-on: ${{ matrix.os }} strategy: matrix: os: [ubuntu-latest, macOS-latest] rust: [nightly, beta, stable] steps: - name: Checkout uses: actions/checkout@master with: submodules: recursive - name: Install ${{ matrix.rust }} uses: actions-rs/toolchain@v1 with: toolchain: ${{ matrix.rust }} override: true - name: check uses: actions-rs/cargo@v1 with: command: check args: --all --bins --tests - name: check bench uses: actions-rs/cargo@v1 if: matrix.rust == 'nightly' with: command: check args: --benches - name: check no default features uses: actions-rs/cargo@v1 with: command: check args: --no-default-features - name: tests uses: actions-rs/cargo@v1 with: command: test args: --all - name: no default features uses: actions-rs/cargo@v1 with: command: test args: --all --no-default-features build_and_test_windows: name: Build and test (Windows) runs-on: ${{ matrix.os }} strategy: matrix: os: [windows-latest] rust: [nightly, beta, stable] target: - x86_64-pc-windows-gnu - x86_64-pc-windows-msvc steps: - name: Checkout uses: actions/checkout@master with: submodules: recursive - name: Install ${{ matrix.rust }} uses: actions-rs/toolchain@v1 with: toolchain: ${{ matrix.rust }} target: ${{ matrix.target }} override: true - uses: msys2/setup-msys2@v2 - name: check uses: actions-rs/cargo@v1 with: command: check args: --all --bins --tests --target ${{ matrix.target }} - name: check no default features uses: actions-rs/cargo@v1 with: command: check override: true args: --no-default-features - name: check bench uses: actions-rs/cargo@v1 if: matrix.rust == 'nightly' with: command: check target: ${{ matrix.target }} args: --benches - name: tests uses: actions-rs/cargo@v1 with: command: test args: --all --target ${{ matrix.target }} check_fmt_and_docs: name: Checking fmt and docs runs-on: ubuntu-latest steps: - uses: actions/checkout@master - uses: actions-rs/toolchain@v1 with: profile: minimal toolchain: nightly override: true components: rustfmt - name: setup run: | rustup component add rustfmt rustc --version - name: fmt run: cargo fmt --all -- --check - name: Docs run: cargo doc clippy_check: runs-on: ubuntu-latest steps: - uses: actions/checkout@master - uses: actions-rs/toolchain@v1 with: profile: minimal toolchain: nightly override: true components: clippy - uses: actions-rs/clippy-check@v1 with: token: ${{ secrets.GITHUB_TOKEN }} args: --all-features --all-targets buffer-redux-1.0.2/.gitignore000064400000000000000000000004371046102023000142160ustar 00000000000000# Compiled files *.o *.so *.rlib *.dll # Executables *.exe # Generated by Cargo /target/ # Remove Cargo.lock from gitignore if creating an executable, leave it for libraries # More information here http://doc.crates.io/guide.html#cargotoml-vs-cargolock Cargo.lock .idea/ .lock *.iml buffer-redux-1.0.2/Cargo.toml0000644000000025310000000000100114310ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2021" name = "buffer-redux" version = "1.0.2" authors = [ "dignifiedquire ", "Austin Bonander ", ] build = false autobins = false autoexamples = false autotests = false autobenches = false description = "Drop-in replacements for buffered I/O in `std::io` with extra features." documentation = "https://docs.rs/buffer-redux" readme = "README.md" keywords = [ "io", "buffer", "buffered", ] license = "MIT OR Apache-2.0" repository = "https://github.com/dignifiedquire/buffer-redux" [lib] name = "buffer_redux" path = "src/lib.rs" [[bench]] name = "construction" path = "benches/construction.rs" [dependencies.memchr] version = "2.0" [features] default = ["slice-deque"] slice-deque = ["dep:slice-ring-buffer"] [target."cfg(any(unix, windows))".dependencies.slice-ring-buffer] version = "0.3" optional = true buffer-redux-1.0.2/Cargo.toml.orig000064400000000000000000000013321046102023000151100ustar 00000000000000[package] name = "buffer-redux" version = "1.0.2" authors = ["dignifiedquire ", "Austin Bonander "] description = "Drop-in replacements for buffered I/O in `std::io` with extra features." keywords = ["io", "buffer", "buffered"] documentation = "https://docs.rs/buffer-redux" repository = "https://github.com/dignifiedquire/buffer-redux" license = "MIT OR Apache-2.0" readme = "README.md" edition = "2021" [dependencies] memchr = "2.0" # `slice_deque` is only supported on platforms with virtual memory [target.'cfg(any(unix, windows))'.dependencies.slice-ring-buffer] version = "0.3" optional = true [features] default = ["slice-deque"] slice-deque = ["dep:slice-ring-buffer"] buffer-redux-1.0.2/LICENSE-APACHE000064400000000000000000000251701046102023000141530ustar 00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright 2016-2018 Austin Bonander and The Rust Project Developers Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. buffer-redux-1.0.2/LICENSE-MIT000064400000000000000000000021361046102023000136600ustar 00000000000000The MIT License (MIT) Copyright (c) 2016-2022 Austin Bonander and The Rust Project Developers Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. buffer-redux-1.0.2/README.md000064400000000000000000000137141046102023000135070ustar 00000000000000# buffer-re(a)dux [![Crates.io](https://img.shields.io/crates/v/buffer-redux.svg)](https://crates.io/crates/buffer-redux) [![Crates.io](https://img.shields.io/crates/d/buffer-redux.svg)](https://crates.io/crates/buffer-redux) [![Crates.io](https://img.shields.io/crates/l/buffer-redux.svg)](https://crates.io/crates/buffer-redux) > Fork of the unmaintained [`buf_redux`](https://github.com/abonander/buf_redux). Drop-in replacements for buffered I/O types in `std::io`. These replacements retain the method names/signatures and implemented traits of their stdlib counterparts, making replacement as simple as swapping the import of the type. ### More Direct Control All replacement types provide methods to: * Increase the capacity of the buffer * Get the number of available bytes as well as the total capacity of the buffer * Consume the wrapper without losing data `BufReader` provides methods to: * Access the buffer through an `&`-reference without performing I/O * Force unconditional reads into the buffer * Get a `Read` adapter which empties the buffer and then pulls from the inner reader directly * Shuffle bytes down to the beginning of the buffer to make room for more reading * Get inner reader and trimmed buffer with the remaining data `BufWriter` and `LineWriter` provide methods to: * Flush the buffer and unwrap the inner writer unconditionally. ### More Sensible and Customizable Buffering Behavior Tune the behavior of the buffer to your specific use-case using the types in the `policy` module: * Refine `BufReader`'s behavior by implementing the `ReaderPolicy` trait or use an existing implementation like `MinBuffered` to ensure the buffer always contains a minimum number of bytes (until the underlying reader is empty). * Refine `BufWriter`'s behavior by implementing the `WriterPolicy` trait or use an existing implementation like `FlushOn` to flush when a particular byte appears in the buffer (used to implement `LineWriter`). ## Usage #### [Documentation](http://docs.rs/buffer-redux/) `Cargo.toml`: ```toml [dependencies] buffer-redux = "0.2" ``` And then simply swap the import of the types you want to replace: #### `BufReader`: ``` - use std::io::BufReader; + use buffer_redux::BufReader; ``` #### `BufWriter`: ``` - use std::io::BufWriter; + use buffer_redux::BufWriter; ``` #### `LineWriter`: ``` - use std::io::LineWriter; + use buffer_redux::LineWriter; ``` ### Using `MinBuffered` The new `policy::MinBuffered` reader-policy can be used to ensure that `BufReader` always has at least a certain number of bytes in its buffer. This can be useful for parsing applications that require a certain amount of lookahead. ```rust use buffer_redux::BufReader; use buffer_redux::policy::MinBuffered; use std::io::{BufRead, Cursor}; let data = (1 .. 16).collect::>(); // normally you should use `BufReader::new()` or give a capacity of several KiB or more let mut reader = BufReader::with_capacity(8, Cursor::new(data)) // always at least 4 bytes in the buffer (or until the source is empty) .set_policy(MinBuffered(4)); // always at least 4 bytes in the buffer // first buffer fill, same as `std::io::BufReader` assert_eq!(reader.fill_buf().unwrap(), &[1, 2, 3, 4, 5, 6, 7, 8]); reader.consume(3); // enough data in the buffer, another read isn't done yet assert_eq!(reader.fill_buf().unwrap(), &[4, 5, 6, 7, 8]); reader.consume(4); // `std::io::BufReader` would return `&[8]` assert_eq!(reader.fill_buf().unwrap(), &[8, 9, 10, 11, 12, 13, 14, 15]); reader.consume(5); // no data left in the reader assert_eq!(reader.fill_buf().unwrap(), &[13, 14, 15]); ``` ### Note: Making Room / Ringbuffers / `slice-deque` Feature With policies like `MinBuffered`, that will read into the buffer and consume bytes from it without completely emptying it, normal buffer handling can run out of room to read/write into as all the free space is at the head of the buffer. If the amount of data in the buffer is small, you can call `.make_room()` on the buffered type to make more room for reading. `MinBuffered` will do this automatically. Instead of this, with the `slice-deque` feature, you can instead have your buffered type allocate a *ringbuffer*, simply by using the `::new_ringbuf()` or `::with_capacity_ringbuf()` constructors instead of `::new()` or `with_capacity()`, respectively. With a ringbuffer, consuming/flushing bytes from a buffer instantly makes room for more reading/writing at the end. However, this has some caveats: * It is only available on target platforms with virtual memory support, namely fully fledged OSes such as Windows and Unix-derivative platforms like Linux, OS X, BSD variants, etc. * The default capacity varies based on platform, and custom capacities are rounded up to a multiple of their minimum size, typically the page size of the platform. Windows' minimum size is comparably quite large (**64 KiB**) due to some legacy reasons, so this may be less optimal than the default capacity for a normal buffer (8 KiB) for some use-cases. * Due to the nature of the virtual-memory trick, the virtual address space the buffer allocates will be double its capacity. This means that your program will *appear* to use more memory than it would if it was using a normal buffer of the same capacity. The physical memory usage will be the same in both cases, but if address space is at a premium in your application (32-bit targets) then this may be a concern. It is up to you to decide if the benefits outweigh the costs. With a policy like `MinBuffered`, it could significantly improve performance. ## License Licensed under either of * Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) at your option. ### Contribution Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions. buffer-redux-1.0.2/benches/construction.rs000064400000000000000000000007451046102023000167370ustar 00000000000000#![feature(test)] extern crate test; use buffer_redux::{BufReader, BufWriter}; use std::io; #[bench] fn bufreader(b: &mut test::Bencher) { b.iter(|| BufReader::new(io::empty())); } #[bench] fn std_bufreader(b: &mut test::Bencher) { b.iter(|| io::BufReader::new(io::empty())); } #[bench] fn bufwriter(b: &mut test::Bencher) { b.iter(|| BufWriter::new(io::sink())); } #[bench] fn std_bufwriter(b: &mut test::Bencher) { b.iter(|| io::BufWriter::new(io::sink())); } buffer-redux-1.0.2/src/buffer/mod.rs000064400000000000000000000065441046102023000154200ustar 00000000000000#![allow(missing_docs)] mod std_buf; #[cfg(feature = "slice-deque")] mod slice_deque_buf; use std::mem::MaybeUninit; use self::std_buf::StdBuf; #[cfg(feature = "slice-deque")] use self::slice_deque_buf::SliceDequeBuf; pub enum BufImpl { Std(StdBuf), #[cfg(feature = "slice-deque")] Ringbuf(SliceDequeBuf), } macro_rules! forward_method { ($(#[$m:meta])* pub fn $fnname:ident(&self $($args:tt)*) [$($passargs:tt)*] $(-> $ret:ty)*) => { $(#[$m])* pub fn $fnname(&self $($args)*) $(-> $ret)* { match *self { BufImpl::Std(ref buf) => buf.$fnname($($passargs)*), #[cfg(feature = "slice-deque")] BufImpl::Ringbuf(ref buf) => buf.$fnname($($passargs)*), } } }; ($(#[$m:meta])* pub fn $fnname:ident(&mut self $($args:tt)*) [$($passargs:tt)*] $(-> $ret:ty)*) => { $(#[$m])* pub fn $fnname(&mut self $($args)*) $(-> $ret)* { match *self { BufImpl::Std(ref mut buf) => buf.$fnname($($passargs)*), #[cfg(feature = "slice-deque")] BufImpl::Ringbuf(ref mut buf) => buf.$fnname($($passargs)*), } } }; ($(#[$m:meta])* pub unsafe fn $fnname:ident(&self $($args:tt)*) [$($passargs:tt)*] $(-> $ret:ty)*) => { $(#[$m])* pub unsafe fn $fnname(&self $($args)*) $(-> $ret)* { match *self { BufImpl::Std(ref buf) => buf.$fnname($($passargs)*), #[cfg(feature = "slice-deque")] BufImpl::Ringbuf(ref buf) => buf.$fnname($($passargs)*), } } }; ($(#[$m:meta])* pub unsafe fn $fnname:ident(&mut self $($args:tt)*) [$($passargs:tt)*] $(-> $ret:ty)*) => { $(#[$m])* pub unsafe fn $fnname(&mut self $($args)*) $(-> $ret)* { match *self { BufImpl::Std(ref mut buf) => buf.$fnname($($passargs)*), #[cfg(feature = "slice-deque")] BufImpl::Ringbuf(ref mut buf) => buf.$fnname($($passargs)*), } } }; } macro_rules! forward_methods { ($($(#[$m:meta])* $($qualifiers:ident)+ ($($args:tt)*) [$($passargs:tt)*] $(-> $ret:ty)*);+;) => ( $(forward_method! { $(#[$m])* $($qualifiers)+ ($($args)*) [$($passargs)*] $(-> $ret)* })* ) } impl BufImpl { pub fn with_capacity(cap: usize) -> Self { BufImpl::Std(StdBuf::with_capacity(cap)) } #[cfg(feature = "slice-deque")] pub fn with_capacity_ringbuf(cap: usize) -> Self { BufImpl::Ringbuf(SliceDequeBuf::with_capacity(cap)) } pub fn is_ringbuf(&self) -> bool { match *self { #[cfg(feature = "slice-deque")] BufImpl::Ringbuf(_) => true, _ => false, } } forward_methods! { pub fn capacity(&self)[] -> usize; pub fn len(&self)[] -> usize; pub fn usable_space(&self)[] -> usize; pub fn reserve(&mut self, additional: usize)[additional] -> bool; pub fn make_room(&mut self)[]; #[inline] pub fn buf(&self)[] -> &[u8]; pub fn buf_mut(&mut self)[] -> &mut [u8]; pub unsafe fn write_buf(&mut self)[] -> &mut [MaybeUninit]; pub unsafe fn bytes_written(&mut self, add: usize)[add]; pub fn consume(&mut self, amt: usize)[amt]; } } buffer-redux-1.0.2/src/buffer/slice_deque_buf.rs000064400000000000000000000040321046102023000177450ustar 00000000000000//! Move-free buffer and reader utilizing the [`slice-ring-buffer`] crate. //! //! These types are only available on target platforms with virtual memory support, //! namely Windows, OS X and Linux. //! //! [`slice-ring-buffer`]: https://crates.io/crates/slice-ring-buffer use slice_ring_buffer::SliceRingBuffer as SliceDeque; use std::{cmp, mem::MaybeUninit}; pub struct SliceDequeBuf { deque: SliceDeque, } /// Move-free buffer utilizing the [`slice-deque`] crate. /// /// Its usable space will always be equal to its free space. /// /// This is only available on target platforms with virtual memory support, /// namely Windows, OS X and Linux. impl SliceDequeBuf { pub fn with_capacity(cap: usize) -> Self { SliceDequeBuf { deque: SliceDeque::with_capacity(cap), } } pub fn capacity(&self) -> usize { self.deque.capacity() } pub fn len(&self) -> usize { self.deque.len() } pub fn usable_space(&self) -> usize { self.capacity() - self.len() } pub fn reserve(&mut self, additional: usize) -> bool { self.deque.reserve(additional); true } /// This method is a no-op. pub fn make_room(&mut self) {} #[inline] pub fn buf(&self) -> &[u8] { &self.deque } pub fn buf_mut(&mut self) -> &mut [u8] { &mut self.deque } pub unsafe fn write_buf(&mut self) -> &mut [MaybeUninit] { self.deque.tail_head_slice() } pub unsafe fn bytes_written(&mut self, add: usize) { let offset = cmp::min(add, self.usable_space()) as isize; if offset < 0 { panic!("BufImpl.bytes_written() arg overflowed isize: {add:x}"); } self.deque.move_tail(offset); } pub fn consume(&mut self, amt: usize) { unsafe { let offset = cmp::min(amt, self.len()) as isize; if offset < 0 { panic!("BufImpl.consume() arg overflowed isize: {amt:x}") } self.deque.move_head(offset); } } } buffer-redux-1.0.2/src/buffer/std_buf.rs000064400000000000000000000104631046102023000162620ustar 00000000000000use std::{cmp, mem::MaybeUninit}; use self::impl_::RawBuf; pub struct StdBuf { buf: RawBuf, pos: usize, end: usize, } impl StdBuf { pub fn with_capacity(cap: usize) -> Self { StdBuf { buf: RawBuf::with_capacity(cap), pos: 0, end: 0, } } pub fn capacity(&self) -> usize { self.buf.capacity() } pub fn len(&self) -> usize { self.end - self.pos } pub fn usable_space(&self) -> usize { self.capacity() - self.end } pub fn reserve(&mut self, additional: usize) -> bool { self.check_cursors(); let usable_space = self.usable_space(); // there's already enough space if usable_space >= additional { return false; } // attempt to reserve additional capacity in-place if self.buf.reserve_in_place(additional - usable_space) { return false; } // don't copy the contents of the buffer as they're irrelevant now if self.pos == self.end { let capacity = self.buf.capacity(); // free the existing memory self.buf = RawBuf::with_capacity(0); self.buf = RawBuf::with_capacity(capacity + additional); return true; } self.buf.reserve(additional - usable_space) } pub fn make_room(&mut self) { self.check_cursors(); // no room at the head of the buffer if self.pos == 0 { return; } // simply move the bytes down to the beginning let len = self.len(); let buf_slice = unsafe { self.buf.as_mut_slice() }; buf_slice.copy_within(self.pos..self.pos + len, 0); self.pos = 0; self.end = len; } #[inline] pub fn buf(&self) -> &[u8] { unsafe { &self.buf.as_slice()[self.pos..self.end] } } pub fn buf_mut(&mut self) -> &mut [u8] { unsafe { &mut self.buf.as_mut_slice()[self.pos..self.end] } } pub unsafe fn write_buf(&mut self) -> &mut [MaybeUninit] { let slice: &mut [u8] = &mut self.buf.as_mut_slice()[self.end..]; // SAFETY: &[T] and &[MaybeUninit] have the same layout std::mem::transmute(slice) } pub unsafe fn bytes_written(&mut self, amt: usize) { self.end = cmp::min(self.end + amt, self.capacity()); } pub fn consume(&mut self, amt: usize) { self.pos = cmp::min(self.pos + amt, self.end); self.check_cursors(); } pub fn check_cursors(&mut self) -> bool { if self.pos == self.end { self.pos = 0; self.end = 0; true } else { false } } } mod impl_ { use std::mem; pub struct RawBuf { buf: Box<[u8]>, } impl RawBuf { pub fn with_capacity(capacity: usize) -> Self { let mut buf = Vec::with_capacity(capacity); let true_cap = buf.capacity(); unsafe { buf.set_len(true_cap); } RawBuf { buf: buf.into_boxed_slice(), } } pub fn capacity(&self) -> usize { self.buf.len() } pub fn reserve(&mut self, additional: usize) -> bool { let mut buf = mem::replace(&mut self.buf, Box::new([])).into_vec(); let old_ptr = self.buf.as_ptr(); buf.reserve_exact(additional); unsafe { let new_cap = buf.capacity(); buf.set_len(new_cap); } self.buf = buf.into_boxed_slice(); old_ptr == self.buf.as_ptr() } pub fn reserve_in_place(&mut self, _additional: usize) -> bool { // `Vec` does not support this false } #[inline] pub unsafe fn as_slice(&self) -> &[u8] { &self.buf } pub unsafe fn as_mut_slice(&mut self) -> &mut [u8] { &mut self.buf } } } #[test] fn read_into_full() { use crate::Buffer; let mut buffer = Buffer::with_capacity(1); assert_eq!(buffer.capacity(), 1); let mut bytes = &[1u8, 2][..]; // Result does not impl PartialEq assert_eq!(buffer.read_from(&mut bytes).unwrap(), 1); assert_eq!(buffer.read_from(&mut bytes).unwrap(), 0); } buffer-redux-1.0.2/src/lib.rs000064400000000000000000001403711046102023000141330ustar 00000000000000// Original implementation Copyright 2013 The Rust Project Developers // Original source file: https://github.com/rust-lang/rust/blob/master/src/libstd/io/buffered.P // Additions copyright 2016-2018 Austin Bonander //! Drop-in replacements for buffered I/O types in `std::io`. //! //! These replacements retain the method names/signatures and implemented traits of their stdlib //! counterparts, making replacement as simple as swapping the import of the type: //! //! #### `BufReader`: //! ```notest //! - use std::io::BufReader; //! + use buffer_redux::BufReader; //! ``` //! #### `BufWriter`: //! ```notest //! - use std::io::BufWriter; //! + use buffer_redux::BufWriter; //! ``` //! #### `LineWriter`: //! ```notest //! - use std::io::LineWriter; //! + use buffer_redux::LineWriter; //! ``` //! //! ### More Direct Control //! All replacement types provide methods to: //! //! * Increase the capacity of the buffer //! * Get the number of available bytes as well as the total capacity of the buffer //! * Consume the wrapper without losing data //! //! `BufReader` provides methods to: //! //! * Access the buffer through an `&`-reference without performing I/O //! * Force unconditional reads into the buffer //! * Get a `Read` adapter which empties the buffer and then pulls from the inner reader directly //! * Shuffle bytes down to the beginning of the buffer to make room for more reading //! * Get inner reader and trimmed buffer with the remaining data //! //! `BufWriter` and `LineWriter` provides methods to: //! //! * Flush the buffer and unwrap the inner writer unconditionally. //! * Get the inner writer and trimmed buffer with the unflushed data. //! //! ### More Sensible and Customizable Buffering Behavior //! Tune the behavior of the buffer to your specific use-case using the types in the //! [`policy` module]: //! //! * Refine `BufReader`'s behavior by implementing the [`ReaderPolicy` trait] or use //! an existing implementation like [`MinBuffered`] to ensure the buffer always contains //! a minimum number of bytes (until the underlying reader is empty). //! //! * Refine `BufWriter`'s behavior by implementing the [`WriterPolicy` trait] //! or use an existing implementation like [`FlushOn`] to flush when a particular byte //! appears in the buffer (used to implement [`LineWriter`]). //! //! [`policy` module]: policy //! [`ReaderPolicy` trait]: policy::ReaderPolicy //! [`MinBuffered`]: policy::MinBuffered //! [`WriterPolicy`]: policy::WriterPolicy //! [`FlushOn`]: policy::FlushOn //! [`LineWriter`]: LineWriter //! //! ### Making Room //! The buffered types of this crate and their `std::io` counterparts, by default, use `Box<[u8]>` //! as their buffer types ([`Buffer`](Buffer) is included as well since it is used internally //! by the other types in this crate). //! //! When one of these types inserts bytes into its buffer, via `BufRead::fill_buf()` (implicitly //! called by `Read::read()`) in `BufReader`'s case or `Write::write()` in `BufWriter`'s case, //! the entire buffer is provided to be read/written into and the number of bytes written is saved. //! The read/written data then resides in the `[0 .. bytes_inserted]` slice of the buffer. //! //! When bytes are consumed from the buffer, via `BufRead::consume()` or `Write::flush()`, //! the number of bytes consumed is added to the start of the slice such that the remaining //! data resides in the `[bytes_consumed .. bytes_inserted]` slice of the buffer. //! //! The `std::io` buffered types, and their counterparts in this crate with their default policies, //! don't have to deal with partially filled buffers as `BufReader` only reads when empty and //! `BufWriter` only flushes when full. //! //! However, because the replacements in this crate are capable of reading on-demand and flushing //! less than a full buffer, they can run out of room in their buffers to read/write data into even //! though there is technically free space, because this free space is at the head of the buffer //! where reading into it would cause the data in the buffer to become non-contiguous. //! //! This isn't technically a problem as the buffer could operate like `VecDeque` in `std` and return //! both slices at once, but this would not fit all use-cases: the `Read::fill_buf()` interface only //! allows one slice to be returned at a time so the older data would need to be completely consumed //! before the newer data can be returned; `BufWriter` could support it as the `Write` interface //! doesn't make an opinion on how the buffer works, but because the data would be non-contiguous //! it would require two flushes to get it all, which could degrade performance. //! //! The obvious solution, then, is to move the existing data down to the beginning of the buffer //! when there is no more room at the end so that more reads/writes into the buffer can be issued. //! This works, and may suit some use-cases where the amount of data left is small and thus copying //! it would be inexpensive, but it is non-optimal. However, this option is provided //! as the `.make_room()` methods, and is utilized by [`policy::MinBuffered`](policy::MinBuffered) //! and [`policy::FlushExact`](policy::FlushExact). //! //! ### Ringbuffers / `slice-deque` Feature //! Instead of moving data, however, it is also possible to use virtual-memory tricks to //! allocate a ringbuffer that loops around on itself in memory and thus is always contiguous, //! as described in [the Wikipedia article on Ringbuffers][ringbuf-wikipedia]. //! //! This is the exact trick used by [the `slice-deque` crate](https://crates.io/crates/slice-deque), //! which is now provided as an optional feature `slice-deque` exposed via the //! `new_ringbuf()` and `with_capacity_ringbuf()` constructors added to the buffered types here. //! When a buffered type is constructed using one of these functions, `.make_room()` is turned into //! a no-op as consuming bytes from the head of the buffer simultaneously makes room at the tail. //! However, this has some caveats: //! //! * It is only available on target platforms with virtual memory support, namely fully fledged //! OSes such as Windows and Unix-derivative platforms like Linux, OS X, BSD variants, etc. //! //! * The default capacity varies based on platform, and custom capacities are rounded up to a //! multiple of their minimum size, typically the page size of the platform. //! Windows' minimum size is comparably quite large (**64 KiB**) due to some legacy reasons, //! so this may be less optimal than the default capacity for a normal buffer (8 KiB) for some //! use-cases. //! //! * Due to the nature of the virtual-memory trick, the virtual address space the buffer //! allocates will be double its capacity. This means that your program will *appear* to use more //! memory than it would if it was using a normal buffer of the same capacity. The physical memory //! usage will be the same in both cases, but if address space is at a premium in your application //! (32-bit targets) then this may be a concern. //! //! [ringbuf-wikipedia]: https://en.wikipedia.org/wiki/Circular_buffer#Optimization #![warn(missing_docs)] // std::io's tests require exact allocation which slice_deque cannot provide mod buffer; #[cfg(all(test, feature = "slice-deque"))] mod ringbuf_tests; #[cfg(test)] mod std_tests; pub mod policy; use std::any::Any; use std::cell::RefCell; use std::io::prelude::*; use std::io::SeekFrom; use std::mem::ManuallyDrop; use std::mem::MaybeUninit; use std::{cmp, error, fmt, io, ptr}; use self::policy::{FlushOnNewline, ReaderPolicy, StdPolicy, WriterPolicy}; use crate::buffer::BufImpl; const DEFAULT_BUF_SIZE: usize = 8 * 1024; /// A drop-in replacement for `std::io::BufReader` with more functionality. /// /// Original method names/signatures and implemented traits are left untouched, /// making replacement as simple as swapping the import of the type. /// /// By default this type implements the behavior of its `std` counterpart: it only reads into /// the buffer when it is empty. /// /// To change this type's behavior, change the policy with [`.set_policy()`] using a type /// from the [`policy` module] or your own implementation of [`ReaderPolicy`]. /// /// Policies that perform alternating reads and consumes without completely emptying the buffer /// may benefit from using a ringbuffer via the [`new_ringbuf()`] and [`with_capacity_ringbuf()`] /// constructors. Ringbuffers are only available on supported platforms with the /// `slice-deque` feature and have some other caveats; see [the crate root docs][ringbufs-root] /// for more details. /// /// [`.set_policy()`]: BufReader::set_policy /// [`policy` module]: policy /// [`ReaderPolicy`]: policy::ReaderPolicy /// [`new_ringbuf()`]: BufReader::new_ringbuf /// [`with_capacity_ringbuf()`]: BufReader::with_capacity_ringbuf /// [ringbufs-root]: index.html#ringbuffers--slice-deque-feature pub struct BufReader { // First field for null pointer optimization. buf: Buffer, inner: R, policy: P, } impl BufReader { /// Create a new `BufReader` wrapping `inner`, utilizing a buffer of /// default capacity and the default [`ReaderPolicy`](policy::ReaderPolicy). pub fn new(inner: R) -> Self { Self::with_capacity(DEFAULT_BUF_SIZE, inner) } /// Create a new `BufReader` wrapping `inner`, utilizing a buffer with a capacity /// of *at least* `cap` bytes and the default [`ReaderPolicy`](policy::ReaderPolicy). /// /// The actual capacity of the buffer may vary based on implementation details of the global /// allocator. pub fn with_capacity(cap: usize, inner: R) -> Self { Self::with_buffer(Buffer::with_capacity(cap), inner) } /// Create a new `BufReader` wrapping `inner`, utilizing a ringbuffer with the default capacity /// and `ReaderPolicy`. /// /// A ringbuffer never has to move data to make room; consuming bytes from the head /// simultaneously makes room at the tail. This is useful in conjunction with a policy like /// [`MinBuffered`](policy::MinBuffered) to ensure there is always room to read more data /// if necessary, without expensive copying operations. /// /// Only available on platforms with virtual memory support and with the `slice-deque` feature /// enabled. The default capacity will differ between Windows and Unix-derivative targets. /// See [`Buffer::new_ringbuf()`](struct.Buffer.html#method.new_ringbuf) /// or [the crate root docs](index.html#ringbuffers--slice-deque-feature) for more info. #[cfg(feature = "slice-deque")] pub fn new_ringbuf(inner: R) -> Self { Self::with_capacity_ringbuf(DEFAULT_BUF_SIZE, inner) } /// Create a new `BufReader` wrapping `inner`, utilizing a ringbuffer with *at least* the given /// capacity and the default `ReaderPolicy`. /// /// A ringbuffer never has to move data to make room; consuming bytes from the head /// simultaneously makes room at the tail. This is useful in conjunction with a policy like /// [`MinBuffered`](policy::MinBuffered) to ensure there is always room to read more data /// if necessary, without expensive copying operations. /// /// Only available on platforms with virtual memory support and with the `slice-deque` feature /// enabled. The capacity will be rounded up to the minimum size for the target platform. /// See [`Buffer::with_capacity_ringbuf()`](struct.Buffer.html#method.with_capacity_ringbuf) /// or [the crate root docs](index.html#ringbuffers--slice-deque-feature) for more info. #[cfg(feature = "slice-deque")] pub fn with_capacity_ringbuf(cap: usize, inner: R) -> Self { Self::with_buffer(Buffer::with_capacity_ringbuf(cap), inner) } /// Wrap `inner` with an existing `Buffer` instance and the default `ReaderPolicy`. /// /// ### Note /// Does **not** clear the buffer first! If there is data already in the buffer /// then it will be returned in `read()` and `fill_buf()` ahead of any data from `inner`. pub fn with_buffer(buf: Buffer, inner: R) -> Self { BufReader { buf, inner, policy: StdPolicy, } } } impl BufReader { /// Apply a new `ReaderPolicy` to this `BufReader`, returning the transformed type. pub fn set_policy(self, policy: P_) -> BufReader { BufReader { inner: self.inner, buf: self.buf, policy, } } /// Mutate the current [`ReaderPolicy`](policy::ReaderPolicy) in-place. /// /// If you want to change the type, use `.set_policy()`. pub fn policy_mut(&mut self) -> &mut P { &mut self.policy } /// Inspect the current `ReaderPolicy`. pub fn policy(&self) -> &P { &self.policy } /// Move data to the start of the buffer, making room at the end for more /// reading. /// /// This is a no-op with the `*_ringbuf()` constructors (requires `slice-deque` feature). pub fn make_room(&mut self) { self.buf.make_room(); } /// Ensure room in the buffer for *at least* `additional` bytes. May not be /// quite exact due to implementation details of the buffer's allocator. pub fn reserve(&mut self, additional: usize) { self.buf.reserve(additional); } // RFC: pub fn shrink(&mut self, new_len: usize) ? /// Get the section of the buffer containing valid data; may be empty. /// /// Call `.consume()` to remove bytes from the beginning of this section. #[inline] pub fn buffer(&self) -> &[u8] { self.buf.buf() } /// Get the current number of bytes available in the buffer. pub fn buf_len(&self) -> usize { self.buf.len() } /// Get the total buffer capacity. pub fn capacity(&self) -> usize { self.buf.capacity() } /// Get an immutable reference to the underlying reader. pub fn get_ref(&self) -> &R { &self.inner } /// Get a mutable reference to the underlying reader. /// /// ## Note /// Reading directly from the underlying reader is not recommended, as some /// data has likely already been moved into the buffer. pub fn get_mut(&mut self) -> &mut R { &mut self.inner } /// Consume `self` and return the inner reader only. pub fn into_inner(self) -> R { self.inner } /// Consume `self` and return both the underlying reader and the buffer. /// /// See also: `BufReader::unbuffer()` pub fn into_inner_with_buffer(self) -> (R, Buffer) { (self.inner, self.buf) } /// Consume `self` and return an adapter which implements `Read` and will /// empty the buffer before reading directly from the underlying reader. pub fn unbuffer(self) -> Unbuffer { Unbuffer { inner: self.inner, buf: Some(self.buf), } } } impl BufReader { #[inline] fn should_read(&mut self) -> bool { self.policy.before_read(&mut self.buf).0 } } impl BufReader { /// Unconditionally perform a read into the buffer. /// /// Does not invoke `ReaderPolicy` methods. /// /// If the read was successful, returns the number of bytes read. pub fn read_into_buf(&mut self) -> io::Result { self.buf.read_from(&mut self.inner) } /// Box the inner reader without losing data. pub fn boxed<'a>(self) -> BufReader, P> where R: 'a, { let inner: Box = Box::new(self.inner); BufReader { inner, buf: self.buf, policy: self.policy, } } } impl Read for BufReader { fn read(&mut self, out: &mut [u8]) -> io::Result { // If we don't have any buffered data and we're doing a read matching // or exceeding the internal buffer's capacity, bypass the buffer. if self.buf.is_empty() && out.len() >= self.buf.capacity() { return self.inner.read(out); } let nread = self.fill_buf()?.read(out)?; self.consume(nread); Ok(nread) } } impl BufRead for BufReader { fn fill_buf(&mut self) -> io::Result<&[u8]> { // If we've reached the end of our internal buffer then we need to fetch // some more data from the underlying reader. // This execution order is important; the policy may want to resize the buffer or move data // before reading into it. while self.should_read() && self.buf.usable_space() > 0 { if self.read_into_buf()? == 0 { break; }; } Ok(self.buffer()) } fn consume(&mut self, mut amt: usize) { amt = cmp::min(amt, self.buf_len()); self.buf.consume(amt); self.policy.after_consume(&mut self.buf, amt); } } impl fmt::Debug for BufReader { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fmt.debug_struct("buffer_redux::BufReader") .field("reader", &self.inner) .field("buf_len", &self.buf_len()) .field("capacity", &self.capacity()) .field("policy", &self.policy) .finish() } } impl Seek for BufReader { /// Seek to an ofPet, in bytes, in the underlying reader. /// /// The position used for seeking with `SeekFrom::Current(_)` is the /// position the underlying reader would be at if the `BufReader` had no /// internal buffer. /// /// Seeking always discards the internal buffer, even if the seek position /// would otherwise fall within it. This guarantees that calling /// `.unwrap()` immediately after a seek yields the underlying reader at /// the same position. /// /// See `std::io::Seek` for more details. /// /// Note: In the edge case where you're seeking with `SeekFrom::Current(n)` /// where `n` minus the internal buffer length underflows an `i64`, two /// seeks will be performed instead of one. If the second seek returns /// `Err`, the underlying reader will be left at the same position it would /// have if you seeked to `SeekFrom::Current(0)`. fn seek(&mut self, pos: SeekFrom) -> io::Result { let result: u64; if let SeekFrom::Current(n) = pos { let remainder = self.buf_len() as i64; // it should be safe to assume that remainder fits within an i64 as the alternative // means we managed to allocate 8 ebibytes and that's absurd. // But it's not out of the realm of possibility for some weird underlying reader to // support seeking by i64::min_value() so we need to handle underflow when subtracting // remainder. if let Some(offset) = n.checked_sub(remainder) { result = self.inner.seek(SeekFrom::Current(offset))?; } else { // seek backwards by our remainder, and then by the offset self.inner.seek(SeekFrom::Current(-remainder))?; self.buf.clear(); // empty the buffer result = self.inner.seek(SeekFrom::Current(n))?; } } else { // Seeking with Start/End doesn't care about our buffer length. result = self.inner.seek(pos)?; } self.buf.clear(); Ok(result) } } /// A drop-in replacement for `std::io::BufWriter` with more functionality. /// /// Original method names/signatures and implemented traits are left untouched, /// making replacement as simple as swapping the import of the type. /// /// By default this type implements the behavior of its `std` counterpart: it only flushes /// the buffer if an incoming write is larger than the remaining space. /// /// To change this type's behavior, change the policy with [`.set_policy()`] using a type /// from the [`policy` module] or your own implentation of [`WriterPolicy`]. /// /// Policies that perform alternating writes and flushes without completely emptying the buffer /// may benefit from using a ringbuffer via the [`new_ringbuf()`] and [`with_capacity_ringbuf()`] /// constructors. Ringbuffers are only available on supported platforms with the /// `slice-deque` feature and have some caveats; see [the docs at the crate root][ringbufs-root] /// for more details. /// /// [`.set_policy()`]: BufWriter::set_policy /// [`policy` module]: policy /// [`WriterPolicy`]: policy::WriterPolicy /// [`new_ringbuf()`]: BufWriter::new_ringbuf /// [`with_capacity_ringbuf()`]: BufWriter::with_capacity_ringbuf /// [ringbufs-root]: index.html#ringbuffers--slice-deque-feature pub struct BufWriter { buf: Buffer, inner: W, policy: P, panicked: bool, } impl BufWriter { /// Create a new `BufWriter` wrapping `inner` with the default buffer capacity and /// [`WriterPolicy`](policy::WriterPolicy). pub fn new(inner: W) -> Self { Self::with_buffer(Buffer::new(), inner) } /// Create a new `BufWriter` wrapping `inner`, utilizing a buffer with a capacity /// of *at least* `cap` bytes and the default [`WriterPolicy`](policy::WriterPolicy). /// /// The actual capacity of the buffer may vary based on implementation details of the global /// allocator. pub fn with_capacity(cap: usize, inner: W) -> Self { Self::with_buffer(Buffer::with_capacity(cap), inner) } /// Create a new `BufWriter` wrapping `inner`, utilizing a ringbuffer with the default /// capacity and [`WriterPolicy`](policy::WriterPolicy). /// /// A ringbuffer never has to move data to make room; consuming bytes from the head /// simultaneously makes room at the tail. This is useful in conjunction with a policy like /// [`FlushExact`](policy::FlushExact) to ensure there is always room to write more data if /// necessary, without expensive copying operations. /// /// Only available on platforms with virtual memory support and with the `slice-deque` feature /// enabled. The default capacity will differ between Windows and Unix-derivative targets. /// See [`Buffer::new_ringbuf()`](Buffer::new_ringbuf) /// or [the crate root docs](index.html#ringbuffers--slice-deque-feature) for more info. #[cfg(feature = "slice-deque")] pub fn new_ringbuf(inner: W) -> Self { Self::with_buffer(Buffer::new_ringbuf(), inner) } /// Create a new `BufWriter` wrapping `inner`, utilizing a ringbuffer with *at least* `cap` /// capacity and the default [`WriterPolicy`](policy::WriterPolicy). /// /// A ringbuffer never has to move data to make room; consuming bytes from the head /// simultaneously makes room at the tail. This is useful in conjunction with a policy like /// [`FlushExact`](policy::FlushExact) to ensure there is always room to write more data if /// necessary, without expensive copying operations. /// /// Only available on platforms with virtual memory support and with the `slice-deque` feature /// enabled. The capacity will be rounded up to the minimum size for the target platform. /// See [`Buffer::with_capacity_ringbuf()`](Buffer::with_capacity_ringbuf) /// or [the crate root docs](index.html#ringbuffers--slice-deque-feature) for more info. #[cfg(feature = "slice-deque")] pub fn with_capacity_ringbuf(cap: usize, inner: W) -> Self { Self::with_buffer(Buffer::with_capacity_ringbuf(cap), inner) } /// Create a new `BufWriter` wrapping `inner`, utilizing the existing [`Buffer`](Buffer) /// instance and the default [`WriterPolicy`](policy::WriterPolicy). /// /// ### Note /// Does **not** clear the buffer first! If there is data already in the buffer /// it will be written out on the next flush! pub fn with_buffer(buf: Buffer, inner: W) -> BufWriter { BufWriter { buf, inner, policy: StdPolicy, panicked: false, } } } impl BufWriter { /// Set a new [`WriterPolicy`](policy::WriterPolicy), returning the transformed type. pub fn set_policy(self, policy: P_) -> BufWriter { let panicked = self.panicked; let (inner, buf) = self.into_inner_(); BufWriter { inner, buf, policy, panicked, } } /// Mutate the current [`WriterPolicy`](policy::WriterPolicy). pub fn policy_mut(&mut self) -> &mut P { &mut self.policy } /// Inspect the current `WriterPolicy`. pub fn policy(&self) -> &P { &self.policy } /// Get a reference to the inner writer. pub fn get_ref(&self) -> &W { &self.inner } /// Get a mutable reference to the inner writer. /// /// ### Note /// If the buffer has not been flushed, writing directly to the inner type will cause /// data inconsistency. pub fn get_mut(&mut self) -> &mut W { &mut self.inner } /// Get the capacty of the inner buffer. pub fn capacity(&self) -> usize { self.buf.capacity() } /// Get the number of bytes currently in the buffer. pub fn buf_len(&self) -> usize { self.buf.len() } /// Reserve space in the buffer for at least `additional` bytes. May not be /// quite exact due to implementation details of the buffer's allocator. pub fn reserve(&mut self, additional: usize) { self.buf.reserve(additional); } /// Move data to the start of the buffer, making room at the end for more /// writing. /// /// This is a no-op with the `*_ringbuf()` constructors (requires `slice-deque` feature). pub fn make_room(&mut self) { self.buf.make_room(); } /// Consume `self` and return both the underlying writer and the buffer pub fn into_inner_with_buffer(self) -> (W, Buffer) { self.into_inner_() } // copy the fields out and forget `self` to avoid dropping twice fn into_inner_(self) -> (W, Buffer) { let s = ManuallyDrop::new(self); unsafe { // safe because we immediately forget `self` let inner = ptr::read(&s.inner); let buf = ptr::read(&s.buf); (inner, buf) } } fn flush_buf(&mut self, amt: usize) -> io::Result<()> { if amt == 0 || amt > self.buf.len() { return Ok(()); } self.panicked = true; let ret = self.buf.write_max(amt, &mut self.inner); self.panicked = false; ret } } impl BufWriter { /// Flush the buffer and unwrap, returning the inner writer on success, /// or a type wrapping `self` plus the error otherwise. pub fn into_inner(mut self) -> Result> { match self.flush() { Err(e) => Err(IntoInnerError(self, e)), Ok(()) => Ok(self.into_inner_().0), } } /// Flush the buffer and unwrap, returning the inner writer and /// any error encountered during flushing. pub fn into_inner_with_err(mut self) -> (W, Option) { let err = self.flush().err(); (self.into_inner_().0, err) } } impl Write for BufWriter { fn write(&mut self, buf: &[u8]) -> io::Result { let flush_amt = self.policy.before_write(&mut self.buf, buf.len()).0; self.flush_buf(flush_amt)?; let written = if self.buf.is_empty() && buf.len() >= self.buf.capacity() { self.panicked = true; let result = self.inner.write(buf); self.panicked = false; result? } else { self.buf.copy_from_slice(buf) }; let flush_amt = self.policy.after_write(&self.buf).0; let _ = self.flush_buf(flush_amt); Ok(written) } fn flush(&mut self) -> io::Result<()> { let flush_amt = self.buf.len(); self.flush_buf(flush_amt)?; self.inner.flush() } } impl Seek for BufWriter { /// Seek to the ofPet, in bytes, in the underlying writer. /// /// Seeking always writes out the internal buffer before seeking. fn seek(&mut self, pos: SeekFrom) -> io::Result { self.flush().and_then(|_| self.get_mut().seek(pos)) } } impl fmt::Debug for BufWriter { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_struct("buffer_redux::BufWriter") .field("writer", &self.inner) .field("capacity", &self.capacity()) .field("policy", &self.policy) .finish() } } /// Attempt to flush the buffer to the underlying writer. /// /// If an error occurs, the thread-local handler is invoked, if one was previously /// set by [`set_drop_err_handler`](set_drop_err_handler) for this thread. impl Drop for BufWriter { fn drop(&mut self) { if !self.panicked { // instead of ignoring a failed flush, call the handler let buf_len = self.buf.len(); if let Err(err) = self.flush_buf(buf_len) { DROP_ERR_HANDLER.with(|deh| (*deh.borrow())(&mut self.inner, &mut self.buf, err)); } } } } /// A drop-in replacement for `std::io::LineWriter` with more functionality. /// /// This is, in fact, only a thin wrapper around /// [`BufWriter`](BufWriter)``, which /// demonstrates the power of custom [`WriterPolicy`](policy::WriterPolicy) implementations. pub struct LineWriter(BufWriter); impl LineWriter { /// Wrap `inner` with the default buffer capacity. pub fn new(inner: W) -> Self { Self::with_buffer(Buffer::new(), inner) } /// Wrap `inner` with the given buffer capacity. pub fn with_capacity(cap: usize, inner: W) -> Self { Self::with_buffer(Buffer::with_capacity(cap), inner) } /// Wrap `inner` with the default buffer capacity using a ringbuffer. #[cfg(feature = "slice-deque")] pub fn new_ringbuf(inner: W) -> Self { Self::with_buffer(Buffer::new_ringbuf(), inner) } /// Wrap `inner` with the given buffer capacity using a ringbuffer. #[cfg(feature = "slice-deque")] pub fn with_capacity_ringbuf(cap: usize, inner: W) -> Self { Self::with_buffer(Buffer::with_capacity_ringbuf(cap), inner) } /// Wrap `inner` with an existing `Buffer` instance. /// /// ### Note /// Does **not** clear the buffer first! If there is data already in the buffer /// it will be written out on the next flush! pub fn with_buffer(buf: Buffer, inner: W) -> LineWriter { LineWriter(BufWriter::with_buffer(buf, inner).set_policy(FlushOnNewline)) } /// Get a reference to the inner writer. pub fn get_ref(&self) -> &W { self.0.get_ref() } /// Get a mutable reference to the inner writer. /// /// ### Note /// If the buffer has not been flushed, writing directly to the inner type will cause /// data inconsistency. pub fn get_mut(&mut self) -> &mut W { self.0.get_mut() } /// Get the capacity of the inner buffer. pub fn capacity(&self) -> usize { self.0.capacity() } /// Get the number of bytes currently in the buffer. pub fn buf_len(&self) -> usize { self.0.buf_len() } /// Ensure enough space in the buffer for *at least* `additional` bytes. May not be /// quite exact due to implementation details of the buffer's allocator. pub fn reserve(&mut self, additional: usize) { self.0.reserve(additional); } /// Flush the buffer and unwrap, returning the inner writer on success, /// or a type wrapping `self` plus the error otherwise. pub fn into_inner(self) -> Result> { self.0 .into_inner() .map_err(|IntoInnerError(inner, e)| IntoInnerError(LineWriter(inner), e)) } /// Flush the buffer and unwrap, returning the inner writer and /// any error encountered during flushing. pub fn into_inner_with_err(self) -> (W, Option) { self.0.into_inner_with_err() } /// Consume `self` and return both the underlying writer and the buffer. pub fn into_inner_with_buf(self) -> (W, Buffer) { self.0.into_inner_with_buffer() } } impl Write for LineWriter { fn write(&mut self, buf: &[u8]) -> io::Result { self.0.write(buf) } fn flush(&mut self) -> io::Result<()> { self.0.flush() } } impl fmt::Debug for LineWriter { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_struct("buffer_redux::LineWriter") .field("writer", self.get_ref()) .field("capacity", &self.capacity()) .finish() } } /// The error type for `BufWriter::into_inner()`, /// contains the `BufWriter` as well as the error that occurred. #[derive(Debug)] pub struct IntoInnerError(pub W, pub io::Error); impl IntoInnerError { /// Get the error pub fn error(&self) -> &io::Error { &self.1 } /// Take the writer. pub fn into_inner(self) -> W { self.0 } } impl From> for io::Error { fn from(val: IntoInnerError) -> Self { val.1 } } impl error::Error for IntoInnerError { fn cause(&self) -> Option<&dyn error::Error> { Some(&self.1) } } impl fmt::Display for IntoInnerError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.error().fmt(f) } } /// A deque-like datastructure for managing bytes. /// /// Supports interacting via I/O traits like `Read` and `Write`, and direct access. pub struct Buffer { buf: BufImpl, zeroed: usize, } impl Default for Buffer { fn default() -> Self { Self::with_capacity(DEFAULT_BUF_SIZE) } } impl Buffer { /// Create a new buffer with a default capacity. pub fn new() -> Self { Self::default() } /// Create a new buffer with *at least* the given capacity. /// /// If the global allocator returns extra capacity, `Buffer` will use all of it. pub fn with_capacity(cap: usize) -> Self { Buffer { buf: BufImpl::with_capacity(cap), zeroed: 0, } } /// Allocate a buffer with a default capacity that never needs to move data to make room /// (consuming from the head simultaneously makes more room at the tail). /// /// The default capacity varies based on the target platform: /// /// * Unix-derivative platforms; Linux, OS X, BSDs, etc: **8KiB** (the default buffer size for /// `std::io` buffered types) /// * Windows: **64KiB** because of legacy reasons, of course (see below) /// /// Only available on platforms with virtual memory support and with the `slice-deque` feature /// enabled. The current platforms that are supported/tested are listed /// [in the README for the `slice-deque` crate][slice-deque]. /// /// [slice-deque]: https://github.com/gnzlbg/slice_deque#platform-support #[cfg(feature = "slice-deque")] pub fn new_ringbuf() -> Self { Self::with_capacity_ringbuf(DEFAULT_BUF_SIZE) } /// Allocate a buffer with *at least* the given capacity that never needs to move data to /// make room (consuming from the head simultaneously makes more room at the tail). /// /// The capacity will be rounded up to the minimum size for the current target: /// /// * Unix-derivative platforms; Linux, OS X, BSDs, etc: the next multiple of the page size /// (typically 4KiB but can vary based on system configuration) /// * Windows: the next muliple of **64KiB**; see [this Microsoft dev blog post][Win-why-64k] /// for why it's 64KiB and not the page size (TL;DR: Alpha AXP needs it and it's applied on /// all targets for consistency/portability) /// /// [Win-why-64k]: https://blogs.msdn.microsoft.com/oldnewthing/20031008-00/?p=42223 /// /// Only available on platforms with virtual memory support and with the `slice-deque` feature /// enabled. The current platforms that are supported/tested are listed /// [in the README for the `slice-deque` crate][slice-deque]. /// /// [slice-deque]: https://github.com/gnzlbg/slice_deque#platform-support #[cfg(feature = "slice-deque")] pub fn with_capacity_ringbuf(cap: usize) -> Self { Buffer { buf: BufImpl::with_capacity_ringbuf(cap), zeroed: 0, } } /// Return `true` if this is a ringbuffer. pub fn is_ringbuf(&self) -> bool { self.buf.is_ringbuf() } /// Return the number of bytes currently in this buffer. /// /// Equivalent to `self.buf().len()`. pub fn len(&self) -> usize { self.buf.len() } /// Return the number of bytes that can be read into this buffer before it needs /// to grow or the data in the buffer needs to be moved. /// /// This may not constitute all free space in the buffer if bytes have been consumed /// from the head. Use `free_space()` to determine the total free space in the buffer. pub fn usable_space(&self) -> usize { self.buf.usable_space() } /// Returns the total amount of free space in the buffer, including bytes /// already consumed from the head. /// /// This will be greater than or equal to `usable_space()`. On supported platforms /// with the `slice-deque` feature enabled, it should be equal. pub fn free_space(&self) -> usize { self.capacity() - self.len() } /// Return the total capacity of this buffer. pub fn capacity(&self) -> usize { self.buf.capacity() } /// Returns `true` if there are no bytes in the buffer, false otherwise. pub fn is_empty(&self) -> bool { self.len() == 0 } /// Move bytes down in the buffer to maximize usable space. /// /// This is a no-op on supported platforms with the `slice-deque` feature enabled. pub fn make_room(&mut self) { self.buf.make_room(); } /// Ensure space for at least `additional` more bytes in the buffer. /// /// This is a no-op if `usable_space() >= additional`. Note that this will reallocate /// even if there is enough free space at the head of the buffer for `additional` bytes, /// because that free space is not at the tail where it can be read into. /// If you prefer copying data down in the buffer before attempting to reallocate you may wish /// to call `.make_room()` first. /// /// ### Panics /// If `self.capacity() + additional` overflows. pub fn reserve(&mut self, additional: usize) { // Returns `true` if we reallocated out-of-place and thus need to re-zero. if self.buf.reserve(additional) { self.zeroed = 0; } } /// Get an immutable slice of the available bytes in this buffer. /// /// Call `.consume()` to remove bytes from the beginning of this slice. #[inline] pub fn buf(&self) -> &[u8] { self.buf.buf() } /// Get a mutable slice representing the available bytes in this buffer. /// /// Call `.consume()` to remove bytes from the beginning of this slice. pub fn buf_mut(&mut self) -> &mut [u8] { self.buf.buf_mut() } /// Read from `rdr`, returning the number of bytes read or any errors. /// /// If there is no more room at the head of the buffer, this will return `Ok(0)`. /// /// ### Panics /// If the returned count from `rdr.read()` overflows the tail cursor of this buffer. pub fn read_from(&mut self, rdr: &mut R) -> io::Result { if self.usable_space() == 0 { return Ok(0); } let cap = self.capacity(); if self.zeroed < cap { unsafe { let buf = self.buf.write_buf(); // TODO: use MaybeUninit::fill once stabilized for el in buf { el.write(0); } } self.zeroed = cap; } let read = { let buf = unsafe { self.buf.write_buf() }; // SAFETY: everything upto `cap` was zeroed above // TODO: use MaybeUninit::slice_assume_init_mut once stabilized let buf = unsafe { &mut *(buf as *mut [MaybeUninit] as *mut [u8]) }; // TODO: use BorrowedCursor once stabilized rdr.read(buf)? }; unsafe { self.buf.bytes_written(read); } Ok(read) } /// Copy from `src` to the tail of this buffer. Returns the number of bytes copied. /// /// This will **not** grow the buffer if `src` is larger than `self.usable_space()`; instead, /// it will fill the usable space and return the number of bytes copied. If there is no usable /// space, this returns 0. pub fn copy_from_slice(&mut self, src: &[u8]) -> usize { let len = unsafe { let buf = self.buf.write_buf(); let len = cmp::min(buf.len(), src.len()); // TODO: use MaybeUninit::copy_from_slice once stabilized // SAFETY: &[T] and &[MaybeUninit] have the same layout let uninit_src: &[MaybeUninit] = std::mem::transmute(src); buf[..len].copy_from_slice(&uninit_src[..len]); len }; unsafe { self.buf.bytes_written(len); } len } /// Write bytes from this buffer to `wrt`. Returns the number of bytes written or any errors. /// /// If the buffer is empty, returns `Ok(0)`. /// /// ### Panics /// If the count returned by `wrt.write()` would cause the head cursor to overflow or pass /// the tail cursor if added to it. pub fn write_to(&mut self, wrt: &mut W) -> io::Result { if self.is_empty() { return Ok(0); } let written = wrt.write(self.buf())?; self.consume(written); Ok(written) } /// Write, at most, the given number of bytes from this buffer to `wrt`, continuing /// to write and ignoring interrupts until the number is reached or the buffer is empty. /// /// ### Panics /// If the count returned by `wrt.write()` would cause the head cursor to overflow or pass /// the tail cursor if added to it. pub fn write_max(&mut self, mut max: usize, wrt: &mut W) -> io::Result<()> { while !self.is_empty() && max > 0 { let len = cmp::min(self.len(), max); let n = match wrt.write(&self.buf()[..len]) { Ok(0) => { return Err(io::Error::new( io::ErrorKind::WriteZero, "Buffer::write_all() got zero-sized write", )) } Ok(n) => n, Err(ref e) if e.kind() == io::ErrorKind::Interrupted => continue, Err(e) => return Err(e), }; self.consume(n); max = max.saturating_sub(n); } Ok(()) } /// Write all bytes in this buffer to `wrt`, ignoring interrupts. Continues writing until /// the buffer is empty or an error is returned. /// /// ### Panics /// If `self.write_to(wrt)` panics. pub fn write_all(&mut self, wrt: &mut W) -> io::Result<()> { while !self.is_empty() { match self.write_to(wrt) { Ok(0) => { return Err(io::Error::new( io::ErrorKind::WriteZero, "Buffer::write_all() got zero-sized write", )) } Ok(_) => (), Err(ref e) if e.kind() == io::ErrorKind::Interrupted => (), Err(e) => return Err(e), } } Ok(()) } /// Copy bytes to `out` from this buffer, returning the number of bytes written. pub fn copy_to_slice(&mut self, out: &mut [u8]) -> usize { let len = { let buf = self.buf(); let len = cmp::min(buf.len(), out.len()); out[..len].copy_from_slice(&buf[..len]); len }; self.consume(len); len } /// Push `bytes` to the end of the buffer, growing it if necessary. /// /// If you prefer moving bytes down in the buffer to reallocating, you may wish to call /// `.make_room()` first. pub fn push_bytes(&mut self, bytes: &[u8]) { let s_len = bytes.len(); if self.usable_space() < s_len { self.reserve(s_len * 2); } unsafe { // TODO: use MaybeUninit::copy_from_slice once stabilized // SAFETY: &[T] and &[MaybeUninit] have the same layout let uninit_src: &[MaybeUninit] = std::mem::transmute(bytes); let buf = self.buf.write_buf(); buf[..s_len].copy_from_slice(uninit_src); self.buf.bytes_written(s_len); } } /// Consume `amt` bytes from the head of this buffer. pub fn consume(&mut self, amt: usize) { self.buf.consume(amt); } /// Empty this buffer by consuming all bytes. pub fn clear(&mut self) { let buf_len = self.len(); self.consume(buf_len); } } impl fmt::Debug for Buffer { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_struct("buffer_redux::Buffer") .field("capacity", &self.capacity()) .field("len", &self.len()) .finish() } } /// A `Read` adapter for a consumed `BufReader` which will empty bytes from the buffer before /// reading from `R` directly. Frees the buffer when it has been emptied. pub struct Unbuffer { inner: R, buf: Option, } impl Unbuffer { /// Returns `true` if the buffer still has some bytes left, `false` otherwise. pub fn is_buf_empty(&self) -> bool { self.buf.is_none() } /// Returns the number of bytes remaining in the buffer. pub fn buf_len(&self) -> usize { self.buf.as_ref().map(Buffer::len).unwrap_or(0) } /// Get a slice over the available bytes in the buffer. #[inline] pub fn buf(&self) -> &[u8] { self.buf.as_ref().map_or(&[], Buffer::buf) } /// Return the underlying reader, releasing the buffer. pub fn into_inner(self) -> R { self.inner } } impl Read for Unbuffer { fn read(&mut self, out: &mut [u8]) -> io::Result { if let Some(ref mut buf) = self.buf.as_mut() { let read = buf.copy_to_slice(out); if !out.is_empty() && read != 0 { return Ok(read); } } self.buf = None; self.inner.read(out) } } impl fmt::Debug for Unbuffer { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fmt.debug_struct("buffer_redux::Unbuffer") .field("reader", &self.inner) .field("buffer", &self.buf) .finish() } } /// Copy data between a `BufRead` and a `Write` without an intermediate buffer. /// /// Retries on interrupts. Returns the total bytes copied or the first error; /// even if an error is returned some bytes may still have been copied. pub fn copy_buf(b: &mut B, w: &mut W) -> io::Result { let mut total_copied = 0; loop { let copied = match b.fill_buf().and_then(|buf| w.write(buf)) { Err(ref e) if e.kind() == io::ErrorKind::Interrupted => continue, Err(e) => return Err(e), Ok(buf) => buf, }; if copied == 0 { break; } b.consume(copied); total_copied += copied as u64; } Ok(total_copied) } type DropHandler = Box; thread_local!( static DROP_ERR_HANDLER: RefCell = RefCell::new(Box::new(|_, _, _| ())) ); /// Set a thread-local handler for errors thrown in `BufWriter`'s `Drop` impl. /// /// The `Write` impl, buffer (at the time of the erroring write) and IO error are provided. /// /// Replaces the previous handler. By default this is a no-op. /// /// ### Panics /// If called from within a handler previously provided to this function. pub fn set_drop_err_handler(handler: F) where F: 'static + Fn(&mut dyn Write, &mut Buffer, io::Error), { DROP_ERR_HANDLER.with(|deh| *deh.borrow_mut() = Box::new(handler)) } buffer-redux-1.0.2/src/policy.rs000064400000000000000000000332161046102023000146630ustar 00000000000000//! Types which can be used to tune the behavior of `BufReader` and `BufWriter`. //! //! Some simple policies are provided for your convenience. You may prefer to create your own //! types and implement the traits for them instead. use super::Buffer; /// Flag for `ReaderPolicy` methods to signal whether or not `BufReader` should read into /// the buffer. /// /// See `do_read!()` for a shorthand. #[derive(Copy, Clone, Debug)] pub struct DoRead(pub bool); /// Shorthand for `return DoRead(bool)` or `return DoRead(true)` (empty invocation) #[macro_export] macro_rules! do_read ( ($val:expr) => ( return $crate::policy::DoRead($val) ); () => ( do_read!(true); ) ); /// Default policy for both `BufReader` and `BufWriter` that reproduces the behaviors of their /// `std::io` counterparts: /// /// * `BufReader`: only reads when the buffer is empty, does not resize or move data. /// * `BufWriter`: only flushes the buffer when there is not enough room for an incoming write. #[derive(Debug, Default)] pub struct StdPolicy; /// Trait that governs `BufReader`'s behavior. pub trait ReaderPolicy { /// Consulted before attempting to read into the buffer. /// /// Return `DoRead(true)` to issue a read into the buffer before reading data out of it, /// or `DoRead(false)` to read from the buffer as it is, even if it's empty. /// `do_read!()` is provided as a shorthand. /// /// If there is no room in the buffer after this method is called, /// the buffer will not be read into (so if the buffer is full but you want more data /// you should call `.make_room()` or reserve more space). If there *is* room, `BufReader` will /// attempt to read into the buffer. If successful (`Ok(x)` where `x > 0` is returned), this /// method will be consulted again for another read attempt. /// /// By default, this implements `std::io::BufReader`'s behavior: only read into the buffer if /// it is empty. /// /// ### Note /// If the read will ignore the buffer entirely (if the buffer is empty and the amount to be /// read matches or exceeds its capacity) or if `BufReader::read_into_buf()` was called to force /// a read into the buffer manually, this method will not be called. fn before_read(&mut self, buffer: &mut Buffer) -> DoRead { DoRead(buffer.is_empty()) } /// Called after bytes are consumed from the buffer. /// /// Supplies the true amount consumed if the amount passed to `BufReader::consume` /// was in excess. /// /// This is a no-op by default. fn after_consume(&mut self, _buffer: &mut Buffer, _amt: usize) {} } /// Behavior of `std::io::BufReader`: the buffer will only be read into if it is empty. impl ReaderPolicy for StdPolicy {} /// A policy for [`BufReader`](::BufReader) which ensures there is at least the given number of /// bytes in the buffer, failing this only if the reader is at EOF. /// /// If the minimum buffer length is greater than the buffer capacity, it will be resized. /// /// ### Example /// ```rust /// use buffer_redux::BufReader; /// use buffer_redux::policy::MinBuffered; /// use std::io::{BufRead, Cursor}; /// /// let data = (1 .. 16).collect::>(); /// /// // normally you should use `BufReader::new()` or give a capacity of several KiB or more /// let mut reader = BufReader::with_capacity(8, Cursor::new(data)) /// // always at least 4 bytes in the buffer (or until the source is empty) /// .set_policy(MinBuffered(4)); // always at least 4 bytes in the buffer /// /// // first buffer fill, same as `std::io::BufReader` /// assert_eq!(reader.fill_buf().unwrap(), &[1, 2, 3, 4, 5, 6, 7, 8]); /// reader.consume(3); /// /// // enough data in the buffer, another read isn't done yet /// assert_eq!(reader.fill_buf().unwrap(), &[4, 5, 6, 7, 8]); /// reader.consume(4); /// /// // `std::io::BufReader` would return `&[8]` /// assert_eq!(reader.fill_buf().unwrap(), &[8, 9, 10, 11, 12, 13, 14, 15]); /// reader.consume(5); /// /// // no data left in the reader /// assert_eq!(reader.fill_buf().unwrap(), &[13, 14, 15]); /// ``` #[derive(Debug)] pub struct MinBuffered(pub usize); impl MinBuffered { /// Set the number of bytes to ensure are in the buffer. pub fn set_min(&mut self, min: usize) { self.0 = min; } } impl ReaderPolicy for MinBuffered { fn before_read(&mut self, buffer: &mut Buffer) -> DoRead { // do nothing if we have enough data if buffer.len() >= self.0 { do_read!(false) } let cap = buffer.capacity(); // if there's enough room but some of it's stuck after the head if buffer.usable_space() < self.0 && buffer.free_space() >= self.0 { buffer.make_room(); } else if cap < self.0 { buffer.reserve(self.0 - cap); } DoRead(true) } } /// Flag for `WriterPolicy` methods to tell `BufWriter` how many bytes to flush to the /// underlying reader. /// /// See `flush_amt!()` for a shorthand. #[derive(Copy, Clone, Debug)] pub struct FlushAmt(pub usize); /// Shorthand for `return FlushAmt(n)` or `return FlushAmt(0)` (empty invocation) #[macro_export] macro_rules! flush_amt ( ($n:expr) => ( return $crate::policy::FlushAmt($n); ); () => ( flush_amt!(0); ) ); /// A trait which tells `BufWriter` when to flush. pub trait WriterPolicy { /// Return `FlushAmt(n > 0)` if the buffer should be flushed before reading into it. /// If the returned amount is 0 or greater than the amount of buffered data, no flush is /// performed. /// /// The buffer is provided, as well as `incoming` which is /// the size of the buffer that will be written to the `BufWriter`. /// /// By default, flushes the buffer if the usable space is smaller than the incoming write. fn before_write(&mut self, buf: &mut Buffer, incoming: usize) -> FlushAmt { FlushAmt(if incoming > buf.usable_space() { buf.len() } else { 0 }) } /// Return `true` if the buffer should be flushed after reading into it. /// /// `buf` references the updated buffer after the read. /// /// Default impl is a no-op. fn after_write(&mut self, _buf: &Buffer) -> FlushAmt { FlushAmt(0) } } /// Default behavior of `std::io::BufWriter`: flush before a read into the buffer /// only if the incoming data is larger than the buffer's writable space. impl WriterPolicy for StdPolicy {} /// Flush the buffer if it contains at least the given number of bytes. #[derive(Debug, Default)] pub struct FlushAtLeast(pub usize); impl WriterPolicy for FlushAtLeast { fn before_write(&mut self, buf: &mut Buffer, incoming: usize) -> FlushAmt { ensure_capacity(buf, self.0); FlushAmt(if incoming > buf.usable_space() { buf.len() } else { 0 }) } fn after_write(&mut self, buf: &Buffer) -> FlushAmt { FlushAmt(::std::cmp::max(buf.len(), self.0)) } } /// Only ever flush exactly the given number of bytes, until the writer is empty. #[derive(Debug, Default)] pub struct FlushExact(pub usize); impl WriterPolicy for FlushExact { /// Flushes the buffer if there is not enough room to fit `incoming` bytes, /// but only when the buffer contains at least `self.0` bytes. /// /// Otherwise, calls [`Buffer::make_room()`](::Buffer::make_room) fn before_write(&mut self, buf: &mut Buffer, incoming: usize) -> FlushAmt { ensure_capacity(buf, self.0); // don't have enough room to fit the additional bytes but we can't flush, // then make room for (at least some of) the incoming bytes. if incoming > buf.usable_space() && buf.len() < self.0 { buf.make_room(); } FlushAmt(self.0) } /// Flushes the given amount if possible, nothing otherwise. fn after_write(&mut self, _buf: &Buffer) -> FlushAmt { FlushAmt(self.0) } } /// Flush the buffer if it contains the given byte. /// /// Only scans the buffer after reading. Searches from the end first. #[derive(Debug, Default)] pub struct FlushOn(pub u8); impl WriterPolicy for FlushOn { fn after_write(&mut self, buf: &Buffer) -> FlushAmt { // include the delimiter in the flush FlushAmt(memchr::memrchr(self.0, buf.buf()).map_or(0, |n| n + 1)) } } /// Flush the buffer if it contains a newline (`\n`). /// /// Equivalent to `FlushOn(b'\n')`. #[derive(Debug, Default)] pub struct FlushOnNewline; impl WriterPolicy for FlushOnNewline { fn after_write(&mut self, buf: &Buffer) -> FlushAmt { FlushAmt(memchr::memrchr(b'\n', buf.buf()).map_or(0, |n| n + 1)) } } fn ensure_capacity(buf: &mut Buffer, min_cap: usize) { let cap = buf.capacity(); if cap < min_cap { buf.reserve(min_cap - cap); } } #[cfg(test)] mod test { use crate::policy::*; use crate::{BufReader, BufWriter}; use std::io::{BufRead, Cursor, Write}; #[test] fn test_min_buffered() { let min_buffered = 4; let data = (0..20).collect::>(); // create a reader with 0 capacity let mut reader = BufReader::with_capacity(0, Cursor::new(data)).set_policy(MinBuffered(min_buffered)); // policy reserves the required space in the buffer assert_eq!(reader.fill_buf().unwrap(), &[0, 1, 2, 3][..]); assert_eq!(reader.capacity(), min_buffered); // double the size now that the buffer's full reader.reserve(min_buffered); assert_eq!(reader.capacity(), min_buffered * 2); // we haven't consumed anything, the reader should have the same data assert_eq!(reader.fill_buf().unwrap(), &[0, 1, 2, 3]); reader.consume(2); // policy read more data, `std::io::BufReader` doesn't do that assert_eq!(reader.fill_buf().unwrap(), &[2, 3, 4, 5, 6, 7]); reader.consume(4); // policy made room and read more assert_eq!(reader.fill_buf().unwrap(), &[6, 7, 8, 9, 10, 11, 12, 13]); reader.consume(4); assert_eq!(reader.fill_buf().unwrap(), &[10, 11, 12, 13]); reader.consume(2); assert_eq!( reader.fill_buf().unwrap(), &[12, 13, 14, 15, 16, 17, 18, 19] ); reader.consume(8); assert_eq!(reader.fill_buf().unwrap(), &[]) } #[test] fn test_flush_at_least() { let flush_min = 4; let mut writer = BufWriter::with_capacity(0, vec![]).set_policy(FlushAtLeast(flush_min)); assert_eq!(writer.capacity(), 0); assert_eq!(writer.write(&[1]).unwrap(), 1); // policy reserved space for writing assert_eq!(writer.capacity(), flush_min); // one byte in buffer, we want to double our capacity writer.reserve(flush_min * 2 - 1); assert_eq!(writer.capacity(), flush_min * 2); assert_eq!(writer.write(&[2, 3]).unwrap(), 2); // no flush yet, only 3 bytes in buffer assert_eq!(*writer.get_ref(), &[]); assert_eq!(writer.write(&[4, 5, 6]).unwrap(), 3); // flushed all assert_eq!(*writer.get_ref(), &[1, 2, 3, 4, 5, 6]); assert_eq!(writer.write(&[7, 8, 9]).unwrap(), 3); // `.into_inner()` should flush always assert_eq!(writer.into_inner().unwrap(), &[1, 2, 3, 4, 5, 6, 7, 8, 9]); } #[test] fn test_flush_exact() { let flush_exact = 4; let mut writer = BufWriter::with_capacity(0, vec![]).set_policy(FlushExact(flush_exact)); assert_eq!(writer.capacity(), 0); assert_eq!(writer.write(&[1]).unwrap(), 1); // policy reserved space for writing assert_eq!(writer.capacity(), flush_exact); // one byte in buffer, we want to double our capacity writer.reserve(flush_exact * 2 - 1); assert_eq!(writer.capacity(), flush_exact * 2); assert_eq!(writer.write(&[2, 3]).unwrap(), 2); // no flush yet, only 3 bytes in buffer assert_eq!(*writer.get_ref(), &[]); assert_eq!(writer.write(&[4, 5, 6]).unwrap(), 3); // flushed exactly 4 bytes assert_eq!(*writer.get_ref(), &[1, 2, 3, 4]); assert_eq!(writer.write(&[7, 8, 9, 10]).unwrap(), 4); // flushed another 4 bytes assert_eq!(*writer.get_ref(), &[1, 2, 3, 4, 5, 6, 7, 8]); // `.into_inner()` should flush always assert_eq!( writer.into_inner().unwrap(), &[1, 2, 3, 4, 5, 6, 7, 8, 9, 10] ); } #[test] fn test_flush_on() { let mut writer = BufWriter::with_capacity(8, vec![]).set_policy(FlushOn(0)); assert_eq!(writer.write(&[1, 2, 3]).unwrap(), 3); assert_eq!(*writer.get_ref(), &[]); assert_eq!(writer.write(&[0, 4, 5]).unwrap(), 3); assert_eq!(*writer.get_ref(), &[1, 2, 3, 0]); assert_eq!(writer.write(&[6, 7, 8, 9, 10, 11, 12]).unwrap(), 7); assert_eq!(*writer.get_ref(), &[1, 2, 3, 0, 4, 5]); assert_eq!(writer.write(&[0]).unwrap(), 1); assert_eq!( *writer.get_ref(), &[1, 2, 3, 0, 4, 5, 6, 7, 8, 9, 10, 11, 12, 0] ); } #[test] fn test_flush_on_newline() { let mut writer = BufWriter::with_capacity(8, vec![]).set_policy(FlushOnNewline); assert_eq!(writer.write(&[1, 2, 3]).unwrap(), 3); assert_eq!(*writer.get_ref(), &[]); assert_eq!(writer.write(&[b'\n', 4, 5]).unwrap(), 3); assert_eq!(*writer.get_ref(), &[1, 2, 3, b'\n']); assert_eq!(writer.write(&[6, 7, 8, 9, b'\n', 11, 12]).unwrap(), 7); assert_eq!( *writer.get_ref(), &[1, 2, 3, b'\n', 4, 5, 6, 7, 8, 9, b'\n'] ); assert_eq!(writer.write(&[b'\n']).unwrap(), 1); assert_eq!( *writer.get_ref(), &[1, 2, 3, b'\n', 4, 5, 6, 7, 8, 9, b'\n', 11, 12, b'\n'] ); } } buffer-redux-1.0.2/src/ringbuf_tests.rs000064400000000000000000000205041046102023000162360ustar 00000000000000// Original implementation Copyright 2013 The Rust Project Developers // Original source file: https://github.com/rust-lang/rust/blob/master/src/libstd/io/buffered.rs // Modifications copyright 2018 Austin Bonander //! Tests checking `Buffer::new_ringbuf()` and friends. //! //! Some may be adapted from rust/src/libstd/io/buffered.rs //! //! Since `SliceDeque` rounds allocations up to the page size or larger, these cannot assume //! a small capacity like `std_test` does. // TODO: add tests centered around the mirrored buf boundary use std::io::prelude::*; use std::io::{self, SeekFrom}; use crate::{BufReader, Buffer, DEFAULT_BUF_SIZE}; use crate::std_tests::ShortReader; macro_rules! assert_capacity { ($buf:expr, $cap:expr) => { let cap = $buf.capacity(); if cfg!(target_os = "windows") { // Windows' minimum allocation size is 64K assert_eq!(cap, ::std::cmp::max(64 * 1024, $cap)); } else if cfg!(target_os = "macos") { // Macos' minimum allocation size is sometimes? 16K assert!(cap == $cap || cap == ::std::cmp::max(16 * 1024, $cap)); } else { assert_eq!(cap, $cap); } }; } #[test] fn test_buffer_new() { let buf = Buffer::new_ringbuf(); assert_capacity!(buf, DEFAULT_BUF_SIZE); assert_eq!(buf.capacity(), buf.usable_space()); } #[test] fn test_buffer_with_cap() { let buf = Buffer::with_capacity_ringbuf(4 * 1024); assert_capacity!(buf, 4 * 1024); // test rounding up to page size let buf = Buffer::with_capacity_ringbuf(64); assert_capacity!(buf, 4 * 1024); assert_eq!(buf.capacity(), buf.usable_space()); } #[test] fn test_buffered_reader() { let inner: &[u8] = &[5, 6, 7, 0, 1, 2, 3, 4]; let mut reader = BufReader::new_ringbuf(inner); let mut buf = [0, 0, 0]; let nread = reader.read(&mut buf); assert_eq!(nread.unwrap(), 3); let b: &[_] = &[5, 6, 7]; assert_eq!(buf, b); let mut buf = [0, 0]; let nread = reader.read(&mut buf); assert_eq!(nread.unwrap(), 2); let b: &[_] = &[0, 1]; assert_eq!(buf, b); let mut buf = [0]; let nread = reader.read(&mut buf); assert_eq!(nread.unwrap(), 1); let b: &[_] = &[2]; assert_eq!(buf, b); let mut buf = [0, 0, 0]; let nread = reader.read(&mut buf); assert_eq!(nread.unwrap(), 2); let b: &[_] = &[3, 4, 0]; assert_eq!(buf, b); assert_eq!(reader.read(&mut buf).unwrap(), 0); } #[test] fn test_buffered_reader_seek() { let inner: &[u8] = &[5, 6, 7, 0, 1, 2, 3, 4]; let mut reader = BufReader::new_ringbuf(io::Cursor::new(inner)); assert_eq!(reader.seek(SeekFrom::Start(3)).ok(), Some(3)); assert_eq!(reader.fill_buf().ok(), Some(&[0, 1, 2, 3, 4][..])); assert_eq!(reader.stream_position().ok(), Some(3)); assert_eq!(reader.fill_buf().ok(), Some(&[0, 1, 2, 3, 4][..])); assert_eq!(reader.seek(SeekFrom::Current(1)).ok(), Some(4)); assert_eq!(reader.fill_buf().ok(), Some(&[1, 2, 3, 4][..])); reader.consume(1); assert_eq!(reader.seek(SeekFrom::Current(-2)).ok(), Some(3)); assert_eq!(reader.fill_buf().ok(), Some(&[0, 1, 2, 3, 4][..])); } #[test] fn test_buffered_reader_seek_underflow() { // gimmick reader that yields its position modulo 256 for each byte struct PositionReader { pos: u64, } impl Read for PositionReader { fn read(&mut self, buf: &mut [u8]) -> io::Result { let len = buf.len(); for x in buf { *x = self.pos as u8; self.pos = self.pos.wrapping_add(1); } Ok(len) } } impl Seek for PositionReader { fn seek(&mut self, pos: SeekFrom) -> io::Result { match pos { SeekFrom::Start(n) => { self.pos = n; } SeekFrom::Current(n) => { self.pos = self.pos.wrapping_add(n as u64); } SeekFrom::End(n) => { self.pos = u64::MAX.wrapping_add(n as u64); } } Ok(self.pos) } } let mut reader = BufReader::with_capacity(5, PositionReader { pos: 0 }); assert_eq!(reader.fill_buf().ok(), Some(&[0, 1, 2, 3, 4][..])); assert_eq!(reader.seek(SeekFrom::End(-5)).ok(), Some(u64::MAX - 5)); assert_eq!(reader.fill_buf().ok().map(|s| s.len()), Some(5)); // the following seek will require two underlying seeks let expected = 9223372036854775802; assert_eq!( reader.seek(SeekFrom::Current(i64::MIN)).ok(), Some(expected) ); assert_eq!(reader.fill_buf().ok().map(|s| s.len()), Some(5)); // seeking to 0 should empty the buffer. assert_eq!(reader.stream_position().ok(), Some(expected)); assert_eq!(reader.get_ref().pos, expected); } #[test] fn test_read_until() { let inner: &[u8] = &[0, 1, 2, 1, 0]; let mut reader = BufReader::with_capacity(2, inner); let mut v = Vec::new(); reader.read_until(0, &mut v).unwrap(); assert_eq!(v, [0]); v.truncate(0); reader.read_until(2, &mut v).unwrap(); assert_eq!(v, [1, 2]); v.truncate(0); reader.read_until(1, &mut v).unwrap(); assert_eq!(v, [1]); v.truncate(0); reader.read_until(8, &mut v).unwrap(); assert_eq!(v, [0]); v.truncate(0); reader.read_until(9, &mut v).unwrap(); assert_eq!(v, []); } #[test] fn test_read_line() { let in_buf: &[u8] = b"a\nb\nc"; let mut reader = BufReader::with_capacity(2, in_buf); let mut s = String::new(); reader.read_line(&mut s).unwrap(); assert_eq!(s, "a\n"); s.truncate(0); reader.read_line(&mut s).unwrap(); assert_eq!(s, "b\n"); s.truncate(0); reader.read_line(&mut s).unwrap(); assert_eq!(s, "c"); s.truncate(0); reader.read_line(&mut s).unwrap(); assert_eq!(s, ""); } #[test] fn test_lines() { let in_buf: &[u8] = b"a\nb\nc"; let reader = BufReader::with_capacity(2, in_buf); let mut it = reader.lines(); assert_eq!(it.next().unwrap().unwrap(), "a".to_string()); assert_eq!(it.next().unwrap().unwrap(), "b".to_string()); assert_eq!(it.next().unwrap().unwrap(), "c".to_string()); assert!(it.next().is_none()); } #[test] fn test_short_reads() { let inner = ShortReader { lengths: vec![0, 1, 2, 0, 1, 0], }; let mut reader = BufReader::new(inner); let mut buf = [0, 0]; assert_eq!(reader.read(&mut buf).unwrap(), 0); assert_eq!(reader.read(&mut buf).unwrap(), 1); assert_eq!(reader.read(&mut buf).unwrap(), 2); assert_eq!(reader.read(&mut buf).unwrap(), 0); assert_eq!(reader.read(&mut buf).unwrap(), 1); assert_eq!(reader.read(&mut buf).unwrap(), 0); assert_eq!(reader.read(&mut buf).unwrap(), 0); } /// Test that the ringbuffer wraps as intended #[test] fn test_mirror_boundary() { // pretends the given bytes have been read struct FakeReader(usize); impl Read for FakeReader { fn read(&mut self, _buf: &mut [u8]) -> io::Result { Ok(self.0) } } let mut buffer = Buffer::new_ringbuf(); let cap = buffer.capacity(); // declaring these as variables for sanity let read_amt = cap; // fill the buffer let test_slice = &[1, 2, 3, 4, 5]; let consume_amt = read_amt - 5; // leave several bytes on the head side of the mirror assert_eq!( buffer.read_from(&mut FakeReader(read_amt)).unwrap(), read_amt ); assert_eq!(buffer.usable_space(), cap - read_amt); // should be 0 assert_eq!(buffer.read_from(&mut FakeReader(read_amt)).unwrap(), 0); // buffer is full buffer.consume(consume_amt); assert_eq!(buffer.usable_space(), consume_amt); assert_eq!(buffer.copy_from_slice(test_slice), test_slice.len()); // zeroes are the bytes we didn't consume assert_eq!(buffer.buf(), &[0, 0, 0, 0, 0, 1, 2, 3, 4, 5]); buffer.clear(); assert_eq!(buffer.usable_space(), cap); } #[test] fn issue_8() { let source = vec![0u8; 4096 * 4]; let mut rdr = BufReader::with_capacity_ringbuf(4096, source.as_slice()); loop { let n = rdr.read_into_buf().unwrap(); if n == 0 { break; } rdr.consume(4000); // rdr.make_room(); // (only necessary with 'standard' reader) println!("{n}"); } } // `BufWriter` doesn't utilize a ringbuffer buffer-redux-1.0.2/src/std_tests.rs000064400000000000000000000215351046102023000154010ustar 00000000000000// Original implementation Copyright 2013 The Rust Project Developers // Original source file: https://github.com/rust-lang/rust/blob/master/src/libstd/io/buffered.rs // Modifications copyright 2016-2018 Austin Bonander //! These tests are copied from rust/src/libstd/io/buffered.rs //! They assume exact capacity allocation use crate::{BufReader, BufWriter, LineWriter}; use std::io::prelude::*; use std::io::{self, SeekFrom}; /// A dummy reader intended at testing short-reads propagation. pub struct ShortReader { pub lengths: Vec, } impl Read for ShortReader { fn read(&mut self, _: &mut [u8]) -> io::Result { if self.lengths.is_empty() { Ok(0) } else { Ok(self.lengths.remove(0)) } } } #[test] fn test_buffered_reader() { let inner: &[u8] = &[5, 6, 7, 0, 1, 2, 3, 4]; let mut reader = BufReader::with_capacity(2, inner); let mut buf = [0, 0, 0]; let nread = reader.read(&mut buf); assert_eq!(nread.unwrap(), 3); let b: &[_] = &[5, 6, 7]; assert_eq!(buf, b); let mut buf = [0, 0]; let nread = reader.read(&mut buf); assert_eq!(nread.unwrap(), 2); let b: &[_] = &[0, 1]; assert_eq!(buf, b); let mut buf = [0]; let nread = reader.read(&mut buf); assert_eq!(nread.unwrap(), 1); let b: &[_] = &[2]; assert_eq!(buf, b); let mut buf = [0, 0, 0]; let nread = reader.read(&mut buf); assert_eq!(nread.unwrap(), 1); let b: &[_] = &[3, 0, 0]; assert_eq!(buf, b); let nread = reader.read(&mut buf); assert_eq!(nread.unwrap(), 1); let b: &[_] = &[4, 0, 0]; assert_eq!(buf, b); assert_eq!(reader.read(&mut buf).unwrap(), 0); } #[test] fn test_buffered_reader_seek() { let inner: &[u8] = &[5, 6, 7, 0, 1, 2, 3, 4]; let mut reader = BufReader::with_capacity(2, io::Cursor::new(inner)); assert_eq!(reader.seek(SeekFrom::Start(3)).ok(), Some(3)); assert_eq!(reader.fill_buf().ok(), Some(&[0, 1][..])); assert_eq!(reader.stream_position().ok(), Some(3)); assert_eq!(reader.fill_buf().ok(), Some(&[0, 1][..])); assert_eq!(reader.seek(SeekFrom::Current(1)).ok(), Some(4)); assert_eq!(reader.fill_buf().ok(), Some(&[1, 2][..])); reader.consume(1); assert_eq!(reader.seek(SeekFrom::Current(-2)).ok(), Some(3)); } #[test] fn test_buffered_reader_seek_underflow() { // gimmick reader that yields its position modulo 256 for each byte struct PositionReader { pos: u64, } impl Read for PositionReader { fn read(&mut self, buf: &mut [u8]) -> io::Result { let len = buf.len(); for x in buf { *x = self.pos as u8; self.pos = self.pos.wrapping_add(1); } Ok(len) } } impl Seek for PositionReader { fn seek(&mut self, pos: SeekFrom) -> io::Result { match pos { SeekFrom::Start(n) => { self.pos = n; } SeekFrom::Current(n) => { self.pos = self.pos.wrapping_add(n as u64); } SeekFrom::End(n) => { self.pos = u64::MAX.wrapping_add(n as u64); } } Ok(self.pos) } } let mut reader = BufReader::with_capacity(5, PositionReader { pos: 0 }); assert_eq!(reader.fill_buf().ok(), Some(&[0, 1, 2, 3, 4][..])); assert_eq!(reader.seek(SeekFrom::End(-5)).ok(), Some(u64::MAX - 5)); assert_eq!(reader.fill_buf().ok().map(|s| s.len()), Some(5)); // the following seek will require two underlying seeks let expected = 9223372036854775802; assert_eq!( reader.seek(SeekFrom::Current(i64::MIN)).ok(), Some(expected) ); assert_eq!(reader.fill_buf().ok().map(|s| s.len()), Some(5)); // seeking to 0 should empty the buffer. assert_eq!(reader.stream_position().ok(), Some(expected)); assert_eq!(reader.get_ref().pos, expected); } #[test] fn test_read_until() { let inner: &[u8] = &[0, 1, 2, 1, 0]; let mut reader = BufReader::with_capacity(2, inner); let mut v = Vec::new(); reader.read_until(0, &mut v).unwrap(); assert_eq!(v, [0]); v.truncate(0); reader.read_until(2, &mut v).unwrap(); assert_eq!(v, [1, 2]); v.truncate(0); reader.read_until(1, &mut v).unwrap(); assert_eq!(v, [1]); v.truncate(0); reader.read_until(8, &mut v).unwrap(); assert_eq!(v, [0]); v.truncate(0); reader.read_until(9, &mut v).unwrap(); assert_eq!(v, []); } #[test] fn test_read_line() { let in_buf: &[u8] = b"a\nb\nc"; let mut reader = BufReader::with_capacity(2, in_buf); let mut s = String::new(); reader.read_line(&mut s).unwrap(); assert_eq!(s, "a\n"); s.truncate(0); reader.read_line(&mut s).unwrap(); assert_eq!(s, "b\n"); s.truncate(0); reader.read_line(&mut s).unwrap(); assert_eq!(s, "c"); s.truncate(0); reader.read_line(&mut s).unwrap(); assert_eq!(s, ""); } #[test] fn test_lines() { let in_buf: &[u8] = b"a\nb\nc"; let reader = BufReader::with_capacity(2, in_buf); let mut it = reader.lines(); assert_eq!(it.next().unwrap().unwrap(), "a".to_string()); assert_eq!(it.next().unwrap().unwrap(), "b".to_string()); assert_eq!(it.next().unwrap().unwrap(), "c".to_string()); assert!(it.next().is_none()); } #[test] fn test_short_reads() { let inner = ShortReader { lengths: vec![0, 1, 2, 0, 1, 0], }; let mut reader = BufReader::new(inner); let mut buf = [0, 0]; assert_eq!(reader.read(&mut buf).unwrap(), 0); assert_eq!(reader.read(&mut buf).unwrap(), 1); assert_eq!(reader.read(&mut buf).unwrap(), 2); assert_eq!(reader.read(&mut buf).unwrap(), 0); assert_eq!(reader.read(&mut buf).unwrap(), 1); assert_eq!(reader.read(&mut buf).unwrap(), 0); assert_eq!(reader.read(&mut buf).unwrap(), 0); } // BufWriter tests #[test] fn test_buffered_writer() { let inner = Vec::new(); let mut writer = BufWriter::with_capacity(2, inner); assert_eq!(writer.capacity(), 2); writer.write_all(&[0, 1]).unwrap(); assert_eq!(*writer.get_ref(), [0, 1]); writer.write_all(&[2]).unwrap(); assert_eq!(*writer.get_ref(), [0, 1]); writer.write_all(&[3]).unwrap(); assert_eq!(*writer.get_ref(), [0, 1]); writer.flush().unwrap(); assert_eq!(*writer.get_ref(), [0, 1, 2, 3]); writer.write_all(&[4]).unwrap(); writer.write_all(&[5]).unwrap(); assert_eq!(*writer.get_ref(), [0, 1, 2, 3]); writer.write_all(&[6]).unwrap(); assert_eq!(*writer.get_ref(), [0, 1, 2, 3, 4, 5]); writer.write_all(&[7, 8]).unwrap(); assert_eq!(*writer.get_ref(), [0, 1, 2, 3, 4, 5, 6, 7, 8]); writer.write_all(&[9, 10, 11]).unwrap(); assert_eq!(*writer.get_ref(), [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]); writer.flush().unwrap(); assert_eq!(*writer.get_ref(), [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]); } #[test] fn test_buffered_writer_inner_flushes() { let mut w = BufWriter::with_capacity(3, Vec::new()); w.write_all(&[0, 1]).unwrap(); assert_eq!(*w.get_ref(), []); let w = w.into_inner().unwrap(); assert_eq!(w, [0, 1]); } #[test] fn test_buffered_writer_seek() { let mut w = BufWriter::with_capacity(3, io::Cursor::new(Vec::new())); w.write_all(&[0, 1, 2, 3, 4, 5]).unwrap(); w.write_all(&[6, 7]).unwrap(); assert_eq!(w.stream_position().ok(), Some(8)); assert_eq!(&w.get_ref().get_ref()[..], &[0, 1, 2, 3, 4, 5, 6, 7][..]); assert_eq!(w.seek(SeekFrom::Start(2)).ok(), Some(2)); w.write_all(&[8, 9]).unwrap(); assert_eq!( &w.into_inner().unwrap().into_inner()[..], &[0, 1, 8, 9, 4, 5, 6, 7] ); } #[test] fn test_line_buffer() { let mut writer = LineWriter::new(Vec::new()); writer.write_all(&[0]).unwrap(); assert_eq!(*writer.get_ref(), []); writer.write_all(&[1]).unwrap(); assert_eq!(*writer.get_ref(), []); writer.flush().unwrap(); assert_eq!(*writer.get_ref(), [0, 1]); writer.write_all(&[0, b'\n', 1, b'\n', 2]).unwrap(); assert_eq!(*writer.get_ref(), [0, 1, 0, b'\n', 1, b'\n']); writer.flush().unwrap(); assert_eq!(*writer.get_ref(), [0, 1, 0, b'\n', 1, b'\n', 2]); writer.write_all(&[3, b'\n']).unwrap(); assert_eq!(*writer.get_ref(), [0, 1, 0, b'\n', 1, b'\n', 2, 3, b'\n']); } #[test] fn test_buf_writer_drops_once() { struct CountDrops(usize); impl Write for CountDrops { fn write(&mut self, _buf: &[u8]) -> io::Result { unimplemented!() } fn flush(&mut self) -> io::Result<()> { unimplemented!() } } impl Drop for CountDrops { fn drop(&mut self) { assert_eq!(self.0, 0); self.0 += 1; } } let writer = BufWriter::new(CountDrops(0)); let (_, _) = writer.into_inner_with_buffer(); }