aboutsummaryrefslogtreecommitdiff
path: root/src/bytes_buf.rs
diff options
context:
space:
mode:
Diffstat (limited to 'src/bytes_buf.rs')
-rw-r--r--src/bytes_buf.rs59
1 files changed, 35 insertions, 24 deletions
diff --git a/src/bytes_buf.rs b/src/bytes_buf.rs
index 931be82..3929a86 100644
--- a/src/bytes_buf.rs
+++ b/src/bytes_buf.rs
@@ -1,3 +1,4 @@
+use std::cmp::Ordering;
use std::collections::VecDeque;
use bytes::BytesMut;
@@ -44,7 +45,7 @@ impl BytesBuf {
/// Takes the whole content of the buffer and returns it as a single Bytes unit
pub fn take_all(&mut self) -> Bytes {
- if self.buf.len() == 0 {
+ if self.buf.is_empty() {
Bytes::new()
} else if self.buf.len() == 1 {
self.buf_len = 0;
@@ -82,31 +83,35 @@ impl BytesBuf {
fn take_exact_ok(&mut self, len: usize) -> Bytes {
assert!(len <= self.buf_len);
let front = self.buf.pop_front().unwrap();
- if front.len() > len {
- self.buf.push_front(front.slice(len..));
- self.buf_len -= len;
- front.slice(..len)
- } else if front.len() == len {
- self.buf_len -= len;
- front
- } else {
- let mut ret = BytesMut::with_capacity(len);
- ret.extend_from_slice(&front[..]);
- self.buf_len -= front.len();
- while ret.len() < len {
- let front = self.buf.pop_front().unwrap();
- if front.len() > len - ret.len() {
- let take = len - ret.len();
- ret.extend_from_slice(&front[..take]);
- self.buf.push_front(front.slice(take..));
- self.buf_len -= take;
- break;
- } else {
- ret.extend_from_slice(&front[..]);
- self.buf_len -= front.len();
+ match front.len().cmp(&len) {
+ Ordering::Greater => {
+ self.buf.push_front(front.slice(len..));
+ self.buf_len -= len;
+ front.slice(..len)
+ }
+ Ordering::Equal => {
+ self.buf_len -= len;
+ front
+ }
+ Ordering::Less => {
+ let mut ret = BytesMut::with_capacity(len);
+ ret.extend_from_slice(&front[..]);
+ self.buf_len -= front.len();
+ while ret.len() < len {
+ let front = self.buf.pop_front().unwrap();
+ if front.len() > len - ret.len() {
+ let take = len - ret.len();
+ ret.extend_from_slice(&front[..take]);
+ self.buf.push_front(front.slice(take..));
+ self.buf_len -= take;
+ break;
+ } else {
+ ret.extend_from_slice(&front[..]);
+ self.buf_len -= front.len();
+ }
}
+ ret.freeze()
}
- ret.freeze()
}
}
@@ -116,6 +121,12 @@ impl BytesBuf {
}
}
+impl Default for BytesBuf {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
impl From<Bytes> for BytesBuf {
fn from(b: Bytes) -> BytesBuf {
let mut ret = BytesBuf::new();