open/
open.rs

1extern crate mem_file;
2use mem_file::*;
3use std::path::PathBuf;
4use std::str::from_utf8_unchecked;
5
6//Is there a rust function that does this ?
7fn from_ut8f_to_null(bytes: &[u8], max_len: usize) -> &str {
8    for i in 0..max_len {
9        if bytes[i] == 0 {
10            return unsafe {from_utf8_unchecked(&bytes[0..i])};
11        }
12    }
13    panic!("Couldnt find null terminator.");
14}
15
16fn main() {
17
18    //Open an existing shared MemFile
19    let mut mem_file: MemFile = match MemFile::open(PathBuf::from("test.txt")) {
20        Ok(v) => v,
21        Err(e) => {
22            println!("Error : {}", e);
23            println!("Failed to open MemFile...");
24            return;
25        }
26    };
27
28    //Read the original contents
29    {
30        //Acquire read lock
31        let read_buf: MemFileRLockSlice<u8> = match mem_file.rlock_as_slice() {
32            Ok(v) => v,
33            Err(_) => panic!("Failed to acquire read lock !"),
34        };
35
36        print!("Shared buffer = \"");
37        print!("{}", from_ut8f_to_null(&read_buf[4..], 256));
38        println!("\"");
39    }
40
41    println!("Incrementing shared listenner count !");
42    //Update the shared memory
43    {
44        let mut num_listenners: MemFileWLock<u32> = match mem_file.wlock() {
45            Ok(v) => v,
46            Err(_) => panic!("Failed to acquire write lock !"),
47        };
48        *(*num_listenners) = 1;
49    }
50
51    //Read the contents of the buffer again
52    std::thread::sleep(std::time::Duration::from_secs(1));
53    {
54        let read_buf = match mem_file.rlock_as_slice::<u8>() {
55            Ok(v) => v,
56            Err(_) => panic!("Failed to acquire read lock !"),
57        };
58
59        print!("Shared buffer = \"");
60        print!("{}", from_ut8f_to_null(&read_buf[4..], 256));
61        println!("\"");
62    }
63}