Fixed size buffer

I would like to create a fixed size buffer that I can use to read from IO.

// this does not compile, just a jist of what I am looking at doing.
let cookie : String = my_cookie_fn();
let cookie = cookie.as_bytes();

let mut buf = [0u8, cookie.len()]; // this will not work as the size has to be known at compile time

result = IO.read_exact(buf);
if Ok(result) && buf == cookie {
   // it matches!
}

I can't use a vec![0, var] because I want to use the read_exact() fn which requires a buf of exactly n bytes. I don't know the size at compile time so I am having a hard time figuring out how to use the read_exact() fn.

You can use Vec:

let mut buf = vec![0u8; cookie.len()];
result = IO.read_exact(buf.as_mut_slice());
1 Like

Thank you so much...I thought I had tried this already, but...

let mut buf1 = vec![0u8, cookie.len()];
let mut buf2 = vec![0u8; cookie.len()];
buf1 != buf2 // wonder if I am the only one to stumble on this...

Yeah, this is a common typo. This case would be a compile error since u8 and usize aren't the same.

2 Likes