From af818b3b58a792e216c503ff9f421bc2bb0c8bb5 Mon Sep 17 00:00:00 2001 From: mat Date: Wed, 29 Nov 2023 19:51:34 -0600 Subject: [PATCH] simplify ServerAddress serde implementations --- azalea-protocol/src/lib.rs | 32 ++++++++++++++------------------ 1 file changed, 14 insertions(+), 18 deletions(-) diff --git a/azalea-protocol/src/lib.rs b/azalea-protocol/src/lib.rs index 973564eb6..38acd7051 100644 --- a/azalea-protocol/src/lib.rs +++ b/azalea-protocol/src/lib.rs @@ -76,30 +76,26 @@ impl Display for ServerAddress { } } -/// -/// Serde Deserialization for ServerAddress -/// This is necessary for config file usage -/// We are not using TryFrom because we want to use the serde error system -/// +/// Serde deserialization for ServerAddress. This is useful for config file +/// usage. impl<'de> serde::Deserialize<'de> for ServerAddress { - fn deserialize(deserializer: D) -> Result where D: serde::Deserializer<'de> { + fn deserialize(deserializer: D) -> Result + where + D: serde::Deserializer<'de>, + { let string = String::deserialize(deserializer)?; - let mut parts = string.split(':'); - let host = parts.next().ok_or(serde::de::Error::custom("No host specified"))?.to_string(); - // default the port to 25565 - let port = parts.next().unwrap_or("25565"); - let port = u16::from_str(port).map_err(|_| serde::de::Error::custom("Invalid port specified"))?; - Ok(ServerAddress { host, port }) + ServerAddress::try_from(string.as_str()).map_err(serde::de::Error::custom) } } -/// -/// Serde Serialization for ServerAddress -/// Pretty much like impl Display -/// +/// Serde serialization for ServerAddress. This uses the Display impl, so it +/// will serialize to a string. impl serde::Serialize for ServerAddress { - fn serialize(&self, serializer: S) -> Result where S: serde::Serializer { - serializer.serialize_str(&format!("{}:{}", self.host, self.port)) + fn serialize(&self, serializer: S) -> Result + where + S: serde::Serializer, + { + serializer.serialize_str(&self.to_string()) } }