console_utils/
control.rs

1//! Control Utilities
2//!
3//! This module provides functions for controlling the console, including flushing the output buffer,
4//! clearing lines, and moving the cursor in various directions.
5use std::io::{self, Write};
6
7/// Flushes the output buffer, ensuring that all content is written to the console.
8pub fn flush() {
9    io::stdout().flush().unwrap();
10}
11
12/// Clears the current line in the console.
13///
14/// This function uses ANSI escape codes to clear the entire line and move the cursor to the
15/// beginning of the line.
16pub fn clear_line() {
17    print!("\r\x1b[2K");
18    flush();
19}
20
21/// Clears the `i` lines in the console.
22pub fn clear_lines(i: usize) {
23    for _ in 0..i {
24        print!("\r\x1b[2K");
25        flush();
26    }
27}
28
29/// Struct for ensuring and changing cursor visibility.
30#[derive(Default)]
31pub struct Visibility;
32
33impl Visibility {
34    pub fn new() -> Self {
35        Self
36    }
37
38    /// Hide the cursor via an ASCII escape sequence.
39    pub fn hide_cursor(&self) {
40        print!("\x1B[?25l");
41        flush();
42    }
43
44    /// Show the cursor via an ASCII escape sequence.
45    pub fn show_cursor(&self) {
46        print!("\x1B[?25h");
47        flush();
48    }
49}
50
51impl Drop for Visibility {
52    fn drop(&mut self) {
53        Visibility::show_cursor(self);
54    }
55}
56
57/// Moves the cursor down by the specified number of lines.
58///
59/// # Arguments
60///
61/// * `n` - The number of lines to move the cursor down.
62pub fn move_cursor_down(n: usize) {
63    if n > 0 {
64        print!("\x1b[{}B", n);
65        flush();
66    }
67}
68
69/// Moves the cursor up by the specified number of lines.
70///
71/// # Arguments
72///
73/// * `n` - The number of lines to move the cursor up.
74pub fn move_cursor_up(n: usize) {
75    if n > 0 {
76        print!("\x1b[{}A", n);
77        flush();
78    }
79}
80
81/// Moves the cursor to the left by the specified number of characters.
82///
83/// # Arguments
84///
85/// * `n` - The number of characters to move the cursor to the left.
86pub fn move_cursor_left(n: usize) {
87    if n > 0 {
88        print!("\x1b[{}D", n);
89        flush();
90    }
91}
92
93/// Moves the cursor to the right by the specified number of characters.
94///
95/// # Arguments
96///
97/// * `n` - The number of characters to move the cursor to the right.
98pub fn move_cursor_right(n: usize) {
99    if n > 0 {
100        print!("\x1b[{}C", n);
101        flush();
102    }
103}
104
105/// Moves the cursor to the specified position on the console.
106///
107/// # Arguments
108///
109/// * `x` - The horizontal position (column) to move the cursor to.
110/// * `y` - The vertical position (row) to move the cursor to.
111pub fn move_cursor_to(x: usize, y: usize) {
112    print!("\x1B[{};{}H", y + 1, x + 1);
113    flush();
114}