Skip to content

Commit

Permalink
feat: add support for fancy strings
Browse files Browse the repository at this point in the history
  • Loading branch information
doinkythederp authored Jan 3, 2023
1 parent b28a87e commit 57dcca3
Show file tree
Hide file tree
Showing 2 changed files with 80 additions and 1 deletion.
77 changes: 77 additions & 0 deletions src/parse.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
use serde::Deserialize;

use self::fancy_string::FancyText;

#[derive(Deserialize, Debug)]
pub struct ServerPingInfo {
pub version: Option<ServerVersion>,
Expand Down Expand Up @@ -32,6 +34,7 @@ pub struct ServerPlayersSample {
#[derive(Deserialize, Debug)]
pub struct ServerDescription {
pub text: String,
pub extra: Option<FancyText>,
}

#[derive(Deserialize, Debug)]
Expand All @@ -47,3 +50,77 @@ impl std::str::FromStr for ServerPingInfo {
serde_json::from_str(json)
}
}

pub mod fancy_string {
use serde::Deserialize;

#[derive(Debug, Deserialize)]
pub struct FancyText(pub Vec<FancyTextComponent>);

impl FancyText {
pub fn to_markdown(&self) -> String {
let mut builder = String::with_capacity(10);
for component in &self.0 {
builder += &component.to_markdown();
}
builder
}
}

#[derive(Debug, Deserialize)]
#[serde(untagged)]
pub enum FancyTextComponent {
ColorText {
color: String,
text: String,
},
PlainText {
text: String,
},
NestedText {
#[serde(default)]
bold: bool,
#[serde(default)]
italic: bool,
#[serde(default)]
underlined: bool,
#[serde(default)]
strikethrough: bool,
#[serde(default)]
obfuscated: bool,
extra: FancyText,
},
}

impl FancyTextComponent {
pub fn to_markdown(&self) -> String {
match self {
FancyTextComponent::ColorText { color: _, text } => text.clone(),
FancyTextComponent::PlainText { text } => text.clone(),
FancyTextComponent::NestedText {
bold,
italic,
underlined,
strikethrough,
obfuscated: _,
extra,
} => {
let mut text = extra.to_markdown();
if *bold {
text = format!("**{text}**");
}
if *italic {
text = format!("*{text}*");
}
if *underlined {
text = format!("__{text}__");
}
if *strikethrough {
text = format!("~~{text}~~");
}
text
}
}
}
}
}
4 changes: 3 additions & 1 deletion src/protocol.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,8 @@ pub mod error {
ConnectionClosed,
#[error("invalid response from server")]
InvalidResponse,
#[error("failed to parse server response")]
Parse(#[from] serde_json::Error),
#[error("server did not respond in time")]
Timeout,
}
Expand Down Expand Up @@ -312,7 +314,7 @@ impl SlpProtocol {
Frame::StatusResponse { json } => json,
_ => return Err(PingError::InvalidResponse),
};
ServerPingInfo::from_str(&frame_data).map_err(|_| PingError::InvalidResponse)
ServerPingInfo::from_str(&frame_data).map_err(|err| PingError::Parse(err))
}

#[cfg(feature = "simple")]
Expand Down

0 comments on commit 57dcca3

Please sign in to comment.