0

Im trying to slice into a buffer but am getting an error.

let mut buf = Vec::new();
let mut dst = [0u8; 4];
let read_index = 0;

dst.clone_from_slice(&buf[read_index..(read_index+3)]);
let length = u32::from_be_bytes(dst);
    
&buf[(read_index+4)..(read_index+length)]

error[E0308]: mismatched types
  --> src/main.rs:28:79
   |
28 |         let trade = root_as_fb_iq_feed_trade(&buf[(read_index+4)..(read_index+length)]);
   |                                                                               ^^^^^^ expected `usize`, found `u32`

error[E0277]: cannot add `u32` to `usize`
  --> src/main.rs:28:78
   |
28 |         let trade = root_as_fb_iq_feed_trade(&buf[(read_index+4)..(read_index+length)]);
   |                                                                              ^ no implementation for `usize + u32`
   |
   = help: the trait `Add<u32>` is not implemented for `usize`
BAR
  • 15,909
  • 27
  • 97
  • 185
  • 2
    Dose this answer your question? https://stackoverflow.com/questions/43704758/how-to-idiomatically-convert-between-u32-and-usize – Joe_Jingyu Dec 19 '21 at 03:25

2 Answers2

1
let mut buf = Vec::new();
let read_index = 0;

dst.clone_from_slice(&buf[read_index..(read_index+3)]);
let length = usize::from_be_bytes(dst); // u32 -> usize
    
&buf[(read_index+4)..(read_index+length)]

usize supports the from_be_bytes method: The Rust doc of size::from_be_bytes

The error info from the compiler is clear enough to make you write the code that works. There is also specification on the doc I mentioned above, the function from_be_bytes only accepts the param as [u8; 8], so there is one more modification:

let mut buf = Vec::new();
let mut dst = [0u8; 8]; // Expand your buffer to the size of 8
let read_index = 0;

dst.clone_from_slice(&buf[read_index..(read_index+3)]);
let length = usize::from_be_bytes(dst);
    
&buf[(read_index+4)..(read_index+length)]
 
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Dec 19 '21 at 10:30
  • let length = usize::from_be_bytes(dst); | ^^^ expected an array with a fixed size of 8 elements, found one with 4 elements – BAR Dec 19 '21 at 18:14
0
let length = u32::from_be_bytes(dst);
let length_us = usize::try_from(length).unwrap();
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
BAR
  • 15,909
  • 27
  • 97
  • 185
  • 4
    If this is a solution to your question, it would be good to add what exactly this code does to solve the problem – camille Dec 19 '21 at 21:06