0

I am trying to extract two 16 byte values from the front of a large buffer into 2 16 byte smaller buffers.

I wrote a simple memcpy_safe() function:

fn memcpy_safe(dest: &mut [u8], src: &[u8]) {
    let src_len = src.len();
    let dest_len = dest.len();
    if(src_len != dest_len) {
        println!("memcpy_safe found src and dest do not have the same length, truncating ({}, {})", src_len, dest_len);
    }

    for i in 0..dest_len {
        if i < src_len {
            dest[i] = src[i];
        } else {
            break;
        }
    }
    
}

and I would like to use this to do the copy, but pass the starting location of each of the 16 byte values to the parameter src.

This is easily possible in C using pointer arithmetic, but I was wondering if a similar thing is possible in Rust. If not, what is the standard way to do something like this?

Chayim Friedman
  • 47,971
  • 5
  • 48
  • 77
Dyskord
  • 365
  • 5
  • 14
  • Does this answer your question? [How to get subslices?](https://stackoverflow.com/questions/30272673/how-to-get-subslices). It sounds like you'd want to get subslices of the beginning of your original buffers: `memcpy_safe(&mut A[..32], &B[..32])`. If you also want this to be generic in the type it's copying you'll want to use a generic type parameter instead of `u8`; see e.g., [`copy_from_slice`](https://doc.rust-lang.org/std/primitive.slice.html#method.copy_from_slice). – kopecs Jun 21 '22 at 20:40
  • *I am trying to extract two 16 byte values from the front of a large buffer* — on the chance that you meant 16 **bits**: [`ReadBytesExt::read_u16`](https://docs.rs/byteorder/latest/byteorder/trait.ReadBytesExt.html#method.read_u16) – Shepmaster Jun 22 '22 at 13:57
  • Nah I meant 16 bytes – Dyskord Jun 22 '22 at 20:40

0 Answers0