I'm having trouble writing Vec<u16>
content to a file:
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() {}
Since write_all()
asks for a &[u8]
, I'm doing an unsafe conversion of &[u16]
to &[u8]
. Because the conversion does not change the slice length (slice.len()
and sl.len()
have the same values), only half of the image data is output to the file.
It would be better if I don't need any unsafe conversion or copying.