Skip to content

Commit c9290dc

Browse files
committed
Auto merge of #68558 - HeroicKatora:buf-writer-capacity, r=alexcrichton
Add a method to query the capacity of a BufWriter and BufReader Besides the obvious of retrieving the parameter used to construct the writer, this method allows consumers to control the number of `flush` calls during write operations. For `BufReader` it gives an upper bound on the returned buffer in `fill_buf` which might influence the allocation behaviour of a consumer.
2 parents 5b0caef + aebd0d7 commit c9290dc

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

src/libstd/io/buffered.rs

+45
Original file line numberDiff line numberDiff line change
@@ -179,6 +179,30 @@ impl<R> BufReader<R> {
179179
&self.buf[self.pos..self.cap]
180180
}
181181

182+
/// Returns the number of bytes the internal buffer can hold at once.
183+
///
184+
/// # Examples
185+
///
186+
/// ```no_run
187+
/// #![feature(buffered_io_capacity)]
188+
/// use std::io::{BufReader, BufRead};
189+
/// use std::fs::File;
190+
///
191+
/// fn main() -> std::io::Result<()> {
192+
/// let f = File::open("log.txt")?;
193+
/// let mut reader = BufReader::new(f);
194+
///
195+
/// let capacity = reader.capacity();
196+
/// let buffer = reader.fill_buf()?;
197+
/// assert!(buffer.len() <= capacity);
198+
/// Ok(())
199+
/// }
200+
/// ```
201+
#[unstable(feature = "buffered_io_capacity", issue = "68558")]
202+
pub fn capacity(&self) -> usize {
203+
self.buf.len()
204+
}
205+
182206
/// Unwraps this `BufReader<R>`, returning the underlying reader.
183207
///
184208
/// Note that any leftover data in the internal buffer is lost. Therefore,
@@ -576,6 +600,27 @@ impl<W: Write> BufWriter<W> {
576600
&self.buf
577601
}
578602

603+
/// Returns the number of bytes the internal buffer can hold without flushing.
604+
///
605+
/// # Examples
606+
///
607+
/// ```no_run
608+
/// #![feature(buffered_io_capacity)]
609+
/// use std::io::BufWriter;
610+
/// use std::net::TcpStream;
611+
///
612+
/// let buf_writer = BufWriter::new(TcpStream::connect("127.0.0.1:34254").unwrap());
613+
///
614+
/// // Check the capacity of the inner buffer
615+
/// let capacity = buf_writer.capacity();
616+
/// // Calculate how many bytes can be written without flushing
617+
/// let without_flush = capacity - buf_writer.buffer().len();
618+
/// ```
619+
#[unstable(feature = "buffered_io_capacity", issue = "68558")]
620+
pub fn capacity(&self) -> usize {
621+
self.buf.capacity()
622+
}
623+
579624
/// Unwraps this `BufWriter<W>`, returning the underlying writer.
580625
///
581626
/// The buffer is written out before returning the writer.

0 commit comments

Comments
 (0)