mcapi 0.3.0

Unified async Rust client for the Minecraft ecosystem (Mojang, Modrinth, CurseForge, Yggdrasil, Blessing Skin, Loaders, BMCLAPI, and Java Runtimes)
Documentation
//! Minecraft UUID wrapper supporting undashed/hyphenated serde and offline-mode v3 UUIDs.

use std::fmt;
use std::str::FromStr;

/// Re-export of [`uuid::Uuid`] used inside [`McUuid`].
pub use ::uuid::Uuid;
use md5::{Digest, Md5};
use serde::{Deserialize, Deserializer, Serialize, Serializer, de};

/// A Minecraft-compatible UUID wrapper.
///
/// Deserializes transparently from both undashed 32-character hex strings
/// (used by Mojang and Yggdrasil) and standard hyphenated 36-character UUID strings.
/// Serializes by default as undashed 32-character lowercase hexadecimal.
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct McUuid(pub ::uuid::Uuid);

impl McUuid {
    /// Wraps an existing [`Uuid`].
    #[must_use]
    pub const fn new(uuid: ::uuid::Uuid) -> Self {
        Self(uuid)
    }

    /// Generates a random v4 [`McUuid`].
    #[must_use]
    pub fn new_v4() -> Self {
        Self(::uuid::Uuid::new_v4())
    }

    /// Computes the deterministic Minecraft offline-mode UUID for `username`
    /// (`UUID.nameUUIDFromBytes(("OfflinePlayer:" + username).getBytes(UTF_8))`).
    ///
    /// Implements RFC 4122 ยง4.3 name-based MD5 (v3) UUID formatting.
    #[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();
        // Set version to 3 (MD5 name-based) and variant to RFC 4122.
        bytes[6] = (bytes[6] & 0x0f) | 0x30;
        bytes[8] = (bytes[8] & 0x3f) | 0x80;
        Self(::uuid::Uuid::from_bytes(bytes))
    }

    /// Returns a reference to the inner [`Uuid`].
    #[must_use]
    pub const fn as_uuid(&self) -> &::uuid::Uuid {
        &self.0
    }

    /// Unwraps and returns the inner [`Uuid`].
    #[must_use]
    pub const fn into_uuid(self) -> ::uuid::Uuid {
        self.0
    }

    /// Formats the UUID as a 32-character lowercase undashed hex string.
    #[must_use]
    pub fn to_undashed(&self) -> String {
        self.0.simple().to_string()
    }

    /// Formats the UUID as a 36-character lowercase hyphenated 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)
    }
}

/// Serde helpers for fields that require hyphenated UUID serialization.
pub mod hyphenated {
    use super::McUuid;
    use serde::{Deserialize, Deserializer, Serializer};

    /// Serializes `McUuid` as a standard hyphenated string.
    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))
    }

    /// Deserializes `McUuid` from either hyphenated or undashed UUID strings.
    pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result<McUuid, D::Error> {
        McUuid::deserialize(deserializer)
    }
}