Rust - как повторить реализацию из PHP?
Есть реализованный на PHP разбор бинарного файла в hex (читаются данные из файла):
while (!feof($handle)) {
$bin = fread ($handle , 7 );
$hex = bin2hex($bin);
}
Как это можно повторить-реализовать на Rust?
fread - читает побайтово
bin2hex - преобразует бинарные в шестнадцатеричное значение
Ответы (1 шт):
Автор решения: free_ze
→ Ссылка
use std::io::{Read, Result};
fn read_as_php(handle: &mut impl Read) -> Result<()> {
const READ_MAX_LEN: usize = 7;
let mut bin = [0; READ_MAX_LEN];
loop {
let bytes_read = handle.take(READ_MAX_LEN as u64)
.read(&mut bin)?;
if bytes_read == 0 { break; } // EOF
let hex = bin[..bytes_read].iter()
.map(|byte|format!("{byte:02x?}"))
.collect::<String>();
println!("{hex}");
}
Ok(())
}
#[test]
fn test_with_file() {
let mut file = std::fs::File::open("path/to/file")
.expect("Unable to open file");
let result = read_as_php(&mut file);
assert!(result.is_ok())
}
Output:
...
f9ca64adf9ca64
adf9ca64a48159
64a1f9ca641285
cb65aff9ca6412
85cf65baf9ca64
1285ce65a4f9ca
641285c965aef9
...
00000000000000
00000000