Struct MemFile

Source
pub struct MemFile { /* private fields */ }
Expand description

Struct used to manipulate the shared memory

Implementations§

Source§

impl MemFile

Source

pub fn open(path: PathBuf) -> Result<MemFile, Box<dyn Error>>

Opens an existing MemFile

§Examples
//Opens an existing shared MemFile named test.txt
let mut mem_file: MemFile = match MemFile::open(PathBuf::from("test.txt")) {
    Ok(v) => v,
    Err(e) => {
        println!("Error : {}", e);
        println!("Failed to open MemFile...");
        return;
    }
};
Examples found in repository?
examples/open.rs (line 19)
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}
Source

pub fn create(path: PathBuf, size: usize) -> Result<MemFile, Box<dyn Error>>

Creates a new MemFile

§Examples
//Creates a new shared MemFile named test.txt of size 4096
let mut mem_file: MemFile = match MemFile::create(PathBuf::from("test.txt"), 4096) {
    Ok(v) => v,
    Err(e) => {
        println!("Error : {}", e);
        println!("Failed to create MemFile...");
        return;
    }
};
Examples found in repository?
examples/create.rs (line 15)
12fn main() {
13
14    //Create a new shared MemFile
15    let mut mem_file: MemFile = match MemFile::create(PathBuf::from("test.txt"), 4096) {
16        Ok(v) => v,
17        Err(e) => {
18            println!("Error : {}", e);
19            println!("Failed to create MemFile...");
20            return;
21        }
22    };
23
24    //Initialize the MemFile with default values
25    {
26        let mut shared_state: MemFileWLock<SharedState> = match mem_file.wlock() {
27            Ok(v) => v,
28            Err(_) => panic!("Failed to acquire write lock !"),
29        };
30
31        shared_state.num_listenners = 0;
32        let src = b"Welcome, we currently have 0 listenners !\x00";
33        shared_state.message[0..src.len()].copy_from_slice(src);
34    }
35    println!("Waiting for a listenner to connect !");
36
37    //Loop until our memory has changed
38    loop {
39
40        //Acquire read lock
41        let shared_state: MemFileRLock<SharedState> = match mem_file.rlock() {
42            Ok(v) => v,
43            Err(_) => panic!("Failed to acquire read lock !"),
44        };
45
46        //Check shared memory
47        if shared_state.num_listenners > 0 {
48            println!("We have a listenner !");
49            break;
50        }
51
52        //Release the lock before sleeping
53        drop(shared_state);
54        std::thread::sleep(std::time::Duration::from_millis(200));
55    }
56
57    //Modify the shared memory just for fun
58    {
59        let mut shared_state: MemFileWLock<SharedState> = match mem_file.wlock() {
60            Ok(v) => v,
61            Err(_) => panic!("Failed to acquire write lock !"),
62        };
63
64        let src = format!("Goodbye {} listenner(s) !\x00", shared_state.num_listenners);
65        shared_state.message[0..src.len()].copy_from_slice(&src.as_bytes());
66    }
67}
Source

pub fn get_size(&self) -> &usize

Returns the size of the MemFile

Source

pub fn get_path(&self) -> &PathBuf

Returns the path of the MemFile

Source

pub fn rlock<T: MemFileCast>( &self, ) -> Result<MemFileRLock<'_, T>, Box<dyn Error>>

Returns a non-exclusive read lock to the shared memory

§Examples
//let some_val: MemFileRLock<u8> = mem_file.rlock().unwrap();
let some_val = mem_file.rlock::<u8>().unwrap();
println!("I can read a shared u8 ! {}", *some_val);
Examples found in repository?
examples/create.rs (line 41)
12fn main() {
13
14    //Create a new shared MemFile
15    let mut mem_file: MemFile = match MemFile::create(PathBuf::from("test.txt"), 4096) {
16        Ok(v) => v,
17        Err(e) => {
18            println!("Error : {}", e);
19            println!("Failed to create MemFile...");
20            return;
21        }
22    };
23
24    //Initialize the MemFile with default values
25    {
26        let mut shared_state: MemFileWLock<SharedState> = match mem_file.wlock() {
27            Ok(v) => v,
28            Err(_) => panic!("Failed to acquire write lock !"),
29        };
30
31        shared_state.num_listenners = 0;
32        let src = b"Welcome, we currently have 0 listenners !\x00";
33        shared_state.message[0..src.len()].copy_from_slice(src);
34    }
35    println!("Waiting for a listenner to connect !");
36
37    //Loop until our memory has changed
38    loop {
39
40        //Acquire read lock
41        let shared_state: MemFileRLock<SharedState> = match mem_file.rlock() {
42            Ok(v) => v,
43            Err(_) => panic!("Failed to acquire read lock !"),
44        };
45
46        //Check shared memory
47        if shared_state.num_listenners > 0 {
48            println!("We have a listenner !");
49            break;
50        }
51
52        //Release the lock before sleeping
53        drop(shared_state);
54        std::thread::sleep(std::time::Duration::from_millis(200));
55    }
56
57    //Modify the shared memory just for fun
58    {
59        let mut shared_state: MemFileWLock<SharedState> = match mem_file.wlock() {
60            Ok(v) => v,
61            Err(_) => panic!("Failed to acquire write lock !"),
62        };
63
64        let src = format!("Goodbye {} listenner(s) !\x00", shared_state.num_listenners);
65        shared_state.message[0..src.len()].copy_from_slice(&src.as_bytes());
66    }
67}
Source

pub fn rlock_as_slice<T: MemFileCast>( &self, ) -> Result<MemFileRLockSlice<'_, T>, Box<dyn Error>>

Returns a non-exclusive read lock to the shared memory as a slice

§Examples
//let read_buf: MemFileRLockSlice<u8> = mem_file.rlock_as_slice().unwrap();
let read_buf = mem_file.rlock_as_slice::<u8>().unwrap();
println!("I'm reading into a u8 from a shared &[u8] ! : {}", read_buf[0]);
Examples found in repository?
examples/open.rs (line 31)
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}
Source

pub fn wlock<T: MemFileCast>( &mut self, ) -> Result<MemFileWLock<'_, T>, Box<dyn Error>>

Returns an exclusive read/write lock to the shared memory

§Examples
//let mut some_val: MemFileWLock<u32> = mem_file.wlock().unwrap();
let mut some_val = mem_file.wlock::<u32>().unwrap();
*(*some_val) = 1;
Examples found in repository?
examples/open.rs (line 44)
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}
More examples
Hide additional examples
examples/create.rs (line 26)
12fn main() {
13
14    //Create a new shared MemFile
15    let mut mem_file: MemFile = match MemFile::create(PathBuf::from("test.txt"), 4096) {
16        Ok(v) => v,
17        Err(e) => {
18            println!("Error : {}", e);
19            println!("Failed to create MemFile...");
20            return;
21        }
22    };
23
24    //Initialize the MemFile with default values
25    {
26        let mut shared_state: MemFileWLock<SharedState> = match mem_file.wlock() {
27            Ok(v) => v,
28            Err(_) => panic!("Failed to acquire write lock !"),
29        };
30
31        shared_state.num_listenners = 0;
32        let src = b"Welcome, we currently have 0 listenners !\x00";
33        shared_state.message[0..src.len()].copy_from_slice(src);
34    }
35    println!("Waiting for a listenner to connect !");
36
37    //Loop until our memory has changed
38    loop {
39
40        //Acquire read lock
41        let shared_state: MemFileRLock<SharedState> = match mem_file.rlock() {
42            Ok(v) => v,
43            Err(_) => panic!("Failed to acquire read lock !"),
44        };
45
46        //Check shared memory
47        if shared_state.num_listenners > 0 {
48            println!("We have a listenner !");
49            break;
50        }
51
52        //Release the lock before sleeping
53        drop(shared_state);
54        std::thread::sleep(std::time::Duration::from_millis(200));
55    }
56
57    //Modify the shared memory just for fun
58    {
59        let mut shared_state: MemFileWLock<SharedState> = match mem_file.wlock() {
60            Ok(v) => v,
61            Err(_) => panic!("Failed to acquire write lock !"),
62        };
63
64        let src = format!("Goodbye {} listenner(s) !\x00", shared_state.num_listenners);
65        shared_state.message[0..src.len()].copy_from_slice(&src.as_bytes());
66    }
67}
Source

pub fn wlock_as_slice<T: MemFileCast>( &mut self, ) -> Result<MemFileWLockSlice<'_, T>, Box<dyn Error>>

Returns exclusive read/write access to a &mut [T] on the shared memory

§Examples
//let write_buf: MemFileWLockSlice<u8> = mem_file.wlock_as_slice().unwrap();
let write_buf = mem_file.wlock_as_slice::<u8>().unwrap();
write_buf[0] = 0x1;

Trait Implementations§

Source§

impl Drop for MemFile

Source§

fn drop(&mut self)

Deletes the MemFile artifacts

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.