diff options
| author | 1zuna <1zuna@ccbluex.net> | 2023-11-30 02:51:19 +0100 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2023-11-29 19:51:19 -0600 |
| commit | 87c2bc2e5d86a0bb0e52edbed60b3ed3ad11e1bd (patch) | |
| tree | 3343acbd3f33e93c12cc0ee3625a206b3f540e02 /azalea-protocol/src | |
| parent | 8fb58b7754797b139ead1c68ece4ec1bf411455c (diff) | |
| download | azalea-drasl-87c2bc2e5d86a0bb0e52edbed60b3ed3ad11e1bd.tar.xz | |
serde support for 'ServerAddress' (#115)
Diffstat (limited to 'azalea-protocol/src')
| -rw-r--r-- | azalea-protocol/src/lib.rs | 27 |
1 files changed, 27 insertions, 0 deletions
diff --git a/azalea-protocol/src/lib.rs b/azalea-protocol/src/lib.rs index aac449c9..973564eb 100644 --- a/azalea-protocol/src/lib.rs +++ b/azalea-protocol/src/lib.rs @@ -76,6 +76,33 @@ 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 +/// +impl<'de> serde::Deserialize<'de> for ServerAddress { + fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> 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 }) + } +} + +/// +/// Serde Serialization for ServerAddress +/// Pretty much like impl Display +/// +impl serde::Serialize for ServerAddress { + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer { + serializer.serialize_str(&format!("{}:{}", self.host, self.port)) + } +} + #[cfg(test)] mod tests { use std::io::Cursor; |
