use std::io::Write;
pub fn copy(text: &str) -> std::io::Result<()> {
let payload = format!("\x1b]52;c;{}\x07", base64(text.as_bytes()));
let mut out = std::io::stdout();
out.write_all(payload.as_bytes())?;
out.flush()
}
fn base64(bytes: &[u8]) -> String {
const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4);
for chunk in bytes.chunks(3) {
let b = [
chunk[0],
chunk.get(1).copied().unwrap_or(0),
chunk.get(2).copied().unwrap_or(0),
];
let triple = (u32::from(b[0]) << 16) | (u32::from(b[1]) << 8) | u32::from(b[2]);
let indices = [
(triple >> 18) & 0x3f,
(triple >> 12) & 0x3f,
(triple >> 6) & 0x3f,
triple & 0x3f,
];
for (position, index) in indices.iter().enumerate() {
if position <= chunk.len() {
out.push(ALPHABET[*index as usize] as char);
} else {
out.push('=');
}
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn base64_matches_the_published_test_vectors() {
for (input, want) in [
("", ""),
("f", "Zg=="),
("fo", "Zm8="),
("foo", "Zm9v"),
("foob", "Zm9vYg=="),
("fooba", "Zm9vYmE="),
("foobar", "Zm9vYmFy"),
] {
assert_eq!(base64(input.as_bytes()), want, "encoding {input:?}");
}
}
#[test]
fn a_real_link_round_trips_through_the_encoder() {
let link = "https://arstechnica.com/science/2026/07/if-a-quantum-computer/";
let encoded = base64(link.as_bytes());
assert_eq!(
decode(&encoded),
link.as_bytes(),
"the link did not survive encoding"
);
}
#[test]
fn multi_byte_text_encodes_as_bytes() {
for text in ["日本語", "café", "🌞", "a🌞b"] {
assert_eq!(decode(&base64(text.as_bytes())), text.as_bytes(), "{text}");
}
}
#[test]
fn the_escape_sequence_is_shaped_the_way_terminals_expect() {
let payload = format!("\x1b]52;c;{}\x07", base64(b"hi"));
assert!(payload.starts_with("\x1b]52;c;"), "OSC 52 introducer");
assert!(payload.ends_with('\x07'), "BEL terminator");
assert_eq!(&payload[7..payload.len() - 1], "aGk=");
}
fn decode(text: &str) -> Vec<u8> {
const ALPHABET: &[u8; 64] =
b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
let mut bits = Vec::new();
for c in text.bytes().filter(|c| *c != b'=') {
let index = ALPHABET
.iter()
.position(|a| *a == c)
.expect("valid base64 alphabet");
for shift in (0..6).rev() {
bits.push((index >> shift) & 1);
}
}
bits.as_chunks::<8>()
.0
.iter()
.map(|byte| byte.iter().fold(0u8, |acc, bit| (acc << 1) | *bit as u8))
.collect()
}
}