1 // FIXME(regexident): 2 // Replace with `bytes::ExactSizeBuf` once merged: 3 // https://github.com/tokio-rs/bytes/pull/496 4 5 use bytes::{ 6 buf::{Chain, Take}, 7 Bytes, BytesMut, 8 }; 9 10 /// A trait for buffers that know their exact length. 11 pub trait ExactSizeBuf { 12 /// Returns the exact length of the buffer. len(&self) -> usize13 fn len(&self) -> usize; 14 15 /// Returns `true` if the buffer is empty. 16 /// 17 /// This method has a default implementation using `ExactSizeBuf::len()`, 18 /// so you don't need to implement it yourself. 19 #[inline] is_empty(&self) -> bool20 fn is_empty(&self) -> bool { 21 self.len() == 0 22 } 23 } 24 25 impl ExactSizeBuf for Bytes { 26 #[inline] len(&self) -> usize27 fn len(&self) -> usize { 28 Bytes::len(self) 29 } 30 31 #[inline] is_empty(&self) -> bool32 fn is_empty(&self) -> bool { 33 Bytes::is_empty(self) 34 } 35 } 36 37 impl ExactSizeBuf for BytesMut { 38 #[inline] len(&self) -> usize39 fn len(&self) -> usize { 40 BytesMut::len(self) 41 } 42 43 #[inline] is_empty(&self) -> bool44 fn is_empty(&self) -> bool { 45 BytesMut::is_empty(self) 46 } 47 } 48 49 impl ExactSizeBuf for [u8] { 50 #[inline] len(&self) -> usize51 fn len(&self) -> usize { 52 <[u8]>::len(self) 53 } 54 55 #[inline] is_empty(&self) -> bool56 fn is_empty(&self) -> bool { 57 <[u8]>::is_empty(self) 58 } 59 } 60 61 impl<T, U> ExactSizeBuf for Chain<T, U> 62 where 63 T: ExactSizeBuf, 64 U: ExactSizeBuf, 65 { len(&self) -> usize66 fn len(&self) -> usize { 67 let first_ref = self.first_ref(); 68 let last_ref = self.last_ref(); 69 70 first_ref.len() + last_ref.len() 71 } 72 is_empty(&self) -> bool73 fn is_empty(&self) -> bool { 74 let first_ref = self.first_ref(); 75 let last_ref = self.last_ref(); 76 77 first_ref.is_empty() && last_ref.is_empty() 78 } 79 } 80 81 impl<T> ExactSizeBuf for Take<T> 82 where 83 T: ExactSizeBuf, 84 { len(&self) -> usize85 fn len(&self) -> usize { 86 let inner_ref = self.get_ref(); 87 let limit = self.limit(); 88 89 limit.min(inner_ref.len()) 90 } 91 is_empty(&self) -> bool92 fn is_empty(&self) -> bool { 93 let inner_ref = self.get_ref(); 94 let limit = self.limit(); 95 96 (limit == 0) || inner_ref.is_empty() 97 } 98 } 99