ipipe/
static_pipe.rs

1use crate::Pipe;
2use lazy_static::lazy_static;
3use std::{io::Write, sync::Mutex};
4use flurry::*;
5
6// FIXME: The inconsistent use of mutex should be cleaned up here
7
8// TODO: Accept non-stringly-typed keys somehow
9lazy_static! 
10{
11    static ref PIPES: HashMap<String, Mutex<Pipe>> = HashMap::new();
12}
13
14/// Print a string to a static pipe
15#[macro_export]
16macro_rules! pprint 
17{
18    ($name:tt, $($arg:tt)*) => ($crate::print($name, format!($($arg)*).as_str()));
19}
20
21/// Print a string and a trailing newline to a static pipe
22#[macro_export]
23macro_rules! pprintln 
24{
25    ($name:tt) => ($crate::print($name, "\n"));
26    ($name:tt, $($arg:tt)*) => ($crate::print($name, {let mut s = format!($($arg)*); s.push('\n'); s}.as_str()))
27}
28
29/// Initialize a static pipe and return a handle to it.
30pub fn init(name: &str) -> crate::Result<Pipe>
31{
32    let pipe = Pipe::with_name(name)?;
33    let reader = pipe.clone();
34    PIPES.insert(name.to_string(), Mutex::from(pipe), &PIPES.guard());
35    Ok(reader)
36}
37
38/// Get a handle to an existing static pipe
39pub fn get(name: &str) -> Option<Pipe>
40{
41    PIPES.get(name, &PIPES.guard()).map(|pipe| pipe.lock().unwrap().clone())
42}
43
44/// Closes a static pipe
45pub fn close(name: &str)
46{
47    PIPES.remove(name, &PIPES.guard());
48}
49
50/// Closes all static pipes
51pub fn close_all()
52{
53    PIPES.clear(&PIPES.guard())
54}
55
56/// The lowest-level static-pipe print function. Panics if pipe is not 
57/// initialized.
58#[inline]
59pub fn print(name: &str, s: &str) -> crate::Result<usize>
60{
61    match PIPES.get(name, &PIPES.guard())
62    {
63        None => Err(crate::Error::Ipipe("Pipe not initialized")),
64        Some(pipe) => 
65        {
66            let mut pipe = pipe.lock()?;
67            match pipe.write(s.as_bytes())
68            {
69                Ok(written) => Ok(written),
70                Err(e) => Err(crate::Error::from(e))
71            }
72        }
73    }
74}