Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

[Rust] flexbuffers::Buffer trait, how to get zero-copy fn buffer_str? #8214

Unanswered
juliusl asked this question in Q&A
Discussion options

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?

You must be logged in to vote

Replies: 1 comment

Comment options

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)?)
 }
}
You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
1 participant

AltStyle によって変換されたページ (->オリジナル) /