Mam problemy z pisania Vec<u16>
zawartość do pliku:Jaki jest prawidłowy sposób zapisu treści `Vec <u16>` do pliku?
use std::fs::File;
use std::io::{Write, BufWriter};
use std::mem;
#[derive(Debug, Copy, Clone, PartialEq)]
pub enum ImageFormat {
GrayScale,
Rgb32,
}
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct ImageHeader {
pub width: usize,
pub height: usize,
pub format: ImageFormat,
}
pub struct Image {
pub header: ImageHeader,
pub data: Vec<u16>,
}
fn write_to_file(path: &str, img: &Image) -> std::io::Result<()> {
let f = try!(File::create(path));
let mut bw = BufWriter::new(f);
let slice = &img.data[..];
println!("before length: {}", slice.len());
let sl: &[u8];
unsafe {
sl = mem::transmute::<&[u16], &[u8]>(slice);
}
println!("after length: {}", sl.len());
try!(bw.write_all(sl));
return Ok(());
}
fn main() {}
Od write_all()
prosi o &[u8]
, robię niebezpiecznego konwersję &[u16]
do &[u8]
. Ponieważ konwersja nie zmienia długości plasterka (slice.len()
i sl.len()
mają te same wartości), tylko połowa danych obrazu jest wysyłana do pliku.
Byłoby lepiej, gdybym nie potrzebował żadnej niebezpiecznej konwersji lub kopiowania.
Dzięki! Próbowałem twojej metody używania 'slice :: from_raw_parts()' i działało idealnie. – rillomas