1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
use bytes::BufMut; use bytes::Bytes; use std::ops::Add; #[derive(Debug, Clone, Eq, PartialEq)] enum BodyInner { Empty, Bytes(Bytes), } #[derive(Debug, Clone, Eq, PartialEq)] pub struct Body { inner: BodyInner, } impl Body { pub fn empty() -> Self { Self { inner: BodyInner::Empty, } } } impl Add<Body> for Body { type Output = Self; fn add(self, other: Self) -> Self::Output { match (self.inner, other.inner) { (BodyInner::Empty, BodyInner::Bytes(b)) => b.into(), (BodyInner::Bytes(a), BodyInner::Empty) => a.into(), (BodyInner::Bytes(a), BodyInner::Bytes(b)) => { let mut buf = Vec::<u8>::with_capacity(a.len() + b.len()); buf.put(a); buf.put(b); Bytes::from(buf).into() } _ => Self { inner: BodyInner::Empty, }, } } } impl From<Bytes> for Body { fn from(bytes: Bytes) -> Self { let inner = if bytes.is_empty() { BodyInner::Empty } else { BodyInner::Bytes(bytes) }; Self { inner } } } impl From<Body> for Bytes { fn from(b: Body) -> Self { match b.inner { BodyInner::Empty => Bytes::new(), BodyInner::Bytes(bytes) => bytes, } } }