1 use std::fmt;
2 //use std::mem;
3 
4 use bytes::Bytes;
5 
6 /// A piece of a message body.
7 pub struct Chunk(Inner);
8 
9 enum Inner {
10     Shared(Bytes),
11 }
12 
13 impl From<Vec<u8>> for Chunk {
14     #[inline]
from(v: Vec<u8>) -> Chunk15     fn from(v: Vec<u8>) -> Chunk {
16         Chunk::from(Bytes::from(v))
17     }
18 }
19 
20 impl From<&'static [u8]> for Chunk {
21     #[inline]
from(slice: &'static [u8]) -> Chunk22     fn from(slice: &'static [u8]) -> Chunk {
23         Chunk::from(Bytes::from_static(slice))
24     }
25 }
26 
27 impl From<String> for Chunk {
28     #[inline]
from(s: String) -> Chunk29     fn from(s: String) -> Chunk {
30         s.into_bytes().into()
31     }
32 }
33 
34 impl From<&'static str> for Chunk {
35     #[inline]
from(slice: &'static str) -> Chunk36     fn from(slice: &'static str) -> Chunk {
37         slice.as_bytes().into()
38     }
39 }
40 
41 impl From<Bytes> for Chunk {
42     #[inline]
from(mem: Bytes) -> Chunk43     fn from(mem: Bytes) -> Chunk {
44         Chunk(Inner::Shared(mem))
45     }
46 }
47 
48 impl From<Chunk> for Bytes {
49     #[inline]
from(chunk: Chunk) -> Bytes50     fn from(chunk: Chunk) -> Bytes {
51         match chunk.0 {
52             Inner::Shared(bytes) => bytes,
53         }
54     }
55 }
56 
57 impl ::std::ops::Deref for Chunk {
58     type Target = [u8];
59 
60     #[inline]
deref(&self) -> &Self::Target61     fn deref(&self) -> &Self::Target {
62         self.as_ref()
63     }
64 }
65 
66 impl AsRef<[u8]> for Chunk {
67     #[inline]
as_ref(&self) -> &[u8]68     fn as_ref(&self) -> &[u8] {
69         match self.0 {
70             Inner::Shared(ref slice) => slice,
71         }
72     }
73 }
74 
75 impl fmt::Debug for Chunk {
76     #[inline]
fmt(&self, f: &mut fmt::Formatter) -> fmt::Result77     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
78         fmt::Debug::fmt(self.as_ref(), f)
79     }
80 }
81 
82 impl Default for Chunk {
83     #[inline]
default() -> Chunk84     fn default() -> Chunk {
85         Chunk(Inner::Shared(Bytes::new()))
86     }
87 }
88 
89 impl IntoIterator for Chunk {
90     type Item = u8;
91     type IntoIter = <Bytes as IntoIterator>::IntoIter;
92 
93     #[inline]
into_iter(self) -> Self::IntoIter94     fn into_iter(self) -> Self::IntoIter {
95         match self.0 {
96             Inner::Shared(bytes) => bytes.into_iter(),
97         }
98     }
99 }
100 
101 impl Extend<u8> for Chunk {
102     #[inline]
extend<T>(&mut self, iter: T) where T: IntoIterator<Item=u8>103     fn extend<T>(&mut self, iter: T) where T: IntoIterator<Item=u8> {
104         match self.0 {
105             Inner::Shared(ref mut bytes) => bytes.extend(iter)
106         }
107     }
108 }
109