Hello,
While exploring rust I wrote a program for reading and writing struct to and from a file , but when I run it from command line it goes into infinite loop.
Program flow is that it first take ref of a given struct and then write to a file and next take a mut ref to a struct and read from a file . Some where some thing goes wrong and it keep printing a particular println! (...) .
rustc version is rustc 1.0.0-dev (e40449e0d 2015-04-16) (built 2015-04-16)
Here is the github link https://github.com/ajayprataps/rust-examples/blob/master/rw_struct1.rs
Code for ref
/// Write and Read struct from a file
/// rustc rw_struct1.rs
use std::mem;
use std::slice;
use std::convert::{AsRef};
use std::fs::File;
use std::io::{Read,Write};
#[repr(C)]
pub struct XYZ {
x: [i32;16],
}
/// Goes into infinite loop ?
fn main () {
let mut xyz: XYZ = XYZ {x: [100; 16]};
let mut file = File::create ("abc").unwrap();
println!("({}, {}, {})" ,xyz.x[0],xyz.x[1],xyz.x[2]);
{
let bites: &[u8] = xyz.as_ref () ;
file.write (bites).unwrap();
}
xyz.x = [101;16];
println!("===> ({}, {}, {})" ,xyz.x[0],xyz.x[1],xyz.x[2]);
// Some where here it goes into loop and keep printing
// above line
file.flush().unwrap();
{
file = File::open("abc").unwrap ();
let bites: &mut [u8] = xyz.as_mut () ;
file.read (bites).unwrap();
}
println!("({}, {}, {})" ,xyz.x[0],xyz.x[1],xyz.x[2]);
}
/// XYZ as &[u8]
impl AsRef<[u8]> for XYZ {
fn as_ref (&self) -> &[u8] {
let slice= unsafe {
let p: *const u8 = mem::transmute (&self);
slice::from_raw_parts (p, mem::size_of::<XYZ>())
};
slice
}
}
/// XYZ as &mut [u8]
impl AsMut<[u8]> for XYZ {
fn as_mut (&mut self) -> &mut [u8] {
let slice= unsafe {
let p: *mut u8 = mem::transmute (&self);
slice::from_raw_parts_mut (p, mem::size_of::<XYZ>())
};
slice
}
}