tokio/util/
as_ref.rs

1use super::typeid;
2
3#[derive(Debug)]
4pub(crate) enum OwnedBuf {
5    Vec(Vec<u8>),
6    #[cfg(feature = "io-util")]
7    Bytes(bytes::Bytes),
8}
9
10impl AsRef<[u8]> for OwnedBuf {
11    fn as_ref(&self) -> &[u8] {
12        match self {
13            Self::Vec(vec) => vec,
14            #[cfg(feature = "io-util")]
15            Self::Bytes(bytes) => bytes,
16        }
17    }
18}
19
20pub(crate) fn upgrade<B: AsRef<[u8]>>(buf: B) -> OwnedBuf {
21    let buf = match unsafe { typeid::try_transmute::<B, Vec<u8>>(buf) } {
22        Ok(vec) => return OwnedBuf::Vec(vec),
23        Err(original_buf) => original_buf,
24    };
25
26    let buf = match unsafe { typeid::try_transmute::<B, String>(buf) } {
27        Ok(string) => return OwnedBuf::Vec(string.into_bytes()),
28        Err(original_buf) => original_buf,
29    };
30
31    #[cfg(feature = "io-util")]
32    let buf = match unsafe { typeid::try_transmute::<B, bytes::Bytes>(buf) } {
33        Ok(bytes) => return OwnedBuf::Bytes(bytes),
34        Err(original_buf) => original_buf,
35    };
36
37    OwnedBuf::Vec(buf.as_ref().to_owned())
38}