-
Notifications
You must be signed in to change notification settings - Fork 3.4k
-
The trait requires Deref<Target = [u8]>
however the trait defines fn buffer_str(&self)
which is fine for the &'de [u8]
's implementation to get zero-copy since it's & &'de [u8]
, but this makes it really difficult for other types to implement Buffer since all types already implement Deref<Target = T> for &T
which means you can't implement Deref<Target = [u8]> for &T
.
I feel it would make more sense if it was something like this,
struct Example(bytes::Bytes); trait TestBuffer { type BufferString<'s> where Self: 's; fn buffer_str<'a: 'b, 'b>(&'a self) -> Result<Self::BufferString<'b>, std::str::Utf8Error>; } impl TestBuffer for Example { type BufferString<'s> = &'s str; fn buffer_str<'a: 'b, 'b>(&'a self) -> Result<Self::BufferString<'b>, std::str::Utf8Error> { std::str::from_utf8(self.0.as_ref()) } }
Playground link: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=70cfeef51c776bdf836f02ef2ad1aaf7
Am I missing another way to get a zero-copy buffer_str()
for custom Buffer implementations?
Beta Was this translation helpful? Give feedback.
All reactions
Replies: 1 comment
-
So the only other way I've figured out how to do this w/ something like Bytes is by using unsafe code,
fn buffer_str<'a: 'b, 'b>(&'a self) -> Result<Self::BufferString<'b>, std::str::Utf8Error> { unsafe { let slice = std::slice::from_raw_parts(self.0.as_ref().as_ptr(), self.0.len()); Ok(std::str::from_utf8(slice)?) } }
Beta Was this translation helpful? Give feedback.