From a1dd77c8fdd5b5d13bc20c60a66bda4591c5cd6a Mon Sep 17 00:00:00 2001 From: Matthias Schiffer Date: Fri, 5 Jan 2024 03:03:53 +0100 Subject: [PATCH] world/sign: implement Display for SignText --- src/world/json_text.rs | 18 +++++++++++++++++- src/world/sign.rs | 43 +++++++++++++++++++++++++++++++++++++++++- 2 files changed, 59 insertions(+), 2 deletions(-) diff --git a/src/world/json_text.rs b/src/world/json_text.rs index 0f72dcc..a153179 100644 --- a/src/world/json_text.rs +++ b/src/world/json_text.rs @@ -1,6 +1,6 @@ //! Newtype and helper methods for handling Minecraft Raw JSON Text -use std::{collections::VecDeque, sync::Arc}; +use std::{collections::VecDeque, fmt::Display, sync::Arc}; use serde::{Deserialize, Serialize}; @@ -51,6 +51,12 @@ impl FormattedText { } } +impl Display for FormattedText { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + self.text.fmt(f) + } +} + /// A tree of [FormattedText] nodes /// /// Each node including the root has a `text` and a list of children (`extra`). @@ -87,6 +93,16 @@ impl FormattedTextList { } } +impl Display for FormattedTextList { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + for text in &self.0 { + text.fmt(f)?; + } + + Ok(()) + } +} + /// Raw deserialized [JSONText] /// /// A [JSONText] can contain various different JSON types. diff --git a/src/world/sign.rs b/src/world/sign.rs index 43cac47..616f7fa 100644 --- a/src/world/sign.rs +++ b/src/world/sign.rs @@ -1,6 +1,6 @@ //! Processing of sign text -use std::sync::Arc; +use std::{fmt::Display, sync::Arc}; use serde::{Deserialize, Serialize}; @@ -89,3 +89,44 @@ impl SignText { self.0.iter().all(|line| line.is_empty()) } } + +impl Display for SignText { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let mut iter = self.0.iter(); + + let Some(first) = iter.next() else { + return Ok(()); + }; + first.fmt(f)?; + + for text in iter { + f.write_str("\n")?; + text.fmt(f)?; + } + + Ok(()) + } +} + +#[cfg(test)] +mod test { + use super::*; + + fn formatted_text(text: &str) -> FormattedText { + FormattedText { + text: text.to_string(), + ..Default::default() + } + } + + #[test] + fn test_sign_text_display() { + let sign_text = SignText(vec![ + FormattedTextList(vec![formatted_text("a"), formatted_text("b")]), + FormattedTextList(vec![formatted_text("c")]), + FormattedTextList(vec![formatted_text("d")]), + FormattedTextList(vec![formatted_text("e")]), + ]); + assert_eq!("ab\nc\nd\ne", sign_text.to_string()); + } +}