Function read_i32

Source
pub fn read_i32<T: Read>(file: &mut T) -> Result<i32, Error>
Expand description

Read four bytes from a file/serial port and convert it to a 32 bits int

ยงExample

use std::io::Cursor;
use std::io::SeekFrom;
use std::io::prelude::*;
use robust_arduino_serial::*;

let mut buffer = Cursor::new(Vec::new());
let big_number: i32 = 16384; // 2^14

// Write the number to the buffer
write_i32(&mut buffer, big_number);

// Go to the beginning of the buffer
buffer.seek(SeekFrom::Start(0)).unwrap();

// Read 32 bits (four bytes) from the buffer
let read_number: i32 = robust_arduino_serial::read_i32(&mut buffer).unwrap();

assert_eq!(big_number, read_number);
Examples found in repository?
examples/file_read_write.rs (line 49)
10fn main() {
11    let args: Vec<String> = env::args().skip(1).collect();
12    if args.len() < 1
13    {
14        panic!("Please provide a filename as argument");
15    }
16    let filename = &args[0];
17    // Open file and create it if it does not exist
18    let mut file = match OpenOptions::new().read(true).write(true).create(true).open(filename)
19                    {
20                        Err(why) => panic!("Could not open file {}: {}", filename, why),
21                        Ok(file) => file
22                    };
23
24    // write_order is equivalent to write_i8
25    write_order(&mut file, Order::HELLO).unwrap();
26
27    let motor_order = Order::MOTOR as i8;
28    let motor_speed: i16 = -56;
29    write_i8(&mut file, motor_order).unwrap();
30    write_i16(&mut file, motor_speed).unwrap();
31    write_i32(&mut file, 131072).unwrap();
32
33    // Go to the beginning of the file
34    file.seek(SeekFrom::Start(0)).unwrap();
35
36    for _ in 0..2 {
37        // We could have also use read_order(&mut file).unwrap()
38        let order = read_i8(&mut file).unwrap();
39        println!("Ordered received: {:?}", order);
40
41        if let Some(received_order) = Order::from_i8(order)
42        {
43            println!("Known order: {:?}", received_order);
44            match received_order
45            {
46                Order::MOTOR => {
47                    let motor_speed = read_i16(&mut file).unwrap();
48                    println!("Motor Speed = {}", motor_speed);
49                    let test = read_i32(&mut file).unwrap();
50                    println!("test = {}", test);
51                },
52                _ => ()
53            }
54        }
55        else
56        {
57            println!("Unknown order: {:?}", order);
58        }
59    }
60}