workflow_terminal/
cursor.rs

1//! Cursor helper structs (from [https://crates.io/crates/termion](https://crates.io/crates/termion))
2
3use numtoa::NumToA;
4use std::fmt;
5
6/// Move cursor left.
7#[derive(Copy, Clone, PartialEq, Eq)]
8pub struct Left(pub u16);
9
10impl From<Left> for String {
11    fn from(this: Left) -> String {
12        let mut buf = [0u8; 20];
13        ["\x1B[", this.0.numtoa_str(10, &mut buf), "D"].concat()
14    }
15}
16
17impl fmt::Display for Left {
18    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
19        write!(f, "\x1B[{}D", self.0)
20    }
21}
22
23/// Move cursor right.
24#[derive(Copy, Clone, PartialEq, Eq)]
25pub struct Right(pub u16);
26
27impl From<Right> for String {
28    fn from(this: Right) -> String {
29        let mut buf = [0u8; 20];
30        ["\x1B[", this.0.numtoa_str(10, &mut buf), "C"].concat()
31    }
32}
33
34impl fmt::Display for Right {
35    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
36        write!(f, "\x1B[{}C", self.0)
37    }
38}
39
40/// Move cursor up.
41#[derive(Copy, Clone, PartialEq, Eq)]
42pub struct Up(pub u16);
43
44impl From<Up> for String {
45    fn from(this: Up) -> String {
46        let mut buf = [0u8; 20];
47        ["\x1B[", this.0.numtoa_str(10, &mut buf), "A"].concat()
48    }
49}
50
51impl fmt::Display for Up {
52    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
53        write!(f, "\x1B[{}A", self.0)
54    }
55}
56
57/// Move cursor down.
58#[derive(Copy, Clone, PartialEq, Eq)]
59pub struct Down(pub u16);
60
61impl From<Down> for String {
62    fn from(this: Down) -> String {
63        let mut buf = [0u8; 20];
64        ["\x1B[", this.0.numtoa_str(10, &mut buf), "B"].concat()
65    }
66}
67
68impl fmt::Display for Down {
69    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
70        write!(f, "\x1B[{}B", self.0)
71    }
72}
73
74/// Goto some position ((1,1)-based).
75#[derive(Copy, Clone, PartialEq, Eq)]
76pub struct Goto(pub u16, pub u16);
77
78impl From<Goto> for String {
79    fn from(this: Goto) -> String {
80        let (mut x, mut y) = ([0u8; 20], [0u8; 20]);
81        [
82            "\x1B[",
83            this.1.numtoa_str(10, &mut x),
84            ";",
85            this.0.numtoa_str(10, &mut y),
86            "H",
87        ]
88        .concat()
89    }
90}
91
92impl Default for Goto {
93    fn default() -> Goto {
94        Goto(1, 1)
95    }
96}
97
98impl fmt::Display for Goto {
99    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
100        debug_assert!(self != &Goto(0, 0), "Goto is one-based.");
101        write!(f, "\x1B[{};{}H", self.1, self.0)
102    }
103}