// Copyright Marcus Del Favero 2025
// Licensed under the GNU AGPLv3 with an exception, see `README.md` for details
use std::fmt::Write;

/*
 * Escapes ANSI escape codes as they allow clients to do fucky stuff on the
 * server's terminal through logs, such as clearing the screen and changing text
 * colour. Probably not too dangerous but it's good to be careful.
 */
pub fn singleline(s: &str) -> String {
	escape(s, |ch| ch < 0x20 as char)
}

pub fn multiline(s: &str) -> String {
	escape(s, |ch| ch < 0x20 as char && ch != '\n' && ch != '\r')
}

fn escape(s: &str, first_cmp: fn(char) -> bool) -> String {
	let mut ret = String::with_capacity(s.len());
	for ch in s.chars() {
		if first_cmp(ch) {
			let _ = write!(ret, "{}", ch.escape_default());
		} else if ch < 0x7f as char || ch.is_alphanumeric() {
			ret.push(ch);
		} else {
			let _ = write!(ret, "{}", ch.escape_default());
		}
	}
	ret
}
