use ghast_protocol::BlockPos;
pub const MAX_LINE_LENGTH: usize = 384;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct SignEditor {
pub pos: BlockPos,
pub front: bool,
}
impl SignEditor {
#[must_use]
pub const fn new(pos: BlockPos, front: bool) -> Self {
SignEditor { pos, front }
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum SignCloseReason {
Replaced,
BlockGone,
TooFar,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum SignEvent {
Opened(SignEditor),
Closed(SignEditor, SignCloseReason),
Ignored(SignEditor),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum SignError {
NotOpen,
TooManyLines,
}
impl std::fmt::Display for SignError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(match self {
SignError::NotOpen => "no sign editor is open",
SignError::TooManyLines => "a sign has four lines",
})
}
}
impl std::error::Error for SignError {}
#[inline]
#[must_use]
pub const fn allowed_char(c: char) -> bool {
c != '§' && c >= ' ' && c != '\u{7f}'
}
#[must_use]
pub fn vanilla_line(line: &str) -> String {
let s: String = line.chars().filter(|&c| allowed_char(c)).collect();
crate::version::truncate_utf16(&s, MAX_LINE_LENGTH).to_owned()
}
#[cfg(feature = "v1_8")]
pub(crate) fn legacy_json_line(line: &str) -> String {
gson_string(line, MAX_LINE_LENGTH)
}
pub(crate) fn gson_string(line: &str, max: usize) -> String {
let mut out = String::with_capacity(line.len() + 2);
out.push('"');
let mut units = 1usize;
for c in line.chars() {
let mut buf = [0u8; 12];
let esc: &str = match c {
'"' => "\\\"",
'\\' => "\\\\",
'\t' => "\\t",
'\u{8}' => "\\b",
'\n' => "\\n",
'\r' => "\\r",
'\u{c}' => "\\f",
'<' | '>' | '&' | '=' | '\'' | '\u{2028}' | '\u{2029}' | '\0'..='\u{1f}' => {
use std::io::Write;
let mut w = &mut buf[..];
let _ = write!(w, "\\u{:04x}", c as u32);
let n = 12 - w.len();
std::str::from_utf8(&buf[..n]).unwrap_or("")
}
_ => c.encode_utf8(&mut buf),
};
let add = esc.encode_utf16().count();
if units.saturating_add(add + 1) > max {
break;
}
units += add;
out.push_str(esc);
}
out.push('"');
out
}
pub(crate) fn lines(given: &[&str]) -> Result<Box<[String; 4]>, SignError> {
if given.len() > 4 {
return Err(SignError::TooManyLines);
}
let mut out: Box<[String; 4]> = Box::default();
for (o, l) in out.iter_mut().zip(given) {
*o = vanilla_line(l);
}
Ok(out)
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct OpenSign {
pub editor: SignEditor,
pub check_first_tick: bool,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum SignRules {
Legacy {
json: bool,
},
FirstTickCheck,
Sided,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn filters_like_the_screen() {
assert_eq!(vanilla_line("a§1b\tc\u{7f}d é"), "a1bcd é");
let long = "x".repeat(500);
assert_eq!(vanilla_line(&long).len(), MAX_LINE_LENGTH);
}
#[cfg(feature = "v1_8")]
#[test]
fn gson_escapes() {
assert_eq!(legacy_json_line(""), "\"\"");
assert_eq!(legacy_json_line("Hello"), "\"Hello\"");
assert_eq!(
legacy_json_line("a\"b\\c<d>&='"),
"\"a\\\"b\\\\c\\u003cd\\u003e\\u0026\\u003d\\u0027\""
);
assert_eq!(legacy_json_line("\u{2028}é"), "\"\\u2028é\"");
let j = legacy_json_line(&"<".repeat(200));
assert!(
j.len() <= MAX_LINE_LENGTH && j.ends_with('"'),
"{}",
j.len()
);
assert_eq!(j.len(), 2 + 6 * 63);
}
#[test]
fn four_lines() {
let l = lines(&["a", "b"]).unwrap();
assert_eq!(
*l,
["a".to_owned(), "b".into(), String::new(), String::new()]
);
assert_eq!(lines(&["", "", "", "", ""]), Err(SignError::TooManyLines));
}
}