Reset Bytes position to zero

The crate bytes doesn't provide anyway to reset position to 0, so I'm stuck with this inefficient code:

static BASIC_PLANE: &'static [u8] = include_bytes!("./general_category_data/basic.bin");

impl From<char> for GeneralCategory {
    fn from(code_point: char) -> Self {
        let code_point = code_point as usize;
        let mut compare_code_point: usize = 0;
        let mut count: usize = 0;
        let mut category_value: u8 = 0;
        if code_point < 0x10000 {
            let plane = Bytes::from_static(BASIC_PLANE);

The problem is that GeneralCategory::from will be called frequently, and I believe the line Bytes::from_static(BASIC_PLANE); will clone the bytes contents on the fly. I wanted to rather store Bytes as a static variable, but as I said there's no set_position method. Someone on Discord said the byteorder crate could be better suited for my needs, but then it requires me to convert the static &'static [u8] into Vec<u8> (that's what Cursor::new accepts).

1 Like

According to the docs Bytes::from_static directly stores a reference without making any copy for as long as you don't mutate the Bytes instance. In any case bytes.set_position() is not possible as Bytes doesn't store a position. .advance() offsets the underlying pointer, losing any information about where it originally started.


I didn't pay attention, thanks! But how doesn't Bytes store a position since it implements Buf? Buf has methods like get_u8_le(), which advances position.

1 Like

It just increments the internal pointer


You can't move backwards with a Bytes, but you can make a clone of it and replace your advanced Bytes with the clone to move back to the position it had when you called clone.