Buf trait on bytes::Bytes


The following might be a stupid problem. Anyway.

The code

use bytes::{BytesMut, Buf, BufMut, Bytes};

    let mut buf = Bytes::with_capacity(1024);
    buf.extend_from_slice(&b"hello world"[..]);
    let check = buf.get_u16();

does not compile. Seems like the function get_u16() which is from the bytes::Buf trait is unknown to the compiler. Error is:

error[E0599]: no method named get_u16 found for type bytes::Bytes in the current scope
–> src/foo.rs:169:25
169 | let check = buf.get_u16();
| ^^^^^^^

error: aborting due to previous error

Does not make sense to me, as Bytes has the buffer trait implemented. That more or less the hole point of Bytes



I think you want something like this.

extern crate bytes; // 0.4.11

fn main() {
    use bytes::{BytesMut, Buf, BufMut, Bytes, IntoBuf};

    let mut bytes = Bytes::with_capacity(1024);
    bytes.extend_from_slice(&b"hello world"[..]);
    let mut buf = (&bytes).into_buf();
    let check = buf.get_u16_le();

Playground Link

Read the crate documentation for more information. A Buf is usually something like a “cursor” over a Bytes or over a bunch of chained Bytes.

1 Like


Hmm… I might not understand Bytes as much as I thought. I was under the impression that Bytes implements the Buf trait. In

how much new data is generated? A bit more than the size of a pointer I assume, right? So buf is a reference to the memory where bytes is also pointing to, but but also holds a counter to a certain position in bytes. Correct? But then bytes itself does the same. Why should I I invest the cycles for buf = (&bytes).into_buf() … One of the major points of bytes is to be used in ultra fast code



Bytes::IntoBuf holds a pointer to the bytes and a u64 for the index. It’s pretty much the cheapest thing in the world, and it’s just as easily optimized as the i in for (int i = 0; i < length; i++) in a traditional C-style loop. Is that also too wasteful?

Edit: Although the implementation of Buf doesn’t seem very “fast”.



Sure, its cheap.