Skip to content

Commit 811f47b

Browse files
Clean up the read portion of the buffer
1 parent b628031 commit 811f47b

1 file changed

Lines changed: 11 additions & 3 deletions

File tree

src/buffer.rs

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -45,20 +45,26 @@ impl<const CHUNK_SIZE: usize> ReadBuffer<CHUNK_SIZE> {
4545
pub fn into_vec(mut self) -> Vec<u8> {
4646
// Current implementation of `tungstenite-rs` expects that the `into_vec()` drains
4747
// the data from the container that has already been read by the cursor.
48-
let pos = self.storage.position() as usize;
49-
self.storage.get_mut().drain(0..pos).count();
50-
self.storage.set_position(0);
48+
self.clean_up();
5149

5250
// Now we can safely return the internal container.
5351
self.storage.into_inner()
5452
}
5553

5654
/// Read next portion of data from the given input stream.
5755
pub fn read_from<S: Read>(&mut self, stream: &mut S) -> IoResult<usize> {
56+
self.clean_up();
5857
let size = stream.read(&mut self.chunk)?;
5958
self.storage.get_mut().extend_from_slice(&self.chunk[..size]);
6059
Ok(size)
6160
}
61+
62+
/// Cleans ups the part of the vector that has been already read by the cursor.
63+
fn clean_up(&mut self) {
64+
let pos = self.storage.position() as usize;
65+
self.storage.get_mut().drain(0..pos).count();
66+
self.storage.set_position(0);
67+
}
6268
}
6369

6470
impl<const CHUNK_SIZE: usize> Buf for ReadBuffer<CHUNK_SIZE> {
@@ -99,10 +105,12 @@ mod tests {
99105

100106
buf.advance(2);
101107
assert_eq!(buf.chunk(), b"ll");
108+
assert_eq!(buf.storage.get_mut(), b"Hell");
102109

103110
let size = buf.read_from(&mut inp).unwrap();
104111
assert_eq!(size, 4);
105112
assert_eq!(buf.chunk(), b"llo Wo");
113+
assert_eq!(buf.storage.get_mut(), b"llo Wo");
106114

107115
let size = buf.read_from(&mut inp).unwrap();
108116
assert_eq!(size, 4);

0 commit comments

Comments
 (0)