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
impl Buffer
Sourcepub fn new() -> Self
pub fn new() -> Self
Examples found in repository?
More examples
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}
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}
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}
Sourcepub fn bytes(&self) -> &[u8] ⓘ
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?
More examples
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}
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}
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}
Sourcepub fn string(&self) -> String
pub fn string(&self) -> String
string returns the contents of the unread portion of the buffer as a string.
Sourcepub fn len(&self) -> usize
pub fn len(&self) -> usize
len returns the number of bytes of the unread portion of the buffer; b.Len() == len(b.bytes()).
pub fn is_empty(&self) -> bool
Sourcepub fn cap(&self) -> usize
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.
pub fn truncate(&mut self, n: usize)
Source§impl Buffer
impl Buffer
Sourcepub fn write_string(&mut self, s: &str) -> Result<usize>
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.
Sourcepub fn write_byte(&mut self, c: u8) -> Result<()>
pub fn write_byte(&mut self, c: u8) -> Result<()>
write_byte appends the byte c to the buffer, growing the buffer as needed.
Trait Implementations§
Source§impl BufRead for Buffer
impl BufRead for Buffer
Source§fn fill_buf(&mut self) -> Result<&[u8]>
fn fill_buf(&mut self) -> Result<&[u8]>
Read
methods, if empty. Read moreSource§fn consume(&mut self, amt: usize)
fn consume(&mut self, amt: usize)
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 moreSource§fn has_data_left(&mut self) -> Result<bool, Error>
fn has_data_left(&mut self) -> Result<bool, Error>
buf_read_has_data_left
)read
. Read more1.83.0 · Source§fn skip_until(&mut self, byte: u8) -> Result<usize, Error>
fn skip_until(&mut self, byte: u8) -> Result<usize, Error>
byte
or EOF is reached. Read more1.0.0 · Source§fn read_line(&mut self, buf: &mut String) -> Result<usize, Error>
fn read_line(&mut self, buf: &mut String) -> Result<usize, Error>
0xA
byte) is reached, and append
them to the provided String
buffer. Read moreSource§impl Read for Buffer
impl Read for Buffer
Source§fn read(&mut self, p: &mut [u8]) -> Result<usize>
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>
fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize, Error>
read
, except that it reads into a slice of buffers. Read moreSource§fn is_read_vectored(&self) -> bool
fn is_read_vectored(&self) -> bool
can_vector
)1.0.0 · Source§fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize, Error>
fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize, Error>
buf
. Read more1.0.0 · Source§fn read_to_string(&mut self, buf: &mut String) -> Result<usize, Error>
fn read_to_string(&mut self, buf: &mut String) -> Result<usize, Error>
buf
. Read more1.6.0 · Source§fn read_exact(&mut self, buf: &mut [u8]) -> Result<(), Error>
fn read_exact(&mut self, buf: &mut [u8]) -> Result<(), Error>
buf
. Read moreSource§fn read_buf(&mut self, buf: BorrowedCursor<'_>) -> Result<(), Error>
fn read_buf(&mut self, buf: BorrowedCursor<'_>) -> Result<(), Error>
read_buf
)Source§fn read_buf_exact(&mut self, cursor: BorrowedCursor<'_>) -> Result<(), Error>
fn read_buf_exact(&mut self, cursor: BorrowedCursor<'_>) -> Result<(), Error>
read_buf
)cursor
. Read more1.0.0 · Source§fn by_ref(&mut self) -> &mut Selfwhere
Self: Sized,
fn by_ref(&mut self) -> &mut Selfwhere
Self: Sized,
Read
. Read moreSource§impl Write for Buffer
impl Write for Buffer
Source§fn write(&mut self, p: &[u8]) -> Result<usize>
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<()>
fn flush(&mut self) -> Result<()>
Source§fn is_write_vectored(&self) -> bool
fn is_write_vectored(&self) -> bool
can_vector
)1.0.0 · Source§fn write_all(&mut self, buf: &[u8]) -> Result<(), Error>
fn write_all(&mut self, buf: &[u8]) -> Result<(), Error>
Source§fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> Result<(), Error>
fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> Result<(), Error>
write_all_vectored
)