Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to manipulate buffer in Rust?

a few weeks ago I got interested in Rust. So far I have only read online tutorials and wonder how to manipulate buffer memory in Rust. Let’s say I have C code like this:

int main()
{
    char buffer[] = { 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa };

    int a = *(int*)&buffer[0];
    a = 0xdeadc0de;

    short b = *(short*)&buffer[4];
    b = 0xbadf;

    *(int*)&buffer[0] = a;  
    *(short*)&buffer[4] = b; 

    //buffer memory: de c0 ad de df ba 77 88 99 aa

    return 0;
}

Could anyone write this in Rust please? I think there’s no casting in Rust, right?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Direct buffer manipulation through transmuted references is considered unsafe in Rust. You can of course use the unsafe keyword for writing into memory directly, but that would negate the whole safety advantage of using Rust.

You can create an u32, convert it to a [u8] array and then write that into the buffer. But you cannot safely get a &u32 reference from a buffer.

fn main() {
    let mut buffer = vec![0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa];

    let a: u32 = 0xdeadc0de;
    let a_bytes = a.to_le_bytes();
    buffer[0..4].copy_from_slice(&a_bytes);

    let b: u16 = 0xbadf;
    let b_bytes = b.to_le_bytes();
    buffer[4..6].copy_from_slice(&b_bytes);

    println!("{:x?}", buffer);
}
[de, c0, ad, de, df, ba, 77, 88, 99, aa]

Just for reference, this is how this would look like with unsafe code.
I highly discourage this solution, though.

fn main() {
    let mut buffer: Vec<u8> = vec![0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa];

    unsafe {
        let ptr = buffer.as_mut_ptr();

        let a = ptr.offset(0) as *mut u32;
        *a = 0xdeadc0de;

        let b = ptr.offset(4) as *mut u16;
        *b = 0xbadf;
    }

    println!("{:x?}", buffer);
}
[de, c0, ad, de, df, ba, 77, 88, 99, aa]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading