summaryrefslogtreecommitdiffstats
path: root/src/utils/mod.rs
blob: 8b5dae639702a8017f1aa53e924deb604451decf (plain) (blame)
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
mod tiktoken;

pub use self::tiktoken::{cl100k_base_singleton, count_tokens, text_to_tokens, tokens_to_text};

use arboard::Clipboard;
use chrono::prelude::*;
use crossterm::style::{Color, Stylize};
use std::io::{stdout, Write};

#[macro_export]
macro_rules! print_now {
    ($($arg:tt)*) => {
        $crate::utils::print_now(&format!($($arg)*))
    };
}

pub fn print_now<T: ToString>(text: &T) {
    print!("{}", text.to_string());
    let _ = stdout().flush();
}

pub fn now() -> String {
    let now = Local::now();
    now.to_rfc3339_opts(SecondsFormat::Secs, false)
}

#[allow(unused)]
pub fn emphasis(text: &str) -> String {
    text.stylize().with(Color::White).to_string()
}

pub fn mask_text(text: &str, head: usize, tail: usize) -> String {
    if text.len() <= head + tail {
        return text.to_string();
    }
    format!("{}...{}", &text[0..head], &text[text.len() - tail..])
}

pub fn copy(src: &str) -> Result<(), arboard::Error> {
    let mut clipboard = Clipboard::new()?;
    clipboard.set_text(src)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_mask_text() {
        assert_eq!(mask_text("123456", 3, 4), "123456");
        assert_eq!(mask_text("1234567", 3, 4), "1234567");
        assert_eq!(mask_text("12345678", 3, 4), "123...5678");
        assert_eq!(mask_text("12345678", 4, 3), "1234...678");
    }
}