1
2
Fork 0
mirror of https://github.com/mat-1/azalea.git synced 2025-08-02 14:26:04 +00:00

serde support for 'ServerAddress' (#115)

This commit is contained in:
1zuna 2023-11-30 02:51:19 +01:00 committed by GitHub
parent 8fb58b7754
commit 87c2bc2e5d
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -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;