Struct Buffer

Source
pub struct Buffer { /* private fields */ }
Expand description

A Buffer is a variable-sized buffer of bytes with read and write methods.

Implementations§

Source§

impl Buffer

Source

pub fn new() -> Self

Examples found in repository?
examples/zlib-writer.rs (line 8)
7fn main() {
8    let mut b = bytes::Buffer::new();
9    let mut w = zlib::Writer::new(&mut b);
10    w.write("hello, world\n".as_bytes()).unwrap();
11    w.close().unwrap();
12    println!("{:?}", b.bytes());
13    // Output: [120 156 202 72 205 201 201 215 81 40 207 47 202 73 225 2 4 0 0 255 255 33 231 4 147]
14}
More examples
Hide additional examples
examples/bytesbuffer.rs (line 9)
8fn main() {
9    let mut buf = Buffer::new();
10    buf.write_all("hello world".as_bytes()).unwrap();
11    println!("{}", buf.string());
12
13    let mut buf = Buffer::new();
14    buf.write_byte(33).unwrap();
15    buf.write_all("hello world".as_bytes()).unwrap();
16    println!("{}", buf.read_byte().unwrap());
17    println!("{}", buf.string());
18}
examples/flate.rs (line 11)
9fn main() {
10    let msg = "Hello World! Hello Rust! Hello World! Hello Rust!";
11    let mut buffer = bytes::Buffer::new();
12    let mut w = flate::Writer::new(&mut buffer, flate::BEST_COMPRESSION).unwrap();
13    w.write_all(msg.as_bytes()).unwrap();
14    w.close().unwrap();
15
16    let result_str = hex::encode_to_string(buffer.bytes());
17    println!(
18        "input string    ({:02} bytes): {}",
19        msg.as_bytes().len(),
20        msg,
21    );
22    println!(
23        "deflated string ({:02} bytes): {}",
24        result_str.len() / 2,
25        result_str
26    );
27}
examples/flate-speed.rs (line 16)
11fn main() {
12    let mut file = File::open("src/testdata/Isaac.Newton-Opticks.txt").unwrap();
13    let mut content = Vec::new();
14    file.read_to_end(&mut content).unwrap();
15
16    let mut buffer = bytes::Buffer::new();
17    let mut w = flate::Writer::new(&mut buffer, flate::BEST_COMPRESSION).unwrap();
18
19    let repeats = 200;
20    for _i in 0..repeats {
21        w.write_all(&content).unwrap();
22    }
23
24    w.close().unwrap();
25
26    let compressed_data = bytes::Buffer::bytes(&buffer);
27    let hash = sha256::sum256(compressed_data);
28    let hash_str = hex::encode_to_string(&hash);
29    println!("compressed data hash:");
30    println!("{}", hash_str);
31}
examples/flate-dict.rs (line 35)
16fn example_dictionary() {
17    // The dictionary is a string of bytes. When compressing some input data,
18    // the compressor will attempt to substitute substrings with matches found
19    // in the dictionary. As such, the dictionary should only contain substrings
20    // that are expected to be found in the actual data stream.
21    let dict = b"<?xml version=\"1.0\"?><book><data><meta name=\"\" content=\"";
22
23    // The data to compress should (but is not required to) contain frequent
24    // substrings that match those in the dictionary.
25    let data = r#"<?xml version="1.0"?>
26<book>
27    <meta name="title" content="The Go Programming Language"/>
28    <meta name="authors" content="Alan Donovan and Brian Kernighan"/>
29    <meta name="published" content="2015-10-26"/>
30    <meta name="isbn" content="978-0134190440"/>
31    <data>...</data>
32</book>
33"#;
34
35    let mut b = bytes::Buffer::new();
36
37    // Compress the data using the specially crafted dictionary.
38    {
39        let mut zw = flate::Writer::new_dict(&mut b, flate::DEFAULT_COMPRESSION, dict).unwrap();
40        let mut data_reader = bytes::new_buffer_string(data);
41        std::io::copy(&mut data_reader, &mut zw).unwrap();
42        zw.close().unwrap();
43    }
44
45    // The decompressor must use the same dictionary as the compressor.
46    // Otherwise, the input may appear as corrupted.
47    println!("Decompressed output using the dictionary:");
48    {
49        let mut data_reader = b.bytes();
50        let mut zr = flate::Reader::new_dict(&mut data_reader, dict);
51        let mut decompressed = bytes::Buffer::new();
52        std::io::copy(&mut zr, &mut decompressed).unwrap();
53        zr.close().unwrap();
54        println!("{}", String::from_utf8_lossy(decompressed.bytes()));
55        println!();
56    }
57
58    // Substitute all of the bytes in the dictionary with a '#' to visually
59    // demonstrate the approximate effectiveness of using a preset dictionary.
60    println!("Substrings matched by the dictionary are marked with #:");
61    {
62        let hash_dict = vec![b'#'; dict.len()];
63        let mut zr = flate::Reader::new_dict(&mut b, &hash_dict);
64        let mut decompressed = bytes::Buffer::new();
65        std::io::copy(&mut zr, &mut decompressed).unwrap();
66        zr.close().unwrap();
67        println!("{}", String::from_utf8_lossy(decompressed.bytes()));
68    }
69
70    // Output:
71    // Decompressed output using the dictionary:
72    // <?xml version="1.0"?>
73    // <book>
74    // 	<meta name="title" content="The Go Programming Language"/>
75    // 	<meta name="authors" content="Alan Donovan and Brian Kernighan"/>
76    // 	<meta name="published" content="2015-10-26"/>
77    // 	<meta name="isbn" content="978-0134190440"/>
78    // 	<data>...</data>
79    // </book>
80    //
81    // Substrings matched by the dictionary are marked with #:
82    // #####################
83    // ######
84    // 	############title###########The Go Programming Language"/#
85    // 	############authors###########Alan Donovan and Brian Kernighan"/#
86    // 	############published###########2015-10-26"/#
87    // 	############isbn###########978-0134190440"/#
88    // 	######...</#####
89    // </#####
90}
Source

pub fn bytes(&self) -> &[u8]

bytes returns a slice of length b.len() holding the unread portion of the buffer. The slice is valid for use only until the next buffer modification (that is, only until the next call to a method like Read, Write, Reset, or Truncate). The slice aliases the buffer content at least until the next buffer modification, so immediate changes to the slice will affect the result of future reads.

Examples found in repository?
examples/zlib-writer.rs (line 12)
7fn main() {
8    let mut b = bytes::Buffer::new();
9    let mut w = zlib::Writer::new(&mut b);
10    w.write("hello, world\n".as_bytes()).unwrap();
11    w.close().unwrap();
12    println!("{:?}", b.bytes());
13    // Output: [120 156 202 72 205 201 201 215 81 40 207 47 202 73 225 2 4 0 0 255 255 33 231 4 147]
14}
More examples
Hide additional examples
examples/flate.rs (line 16)
9fn main() {
10    let msg = "Hello World! Hello Rust! Hello World! Hello Rust!";
11    let mut buffer = bytes::Buffer::new();
12    let mut w = flate::Writer::new(&mut buffer, flate::BEST_COMPRESSION).unwrap();
13    w.write_all(msg.as_bytes()).unwrap();
14    w.close().unwrap();
15
16    let result_str = hex::encode_to_string(buffer.bytes());
17    println!(
18        "input string    ({:02} bytes): {}",
19        msg.as_bytes().len(),
20        msg,
21    );
22    println!(
23        "deflated string ({:02} bytes): {}",
24        result_str.len() / 2,
25        result_str
26    );
27}
examples/flate-speed.rs (line 26)
11fn main() {
12    let mut file = File::open("src/testdata/Isaac.Newton-Opticks.txt").unwrap();
13    let mut content = Vec::new();
14    file.read_to_end(&mut content).unwrap();
15
16    let mut buffer = bytes::Buffer::new();
17    let mut w = flate::Writer::new(&mut buffer, flate::BEST_COMPRESSION).unwrap();
18
19    let repeats = 200;
20    for _i in 0..repeats {
21        w.write_all(&content).unwrap();
22    }
23
24    w.close().unwrap();
25
26    let compressed_data = bytes::Buffer::bytes(&buffer);
27    let hash = sha256::sum256(compressed_data);
28    let hash_str = hex::encode_to_string(&hash);
29    println!("compressed data hash:");
30    println!("{}", hash_str);
31}
examples/flate-dict.rs (line 49)
16fn example_dictionary() {
17    // The dictionary is a string of bytes. When compressing some input data,
18    // the compressor will attempt to substitute substrings with matches found
19    // in the dictionary. As such, the dictionary should only contain substrings
20    // that are expected to be found in the actual data stream.
21    let dict = b"<?xml version=\"1.0\"?><book><data><meta name=\"\" content=\"";
22
23    // The data to compress should (but is not required to) contain frequent
24    // substrings that match those in the dictionary.
25    let data = r#"<?xml version="1.0"?>
26<book>
27    <meta name="title" content="The Go Programming Language"/>
28    <meta name="authors" content="Alan Donovan and Brian Kernighan"/>
29    <meta name="published" content="2015-10-26"/>
30    <meta name="isbn" content="978-0134190440"/>
31    <data>...</data>
32</book>
33"#;
34
35    let mut b = bytes::Buffer::new();
36
37    // Compress the data using the specially crafted dictionary.
38    {
39        let mut zw = flate::Writer::new_dict(&mut b, flate::DEFAULT_COMPRESSION, dict).unwrap();
40        let mut data_reader = bytes::new_buffer_string(data);
41        std::io::copy(&mut data_reader, &mut zw).unwrap();
42        zw.close().unwrap();
43    }
44
45    // The decompressor must use the same dictionary as the compressor.
46    // Otherwise, the input may appear as corrupted.
47    println!("Decompressed output using the dictionary:");
48    {
49        let mut data_reader = b.bytes();
50        let mut zr = flate::Reader::new_dict(&mut data_reader, dict);
51        let mut decompressed = bytes::Buffer::new();
52        std::io::copy(&mut zr, &mut decompressed).unwrap();
53        zr.close().unwrap();
54        println!("{}", String::from_utf8_lossy(decompressed.bytes()));
55        println!();
56    }
57
58    // Substitute all of the bytes in the dictionary with a '#' to visually
59    // demonstrate the approximate effectiveness of using a preset dictionary.
60    println!("Substrings matched by the dictionary are marked with #:");
61    {
62        let hash_dict = vec![b'#'; dict.len()];
63        let mut zr = flate::Reader::new_dict(&mut b, &hash_dict);
64        let mut decompressed = bytes::Buffer::new();
65        std::io::copy(&mut zr, &mut decompressed).unwrap();
66        zr.close().unwrap();
67        println!("{}", String::from_utf8_lossy(decompressed.bytes()));
68    }
69
70    // Output:
71    // Decompressed output using the dictionary:
72    // <?xml version="1.0"?>
73    // <book>
74    // 	<meta name="title" content="The Go Programming Language"/>
75    // 	<meta name="authors" content="Alan Donovan and Brian Kernighan"/>
76    // 	<meta name="published" content="2015-10-26"/>
77    // 	<meta name="isbn" content="978-0134190440"/>
78    // 	<data>...</data>
79    // </book>
80    //
81    // Substrings matched by the dictionary are marked with #:
82    // #####################
83    // ######
84    // 	############title###########The Go Programming Language"/#
85    // 	############authors###########Alan Donovan and Brian Kernighan"/#
86    // 	############published###########2015-10-26"/#
87    // 	############isbn###########978-0134190440"/#
88    // 	######...</#####
89    // </#####
90}
Source

pub fn string(&self) -> String

string returns the contents of the unread portion of the buffer as a string.

Examples found in repository?
examples/bytesbuffer.rs (line 11)
8fn main() {
9    let mut buf = Buffer::new();
10    buf.write_all("hello world".as_bytes()).unwrap();
11    println!("{}", buf.string());
12
13    let mut buf = Buffer::new();
14    buf.write_byte(33).unwrap();
15    buf.write_all("hello world".as_bytes()).unwrap();
16    println!("{}", buf.read_byte().unwrap());
17    println!("{}", buf.string());
18}
Source

pub fn len(&self) -> usize

len returns the number of bytes of the unread portion of the buffer; b.Len() == len(b.bytes()).

Source

pub fn is_empty(&self) -> bool

Source

pub fn cap(&self) -> usize

cap returns the capacity of the buffer’s underlying byte slice, that is, the total space allocated for the buffer’s data.

Source

pub fn truncate(&mut self, n: usize)

Source

pub fn reset(&mut self)

reset resets the buffer to be empty, but it retains the underlying storage for use by future writes. Reset is the same as Truncate(0).

Source

pub fn grow(&mut self, n: usize)

grow grows the buffer’s capacity, if necessary, to guarantee space for another n bytes. After Grow(n), at least n bytes can be written to the buffer without another allocation.

Source§

impl Buffer

Source

pub fn write_string(&mut self, s: &str) -> Result<usize>

write_string appends the contents of s to the buffer, growing the buffer as needed. The return value n is the length of s.

Source

pub fn write_byte(&mut self, c: u8) -> Result<()>

write_byte appends the byte c to the buffer, growing the buffer as needed.

Examples found in repository?
examples/bytesbuffer.rs (line 14)
8fn main() {
9    let mut buf = Buffer::new();
10    buf.write_all("hello world".as_bytes()).unwrap();
11    println!("{}", buf.string());
12
13    let mut buf = Buffer::new();
14    buf.write_byte(33).unwrap();
15    buf.write_all("hello world".as_bytes()).unwrap();
16    println!("{}", buf.read_byte().unwrap());
17    println!("{}", buf.string());
18}
Source

pub fn read_byte(&mut self) -> Option<u8>

read_byte reads and returns the next byte from the buffer. If no byte is available, it returns None.

Examples found in repository?
examples/bytesbuffer.rs (line 16)
8fn main() {
9    let mut buf = Buffer::new();
10    buf.write_all("hello world".as_bytes()).unwrap();
11    println!("{}", buf.string());
12
13    let mut buf = Buffer::new();
14    buf.write_byte(33).unwrap();
15    buf.write_all("hello world".as_bytes()).unwrap();
16    println!("{}", buf.read_byte().unwrap());
17    println!("{}", buf.string());
18}

Trait Implementations§

Source§

impl BufRead for Buffer

Source§

fn fill_buf(&mut self) -> Result<&[u8]>

Returns the contents of the internal buffer, filling it with more data, via Read methods, if empty. Read more
Source§

fn consume(&mut self, amt: usize)

Marks the given amount of additional bytes from the internal buffer as having been read. Subsequent calls to read only return bytes that have not been marked as read. Read more
Source§

fn has_data_left(&mut self) -> Result<bool, Error>

🔬This is a nightly-only experimental API. (buf_read_has_data_left)
Checks if there is any data left to be read. Read more
1.0.0 · Source§

fn read_until(&mut self, byte: u8, buf: &mut Vec<u8>) -> Result<usize, Error>

Reads all bytes into buf until the delimiter byte or EOF is reached. Read more
1.83.0 · Source§

fn skip_until(&mut self, byte: u8) -> Result<usize, Error>

Skips all bytes until the delimiter byte or EOF is reached. Read more
1.0.0 · Source§

fn read_line(&mut self, buf: &mut String) -> Result<usize, Error>

Reads all bytes until a newline (the 0xA byte) is reached, and append them to the provided String buffer. Read more
1.0.0 · Source§

fn split(self, byte: u8) -> Split<Self>
where Self: Sized,

Returns an iterator over the contents of this reader split on the byte byte. Read more
1.0.0 · Source§

fn lines(self) -> Lines<Self>
where Self: Sized,

Returns an iterator over the lines of this reader. Read more
Source§

impl Default for Buffer

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl Read for Buffer

Source§

fn read(&mut self, p: &mut [u8]) -> Result<usize>

Read reads the next p.len() bytes from the buffer or until the buffer is drained. The return value n is the number of bytes read.

1.36.0 · Source§

fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize, Error>

Like read, except that it reads into a slice of buffers. Read more
Source§

fn is_read_vectored(&self) -> bool

🔬This is a nightly-only experimental API. (can_vector)
Determines if this Reader has an efficient read_vectored implementation. Read more
1.0.0 · Source§

fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize, Error>

Reads all bytes until EOF in this source, placing them into buf. Read more
1.0.0 · Source§

fn read_to_string(&mut self, buf: &mut String) -> Result<usize, Error>

Reads all bytes until EOF in this source, appending them to buf. Read more
1.6.0 · Source§

fn read_exact(&mut self, buf: &mut [u8]) -> Result<(), Error>

Reads the exact number of bytes required to fill buf. Read more
Source§

fn read_buf(&mut self, buf: BorrowedCursor<'_>) -> Result<(), Error>

🔬This is a nightly-only experimental API. (read_buf)
Pull some bytes from this source into the specified buffer. Read more
Source§

fn read_buf_exact(&mut self, cursor: BorrowedCursor<'_>) -> Result<(), Error>

🔬This is a nightly-only experimental API. (read_buf)
Reads the exact number of bytes required to fill cursor. Read more
1.0.0 · Source§

fn by_ref(&mut self) -> &mut Self
where Self: Sized,

Creates a “by reference” adaptor for this instance of Read. Read more
1.0.0 · Source§

fn bytes(self) -> Bytes<Self>
where Self: Sized,

Transforms this Read instance to an Iterator over its bytes. Read more
1.0.0 · Source§

fn chain<R>(self, next: R) -> Chain<Self, R>
where R: Read, Self: Sized,

Creates an adapter which will chain this stream with another. Read more
1.0.0 · Source§

fn take(self, limit: u64) -> Take<Self>
where Self: Sized,

Creates an adapter which will read at most limit bytes from it. Read more
Source§

impl Write for Buffer

Source§

fn write(&mut self, p: &[u8]) -> Result<usize>

write appends the contents of p to the buffer, growing the buffer as needed. The return value n is the length of p.

Source§

fn flush(&mut self) -> Result<()>

Flushes this output stream, ensuring that all intermediately buffered contents reach their destination. Read more
1.36.0 · Source§

fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> Result<usize, Error>

Like write, except that it writes from a slice of buffers. Read more
Source§

fn is_write_vectored(&self) -> bool

🔬This is a nightly-only experimental API. (can_vector)
Determines if this Writer has an efficient write_vectored implementation. Read more
1.0.0 · Source§

fn write_all(&mut self, buf: &[u8]) -> Result<(), Error>

Attempts to write an entire buffer into this writer. Read more
Source§

fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> Result<(), Error>

🔬This is a nightly-only experimental API. (write_all_vectored)
Attempts to write multiple buffers into this writer. Read more
1.0.0 · Source§

fn write_fmt(&mut self, args: Arguments<'_>) -> Result<(), Error>

Writes a formatted string into this writer, returning any error encountered. Read more
1.0.0 · Source§

fn by_ref(&mut self) -> &mut Self
where Self: Sized,

Creates a “by reference” adapter for this instance of Write. Read more

Auto Trait Implementations§

§

impl Freeze for Buffer

§

impl RefUnwindSafe for Buffer

§

impl Send for Buffer

§

impl Sync for Buffer

§

impl Unpin for Buffer

§

impl UnwindSafe for Buffer

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.