1
//! Clipboard copy through the terminal's OSC 52 escape.
2

            
3
use std::fmt;
4

            
5
use base64::prelude::{BASE64_STANDARD, Engine};
6

            
7
/// Largest base64 payload sent; terminals such as xterm drop longer OSC 52 sequences.
8
pub const MAX_COPY_BASE64: usize = 100_000;
9

            
10
/// The text was longer than [`MAX_COPY_BASE64`] once encoded.
11
#[derive(Debug, PartialEq, Eq)]
12
pub struct TooLarge(pub usize);
13

            
14
impl fmt::Display for TooLarge {
15
2
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
16
2
        write!(
17
2
            f,
18
2
            "CSV too large to copy ({} bytes encoded, limit {MAX_COPY_BASE64})",
19
2
            self.0
20
        )
21
2
    }
22
}
23

            
24
/// The OSC 52 sequence that puts `text` on the clipboard of the terminal reading it.
25
///
26
/// # Errors
27
/// [`TooLarge`] when the encoded text exceeds [`MAX_COPY_BASE64`].
28
5
pub fn osc52(text: &str) -> Result<Vec<u8>, TooLarge> {
29
5
    let encoded = BASE64_STANDARD.encode(text);
30
5
    if encoded.len() > MAX_COPY_BASE64 {
31
2
        return Err(TooLarge(encoded.len()));
32
3
    }
33
3
    Ok(format!("\x1b]52;c;{encoded}\x07").into_bytes())
34
5
}
35

            
36
#[cfg(test)]
37
mod tests;