Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Serde support for 'ServerAddress' #115

Merged
merged 1 commit into from
Nov 30, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions azalea-protocol/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
Loading