bytes icon indicating copy to clipboard operation
bytes copied to clipboard

Feature request: implement `From<Cow<'static, [u8]>>` for `Bytes`

Open alkarkhi opened this issue 2 months ago • 0 comments

I have a function that encodes an input Into<Cow<'static, [u8]>>. When there is encoding accepted I return a new Cow::Owned. But when there is no encoding accepted I just return the input. Here is what it looks like

pub struct Encoding {
    brotli: bool,
    gzip: bool,
}

impl Encoding {
    pub fn new(headers: &HeaderMap) -> Encoding {
        // init
    }

    pub fn encode<T>(&self, content: T) -> Cow<'static, [u8]>
    where 
        T: Into<Cow<'static, [u8]>>,
    {
        if self.brotli {
            // encode to brotli
        }
        else if self.gzip {
            // encode to gzip
        }
        else {
            content.into()
        }
    }
}

Then I have to convert this value into Bytes. For now I can either use match (which becomes too much boilerplate) or Cow::into_owned to convert to Vec<u8> and then Bytes (but that will convert any &'static [u8] to a Vec and thus allocate). I was wondering whether it would be possible to implement From<Cow<'static, [u8]>> for Bytes. From what I can see From<&'static [u8]> and From<Vec<u8>> are already implemented so I don't see an issue.

alkarkhi avatar Jun 12 '24 08:06 alkarkhi