|
| 1 | +use bytes::{Bytes, BytesMut}; |
| 2 | + |
| 3 | +#[derive(Default)] |
| 4 | +pub(crate) struct BytesExt { |
| 5 | + bytes: Bytes, |
| 6 | + cursor: usize, |
| 7 | +} |
| 8 | + |
| 9 | +impl BytesExt { |
| 10 | + #[inline(always)] |
| 11 | + pub(crate) fn slice(&self) -> &[u8] { |
| 12 | + &self.bytes[self.cursor..] |
| 13 | + } |
| 14 | + |
| 15 | + #[inline(always)] |
| 16 | + pub(crate) fn remaining(&self) -> usize { |
| 17 | + self.bytes.len() - self.cursor |
| 18 | + } |
| 19 | + |
| 20 | + #[inline(always)] |
| 21 | + pub(crate) fn set_remaining(&mut self, n: usize) { |
| 22 | + // We can use `bytes.advance()` here, but it's slower. |
| 23 | + self.cursor = self.bytes.len() - n; |
| 24 | + } |
| 25 | + |
| 26 | + #[inline(always)] |
| 27 | + pub(crate) fn advance(&mut self, n: usize) { |
| 28 | + // We can use `bytes.advance()` here, but it's slower. |
| 29 | + self.cursor += n; |
| 30 | + } |
| 31 | + |
| 32 | + #[inline(always)] |
| 33 | + pub(crate) fn extend(&mut self, chunk: Bytes) { |
| 34 | + if self.cursor == self.bytes.len() { |
| 35 | + // Most of the time, we read the next chunk after consuming the previous one. |
| 36 | + self.bytes = chunk; |
| 37 | + self.cursor = 0; |
| 38 | + } else { |
| 39 | + // Some bytes are left in the buffer, we need to merge them with the next chunk. |
| 40 | + self.extend_slow(chunk); |
| 41 | + } |
| 42 | + } |
| 43 | + |
| 44 | + #[cold] |
| 45 | + #[inline(never)] |
| 46 | + fn extend_slow(&mut self, chunk: Bytes) { |
| 47 | + let total = self.remaining() + chunk.len(); |
| 48 | + let mut new_bytes = BytesMut::with_capacity(total); |
| 49 | + let capacity = new_bytes.capacity(); |
| 50 | + new_bytes.extend_from_slice(self.slice()); |
| 51 | + new_bytes.extend_from_slice(&chunk); |
| 52 | + debug_assert_eq!(new_bytes.capacity(), capacity); |
| 53 | + self.bytes = new_bytes.freeze(); |
| 54 | + self.cursor = 0; |
| 55 | + } |
| 56 | +} |
| 57 | + |
| 58 | +#[test] |
| 59 | +fn it_works() { |
| 60 | + let mut bytes = BytesExt::default(); |
| 61 | + assert!(bytes.slice().is_empty()); |
| 62 | + assert_eq!(bytes.remaining(), 0); |
| 63 | + |
| 64 | + bytes.extend(Bytes::from_static(b"hello")); |
| 65 | + assert_eq!(bytes.slice(), b"hello"); |
| 66 | + assert_eq!(bytes.remaining(), 5); |
| 67 | + |
| 68 | + bytes.advance(3); |
| 69 | + assert_eq!(bytes.slice(), b"lo"); |
| 70 | + assert_eq!(bytes.remaining(), 2); |
| 71 | + |
| 72 | + bytes.extend(Bytes::from_static(b"l")); |
| 73 | + assert_eq!(bytes.slice(), b"lol"); |
| 74 | + assert_eq!(bytes.remaining(), 3); |
| 75 | + |
| 76 | + bytes.set_remaining(1); |
| 77 | + assert_eq!(bytes.slice(), b"l"); |
| 78 | + assert_eq!(bytes.remaining(), 1); |
| 79 | +} |
0 commit comments