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