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