1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
use crate::Pipe;
use lazy_static::lazy_static;
use std::{io::Write, sync::Mutex};
use flurry::*;

lazy_static! 
{
    static ref PIPES: HashMap<String, Mutex<Pipe>> = HashMap::new();
}

/// Print a string to a static pipe
#[macro_export]
macro_rules! pprint 
{
    ($name:tt, $($arg:tt)*) => ($crate::print($name, format!($($arg)*).as_str()));
}

/// Print a string and a trailing newline to a static pipe
#[macro_export]
macro_rules! pprintln 
{
    ($name:tt) => ($crate::print($name, "\n"));
    ($name:tt, $($arg:tt)*) => ($crate::print($name, {let mut s = format!($($arg)*); s.push('\n'); s}.as_str()))
}

/// Initialize a static pipe and return a handle to it.
pub fn init(name: &str) -> crate::Result<Pipe>
{
    let pipe = Pipe::with_name(name)?;
    let reader = pipe.clone();
    PIPES.insert(name.to_string(), Mutex::from(pipe), &PIPES.guard());
    Ok(reader)
}

/// Get a handle to an existing static pipe
pub fn get(name: &str) -> Option<Pipe>
{
    PIPES.get(name, &PIPES.guard()).map(|pipe| pipe.lock().unwrap().clone())
}

/// Closes a static pipe
pub fn close(name: &str)
{
    match PIPES.remove(name, &PIPES.guard())
    {
        Some(pipe) => { drop(pipe.lock().unwrap()) }
        None => {}
    }
}

/// Closes all static pipes
pub fn close_all()
{
    PIPES.clear(&PIPES.guard())
}

/// The lowest-level static-pipe print function. Panics if pipe is not 
/// initialized.
#[inline]
pub fn print(name: &str, s: &str) -> crate::Result<usize>
{
    match PIPES.get(name, &PIPES.guard())
    {
        None => Err(crate::Error::Ipipe("Pipe not initialized")),
        Some(pipe) => 
        {
            let mut pipe = pipe.lock()?;
            match pipe.write(s.as_bytes())
            {
                Ok(written) => Ok(written),
                Err(e) => Err(crate::Error::from(e))
            }
        }
    }
}