use ghast_inventory::Stack;
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub struct BookEdit {
pub slot: i32,
pub pages: Vec<String>,
pub title: Option<String>,
pub stack: Option<Stack>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum BookError {
NoBook,
TooManyPages,
EmptyTitle,
OffHand,
}
impl std::fmt::Display for BookError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(match self {
BookError::NoBook => "the hand holds no book and quill",
BookError::TooManyPages => "too many pages for this version",
BookError::EmptyTitle => "the title is blank",
BookError::OffHand => "this version has no off hand",
})
}
}
impl std::error::Error for BookError {}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum BookRules {
Legacy18,
Legacy112,
Stack116,
Pages,
}
impl BookRules {
#[must_use]
pub const fn max_pages(self) -> usize {
match self {
BookRules::Legacy18 | BookRules::Legacy112 => 50,
BookRules::Stack116 | BookRules::Pages => 100,
}
}
#[must_use]
pub const fn max_page_len(self) -> usize {
match self {
BookRules::Legacy18 | BookRules::Legacy112 => 255,
BookRules::Stack116 => 1023,
BookRules::Pages => 1024,
}
}
#[must_use]
pub const fn max_title_len(self) -> usize {
match self {
BookRules::Legacy18 | BookRules::Legacy112 => 16,
BookRules::Stack116 | BookRules::Pages => 15,
}
}
}
#[must_use]
pub(crate) fn page(s: &str, max: usize) -> String {
let p: String = s
.chars()
.filter(|&c| c == '\n' || crate::sign::allowed_char(c))
.collect();
crate::version::truncate_utf16(&p, max).to_owned()
}
pub(crate) fn prepare(
rules: BookRules,
pages: &[&str],
title: Option<&str>,
) -> Result<(Vec<String>, Option<String>), BookError> {
if pages.len() > rules.max_pages() {
return Err(BookError::TooManyPages);
}
let mut p: Vec<String> = pages
.iter()
.map(|s| page(s, rules.max_page_len()))
.collect();
let title = match title {
Some(t) => {
let t: String = t
.chars()
.filter(|&c| crate::sign::allowed_char(c))
.collect();
let t = crate::version::truncate_utf16(&t, rules.max_title_len()).trim();
if t.is_empty() {
return Err(BookError::EmptyTitle);
}
Some(t.to_owned())
}
None => None,
};
match rules {
BookRules::Legacy18 | BookRules::Legacy112 => {
if p.is_empty() {
p.push(String::new());
}
while p.len() > 1 && p.last().is_some_and(String::is_empty) {
p.pop();
}
}
BookRules::Pages if title.is_some() => {}
BookRules::Stack116 | BookRules::Pages => {
while p.last().is_some_and(String::is_empty) {
p.pop();
}
}
}
Ok((p, title))
}
pub(crate) fn nbt_stack(
rules: BookRules,
held: &Stack,
pages: &[String],
title: Option<&str>,
author: &str,
written_book: i32,
) -> Stack {
use ghast_protocol::nbt::{Compound, List, NamedTag, RawNbt, Tag, tag};
let mut root = held
.nbt()
.and_then(|n| n.parse().ok().flatten())
.and_then(|t| match t.tag {
Tag::Compound(c) => Some(c),
_ => None,
})
.unwrap_or_default();
let put = |c: &mut Compound, k: &str, v: Tag| {
if let Some(e) = c.0.iter_mut().find(|(n, _)| n == k) {
e.1 = v;
} else {
c.0.push((k.to_owned(), v));
}
};
let json = rules == BookRules::Legacy18 && title.is_some();
if rules != BookRules::Stack116 || !pages.is_empty() {
let items = pages
.iter()
.map(|p| {
Tag::String(if json {
crate::sign::gson_string(p, usize::MAX)
} else {
p.clone()
})
})
.collect();
put(
&mut root,
"pages",
Tag::List(List {
elem_type: tag::STRING,
items,
}),
);
}
if let Some(t) = title {
put(&mut root, "author", Tag::String(author.to_owned()));
put(&mut root, "title", Tag::String(t.to_owned()));
}
let nbt = RawNbt::from_named(&NamedTag {
name: String::new(),
tag: Tag::Compound(root),
})
.ok();
Stack::new(
if json { written_book } else { held.id() },
held.count(),
held.damage(),
)
.with_nbt(nbt)
}
#[cfg(ghast_modern)]
pub(crate) fn modern_stack(held: &Stack, pages: &[String], protocol: i32) -> Option<Stack> {
use bytes::BufMut;
use ghast_protocol::types::slot::v775::ComponentPatch;
let ty = if protocol >= 777 { 56 } else { 54 };
let mut v = bytes::BytesMut::new();
let varint = |v: &mut bytes::BytesMut, mut n: u32| loop {
if n < 0x80 {
v.put_u8(n as u8);
break;
}
v.put_u8((n as u8 & 0x7f) | 0x80);
n >>= 7;
};
varint(&mut v, u32::try_from(pages.len()).ok()?);
for p in pages {
varint(&mut v, u32::try_from(p.len()).ok()?);
v.put_slice(p.as_bytes());
v.put_u8(0); }
let old = held.components();
let mut added: Vec<(i32, bytes::Bytes)> = old
.map(|c| c.iter().filter(|(t, _)| *t != ty).collect())
.unwrap_or_default();
added.push((ty, v.freeze()));
let removed: Vec<i32> = old
.map(|c| c.removed().filter(|t| *t != ty).collect())
.unwrap_or_default();
let parts: Vec<(i32, &[u8])> = added.iter().map(|(t, b)| (*t, &b[..])).collect();
let patch = match protocol {
775 => ComponentPatch::from_parts(&parts, &removed),
776 => ComponentPatch::from_parts_776(&parts, &removed),
_ => ComponentPatch::from_parts_777(&parts, &removed),
};
Some(
held.clone()
.with_data(ghast_inventory::ItemData::Components(Box::new(patch))),
)
}
pub(crate) fn book_items(data: crate::version::DataSet) -> Option<(i32, i32)> {
#[allow(unused_imports)]
use crate::version::DataSet;
#[allow(unused_macros)]
macro_rules! by_name {
($m:path) => {{
use $m as d;
Some((
i32::from(d::Item::from_name("writable_book")?.id()),
i32::from(d::Item::from_name("written_book")?.id()),
))
}};
}
match data {
#[cfg(feature = "v1_8")]
DataSet::V1_8 => Some((386, 387)),
#[cfg(feature = "v1_12_2")]
DataSet::V1_12 => Some((386, 387)),
#[cfg(feature = "v1_16_5")]
DataSet::V1_16_5 => by_name!(ghast_data::v1_16_5),
#[cfg(feature = "v26_1")]
DataSet::V26_1 => by_name!(ghast_data::v26_1),
#[cfg(feature = "v26_2")]
DataSet::V26_2 => by_name!(ghast_data::v26_2),
#[cfg(feature = "v26_3")]
DataSet::V26_3 => by_name!(ghast_data::v26_3),
#[allow(unreachable_patterns)]
_ => None,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn pages_and_titles() {
let (p, t) = prepare(BookRules::Legacy18, &["a§b\nc", "", ""], Some(" Ti§tle ")).unwrap();
assert_eq!(p, ["ab\nc"]);
assert_eq!(t.as_deref(), Some("Title"));
let (p, _) = prepare(BookRules::Legacy112, &[], None).unwrap();
assert_eq!(p, [""]);
let (p, _) = prepare(BookRules::Stack116, &["", ""], None).unwrap();
assert!(p.is_empty());
let (p, _) = prepare(BookRules::Pages, &["x", ""], Some("t")).unwrap();
assert_eq!(p, ["x", ""]);
let (p, _) = prepare(BookRules::Pages, &["x", ""], None).unwrap();
assert_eq!(p, ["x"]);
assert_eq!(
prepare(BookRules::Pages, &["x"], Some(" ")),
Err(BookError::EmptyTitle)
);
let many = vec!["p"; 51];
assert_eq!(
prepare(BookRules::Legacy18, &many, None),
Err(BookError::TooManyPages)
);
assert!(prepare(BookRules::Stack116, &many, None).is_ok());
let long = "y".repeat(2000);
let (p, t) = prepare(BookRules::Stack116, &[&long], Some(&long)).unwrap();
assert_eq!((p[0].len(), t.unwrap().len()), (1023, 15));
let (p, t) = prepare(BookRules::Legacy112, &[&long], Some(&long)).unwrap();
assert_eq!((p[0].len(), t.unwrap().len()), (255, 16));
let (p, _) = prepare(BookRules::Pages, &[&long], None).unwrap();
assert_eq!(p[0].len(), 1024);
}
}