Compile time checked bytes manipulations

Hello, when I was implementing some file format using bytes I kept thinking that each put_u16 call checks length of underlying buffer. But usually headers and other file format stuff have known size.
I decided to create crate that lets you check your buffer once and then write to it fixed amount of bytes.

And there it is:
Const Writer(github)
Const Writer(crates.io)

Sample:

use const_writer::ConstWrite;
fn main() {
   let mut vec = vec![];
   let writer = vec.const_writer::<10>() // reserve 10 bytes in vec
       .write_u32_le(12)  // no runtime checks
       .write_u32_le(34); // no runtime checks

   assert_eq!(writer.remaining(), 2);
   assert_eq!(vec.len(), 8);
   assert_eq!(&vec[0..8], &[12, 0, 0, 0, 34, 0, 0, 0]);
}

This lib uses fresh const_generics and const_evaluatable_checked features.
My main concern is unsafe code. I've never wrote unsafe code, which should be safe, so I'm completely unsure if my code anywhere close to being safe.

Will be really happy to hear your feedback.
Thanks in advance

The use case looks nice. I haven't looked at the code. However, I am not sure whether this would actually have a performance increase, since it's possible that the optimizer would already prove at compile time that the bounds check will not be exceeded. I don't know, though.

I have few benchmarks. Vec benchmarks on par with bytes (bytes have unoptimized operation on slices, found this bug while comparing assembly output pull).

Assembly for bytes still contains more comparison playground, but looks like branch prediction works nice too.

So yeah, not a lot of profit, but maybe in some cases a bit less of jmp instructions could help)

1 Like