protocol: change UUID from_str to implement FromStr trait (should_implement_trait)

This commit is contained in:
ice_iix 2020-06-29 17:33:50 -07:00
parent 783e437397
commit 66a787a535
2 changed files with 19 additions and 8 deletions

View File

@ -419,11 +419,21 @@ impl Serializable for f64 {
#[derive(Debug, PartialEq, Eq, Hash, Clone)]
pub struct UUID(u64, u64);
impl UUID {
pub fn from_str(s: &str) -> UUID {
// TODO: Panics aren't the best idea here
#[derive(Debug)]
pub struct UUIDParseError;
impl std::error::Error for UUIDParseError {}
impl fmt::Display for UUIDParseError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Invalid UUID format")
}
}
impl std::str::FromStr for UUID {
type Err = UUIDParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
if s.len() != 36 {
panic!("Invalid UUID format");
return Err(UUIDParseError {});
}
let mut parts = hex::decode(&s[..8]).unwrap();
parts.extend_from_slice(&hex::decode(&s[9..13]).unwrap());
@ -436,7 +446,7 @@ impl UUID {
high |= (parts[i] as u64) << (56 - i * 8);
low |= (parts[i + 8] as u64) << (56 - i * 8);
}
UUID(high, low)
Ok(UUID(high, low))
}
}

View File

@ -32,6 +32,7 @@ use rsa_public_encrypt_pkcs1;
use serde_json;
use std::collections::HashMap;
use std::hash::BuildHasherDefault;
use std::str::FromStr;
use std::sync::mpsc;
use std::sync::{Arc, RwLock};
use std::thread;
@ -158,7 +159,7 @@ impl Server {
return Ok(Server::new(
protocol_version,
forge_mods,
protocol::UUID::from_str(&val.uuid),
protocol::UUID::from_str(&val.uuid).unwrap(),
resources,
Some(write),
Some(rx),
@ -230,7 +231,7 @@ impl Server {
}
protocol::packet::Packet::LoginSuccess_String(val) => {
debug!("Login: {} {}", val.username, val.uuid);
uuid = protocol::UUID::from_str(&val.uuid);
uuid = protocol::UUID::from_str(&val.uuid).unwrap();
read.state = protocol::State::Play;
write.state = protocol::State::Play;
break;
@ -1368,7 +1369,7 @@ impl Server {
) {
self.on_player_spawn(
spawn.entity_id.0,
protocol::UUID::from_str(&spawn.uuid),
protocol::UUID::from_str(&spawn.uuid).unwrap(),
f64::from(spawn.x),
f64::from(spawn.y),
f64::from(spawn.z),