Help at converting Python code to Rust

Hi,

I am trying to convert following Python code to Rust:

data = open(src, 'rb').read()
n = len(data) + 7
header = [82, 73, 70, 70, 255 & n, n >> 8 & 255, n >> 16 & 255, n >> 24 & 255, 87, 69, 66, 80, 86, 80, 56]
data = map(lambda x: x ^ 101, data)

with open(src, 'wb') as f:
    f.write(bytes(header))
    f.write(bytes(data))

But I am not that fit in Rust for now. Can anybody please help me?

If it helps somehow, there is a library in go which does the same.

For a quick script where error messages being ugly does not matter much, I would do the following:

use ::std::{*,
    io::{
        prelude::*,
        Write,
    },
    fs::OpenOptions,
};


fn main () -> io::Result<()>
{
    let src = "some_file";

    let mut data = fs::read(src)?;
    let n = data.len() + 7;
    let header = [
        82, 73, 70, 70, n as u8, (n >> 8) as u8, (n >> 16) as u8, (n >> 24) as u8, 87, 69, 66, 80, 86, 80, 56,
    ];
    // data = data.into_iter().map(|x| x ^ 101).collect();
    data.iter_mut().for_each(|at_x| *at_x ^= 101); // more efficient
    let mut f =
        OpenOptions::new()
            .write(true)
            .truncate(true)
            .open(src)?
    ;
    f.write_all(&header)?;
    f.write_all(&data)?;
    Ok(())
}
2 Likes

You are my hero :smiley:

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.