use std::fmt;
use std::str::FromStr;
pub use ::uuid::Uuid;
use md5::{Digest, Md5};
use serde::{Deserialize, Deserializer, Serialize, Serializer, de};
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct McUuid(pub ::uuid::Uuid);
impl McUuid {
#[must_use]
pub const fn new(uuid: ::uuid::Uuid) -> Self {
Self(uuid)
}
#[must_use]
pub fn new_v4() -> Self {
Self(::uuid::Uuid::new_v4())
}
#[must_use]
pub fn offline_player(username: &str) -> Self {
let mut hasher = Md5::new();
hasher.update(b"OfflinePlayer:");
hasher.update(username.as_bytes());
let mut bytes: [u8; 16] = hasher.finalize().into();
bytes[6] = (bytes[6] & 0x0f) | 0x30;
bytes[8] = (bytes[8] & 0x3f) | 0x80;
Self(::uuid::Uuid::from_bytes(bytes))
}
#[must_use]
pub const fn as_uuid(&self) -> &::uuid::Uuid {
&self.0
}
#[must_use]
pub const fn into_uuid(self) -> ::uuid::Uuid {
self.0
}
#[must_use]
pub fn to_undashed(&self) -> String {
self.0.simple().to_string()
}
#[must_use]
pub fn to_hyphenated(&self) -> String {
self.0.hyphenated().to_string()
}
}
impl AsRef<::uuid::Uuid> for McUuid {
fn as_ref(&self) -> &::uuid::Uuid {
&self.0
}
}
impl PartialEq<::uuid::Uuid> for McUuid {
fn eq(&self, other: &::uuid::Uuid) -> bool {
self.0 == *other
}
}
impl PartialEq<McUuid> for ::uuid::Uuid {
fn eq(&self, other: &McUuid) -> bool {
*self == other.0
}
}
impl From<::uuid::Uuid> for McUuid {
fn from(value: ::uuid::Uuid) -> Self {
Self(value)
}
}
impl From<McUuid> for ::uuid::Uuid {
fn from(value: McUuid) -> Self {
value.0
}
}
impl fmt::Display for McUuid {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.0.simple())
}
}
impl FromStr for McUuid {
type Err = ::uuid::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
::uuid::Uuid::parse_str(s.trim()).map(Self)
}
}
impl Serialize for McUuid {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
let mut buf = ::uuid::Uuid::encode_buffer();
serializer.serialize_str(self.0.simple().encode_lower(&mut buf))
}
}
impl<'de> Deserialize<'de> for McUuid {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
struct McUuidVisitor;
impl de::Visitor<'_> for McUuidVisitor {
type Value = McUuid;
fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("a hyphenated or undashed Minecraft UUID string")
}
fn visit_str<E: de::Error>(self, v: &str) -> Result<Self::Value, E> {
McUuid::from_str(v).map_err(de::Error::custom)
}
}
deserializer.deserialize_str(McUuidVisitor)
}
}
pub mod hyphenated {
use super::McUuid;
use serde::{Deserialize, Deserializer, Serializer};
pub fn serialize<S: Serializer>(uuid: &McUuid, serializer: S) -> Result<S::Ok, S::Error> {
let mut buf = ::uuid::Uuid::encode_buffer();
serializer.serialize_str(uuid.0.hyphenated().encode_lower(&mut buf))
}
pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result<McUuid, D::Error> {
McUuid::deserialize(deserializer)
}
}