easyterm/
lib.rs

1use std::fmt::Display;
2use std::io::Write;
3
4use num::FromPrimitive;
5use num::Num;
6
7pub struct EasyTerm {}
8
9impl EasyTerm {
10    pub fn clear_screen() {
11        print!("\x1B[2J");
12    }
13    pub fn set_cursor_invisible() {
14        print!("\x1B[?25l");
15    }
16    pub fn set_cursor_top_left() {
17        print!("\x1B[1;1H");
18    }
19    pub fn set_cursor_pos<N: Num + Display>(x: N, y: N) {
20        print!("\x1B[{};{}H", y, x);
21    }
22    pub fn move_cursor_up() {
23        print!("\x1B[1A");
24    }
25    pub fn move_cursor_down() {
26        print!("\x1B[1B");
27    }
28    pub fn move_cursor_left() {
29        print!("\x1B[1D");
30    }
31    pub fn move_cursor_right() {
32        print!("\x1B[1C");
33    }
34    pub fn move_cursor_up_by<N: Num + Display>(n: N) {
35        print!("\x1B[{}A", n);
36    }
37    pub fn move_cursor_down_by<N: Num + Display>(n: N) {
38        print!("\x1B[{}B", n);
39    }
40    pub fn move_cursor_left_by<N: Num + Display>(n: N) {
41        print!("\x1B[{}D", n);
42    }
43    pub fn move_cursor_right_by<N: Num + Display>(n: N) {
44        print!("\x1B[{}C", n);
45    }
46    pub fn move_cursor_by<N>(x: N, y: N)
47    where
48        N: Num + Display + PartialOrd + FromPrimitive + std::ops::Neg<Output = N>,
49    {
50        if x >= FromPrimitive::from_i32(0).unwrap() {
51            if y >= FromPrimitive::from_i32(0).unwrap() {
52                print!("\x1B[{}C\x1B[{}A", x, y)
53            } else {
54                print!("\x1B[{}C\x1B[{}B", x, -y)
55            }
56        } else {
57            if y >= FromPrimitive::from_i32(0).unwrap() {
58                print!("\x1B[{}D\x1B[{}A", -x, y)
59            } else {
60                print!("\x1B[{}D\x1B[{}B", -x, -y)
61            }
62        }
63    }
64    pub fn print_at<N: Num + Display, T: Display>(x: N, y: N, s: T) {
65        EasyTerm::set_cursor_pos(x, y);
66        print!("{}", s);
67        std::io::stdout().flush().unwrap();
68    }
69}
70
71#[cfg(test)]
72mod tests {
73    #[test]
74    fn it_works() {
75        let result = 2 + 2;
76        assert_eq!(result, 4);
77    }
78}