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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
use lazy_static::lazy_static; 
use std::sync::Mutex;

pub struct Handler {
    id: u64,
    uri: String,
}

impl Handler {
    fn new(id: u64, uri: &str) -> Handler {
        Handler {
            id: id,
            uri: uri.to_string()
        }
    }
}

lazy_static! {
    static ref HANDLERS:Mutex<Vec<Handler>> = Mutex::new(Vec::new());
    static ref SOCKETS:Mutex<Vec<u64>> = Mutex::new(vec![0;0]);
}


pub fn handler_create(uri: &str) -> u64 {
    let new_id:u64;
    let mut handles = HANDLERS.lock().unwrap();

    if handles.len() == 0 {
        new_id = 1;
    } else {
        let last_id = handles[handles.len()-1].id;
        new_id = last_id + 1;
    }

    let new_handler = Handler::new(new_id, uri); 
    
    handles.push(new_handler);
    return new_id;
}

pub fn handler_close(hndl:u64) -> bool {
    let mut handles = HANDLERS.lock().unwrap();
    let idx = match handles.iter().position(|h| (*h).id == hndl) {
        Some(i) => i,
        None => return false,
    };
    handles.remove(idx);
    return true;
}

pub fn handler_print() {
    let hndls = HANDLERS.lock().unwrap();
    for h in hndls.iter() {
        println!("{:x} {}", h.id, h.uri);
    }
}

pub fn handler_exist(hndl:u64) -> bool {
    let handles = HANDLERS.lock().unwrap();
    match handles.iter().position(|h| (*h).id == hndl) {
        Some(_) => return true,
        None => return false,
    }
}

pub fn handler_get_uri(hndl:u64) -> String {
    let handles = HANDLERS.lock().unwrap();
    match handles.iter().position(|h| (*h).id == hndl) {
        Some(idx) => return handles[idx].uri.clone(),
        None => return String::new(),
    }
}


pub fn socket_create() -> u64 {
    let new_socket:u64;
    let mut sockets = SOCKETS.lock().unwrap();

    if sockets.len() == 0 {
        sockets.push(0); // stdin
        sockets.push(1); // stdout
        sockets.push(2); // stderr
        new_socket = 3;  // first available socket
    } else {
        let last_socket = sockets[sockets.len()-1];
        new_socket = last_socket + 1;
    }
    
    sockets.push(new_socket);
    return new_socket;
}

pub fn socket_close(sock:u64) -> bool {
    let mut sockets = SOCKETS.lock().unwrap();
    let idx = match sockets.iter().position(|s| *s == sock) {
        Some(i) => i,
        None => return false,
    };
    sockets.remove(idx);
    return true;
}

pub fn socket_exist(sock:u64) -> bool {
    let sockets = SOCKETS.lock().unwrap();
    match sockets.iter().position(|s| *s == sock) {
        Some(_) => return true,
        None => return false,
    }
}