mcapi 0.2.0

Unified async Rust client for the Minecraft ecosystem (Mojang, Modrinth, CurseForge, Yggdrasil, Blessing Skin, Loaders, Java Runtimes, and SLP)
Documentation
//! Shared path encoding, serde helpers, and internal boilerplate macros.

#[cfg(feature = "http")]
use serde::{Deserialize, Deserializer};
#[cfg(any(feature = "curseforge", feature = "modrinth"))]
use serde::{Serialize, Serializer};
#[cfg(feature = "http")]
use url::Url;

use crate::{Error, Result};

/// Percent-encodes a single URL path segment according to RFC 3986 ยง3.3.
///
/// Rejects empty strings, dot segments (`.` / `..`), slashes (`/` / `\`), and NUL bytes
/// so callers cannot inject extra path segments or query/fragment delimiters.
pub fn encode_path_segment(segment: &str) -> Result<String> {
    if segment.is_empty()
        || segment == "."
        || segment == ".."
        || segment.contains(['/', '\\', '\0'])
    {
        return Err(Error::InvalidInput(format!(
            "invalid URL path segment: {segment:?}"
        )));
    }

    let mut out = String::with_capacity(segment.len());
    for byte in segment.bytes() {
        let is_unreserved =
            byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~');
        if is_unreserved {
            out.push(byte as char);
        } else {
            out.push('%');
            out.push(hex_upper(byte >> 4));
            out.push(hex_upper(byte & 0x0F));
        }
    }
    Ok(out)
}

#[inline]
fn hex_upper(nibble: u8) -> char {
    match nibble {
        0..=9 => (b'0' + nibble) as char,
        10..=15 => (b'A' + (nibble - 10)) as char,
        _ => unreachable!(),
    }
}

/// Strips any trailing `'/'` characters from `url` in place without extra allocation.
pub fn trim_trailing_slash(url: impl Into<String>) -> String {
    let mut s = url.into();
    while s.ends_with('/') {
        s.pop();
    }
    s
}

/// Deserializes an optional [`Url`], treating `null` or empty/whitespace-only strings as `None`.
#[cfg(feature = "http")]
#[cfg_attr(docsrs, doc(cfg(feature = "http")))]
pub fn deserialize_optional_url<'de, D>(
    deserializer: D,
) -> std::result::Result<Option<Url>, D::Error>
where
    D: Deserializer<'de>,
{
    let raw = Option::<String>::deserialize(deserializer)?;
    match raw {
        None => Ok(None),
        Some(s) => {
            let trimmed = s.trim();
            if trimmed.is_empty() {
                Ok(None)
            } else {
                Url::parse(trimmed)
                    .map(Some)
                    .map_err(serde::de::Error::custom)
            }
        }
    }
}

/// Serializes an `Option<T>` as a compact JSON string when `Some` (for query parameters
/// such as Modrinth `loaders`/`game_versions` or CurseForge `categoryIds`/`modLoaderTypes`).
#[cfg(any(feature = "curseforge", feature = "modrinth"))]
pub(crate) fn serialize_option_json<T: Serialize, S: Serializer>(
    value: &Option<T>,
    serializer: S,
) -> std::result::Result<S::Ok, S::Error> {
    match value {
        Some(v) => {
            let encoded = serde_json::to_string(v).map_err(serde::ser::Error::custom)?;
            serializer.serialize_str(&encoded)
        }
        None => serializer.serialize_none(),
    }
}

/// Declares a module-local zero-cost `Authed<'a>` view struct for `$client`.
#[cfg(any(
    feature = "mojang",
    feature = "modrinth",
    feature = "yggdrasil",
    feature = "blessing"
))]
macro_rules! define_authed {
    ($client:ty) => {
        /// Borrowed authenticated view over a client bound to a credential token.
        #[derive(Clone, Copy)]
        pub struct Authed<'a> {
            pub(crate) client: &'a $client,
            pub(crate) token: &'a str,
        }

        impl<'a> std::fmt::Debug for Authed<'a> {
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                f.debug_struct("Authed")
                    .field("client", &self.client)
                    .field("token", &"[REDACTED]")
                    .finish()
            }
        }

        impl<'a> Authed<'a> {
            /// Creates a new authenticated view.
            pub const fn new(client: &'a $client, token: &'a str) -> Self {
                Self { client, token }
            }

            /// Returns the underlying client reference.
            pub const fn client(&self) -> &'a $client {
                self.client
            }

            /// Returns the bound credential token.
            pub const fn token(&self) -> &'a str {
                self.token
            }
        }
    };
}

#[cfg(any(
    feature = "mojang",
    feature = "modrinth",
    feature = "yggdrasil",
    feature = "blessing"
))]
pub(crate) use define_authed;

/// Implements `std::fmt::Debug` for a struct while replacing sensitive fields with `"[REDACTED]"`.
#[cfg(any(
    feature = "curseforge",
    feature = "mojang",
    feature = "yggdrasil",
    feature = "blessing"
))]
macro_rules! impl_redacted_debug {
    (
        $ty:ident {
            $($field:ident),* $(,)?;
            redacted: $($secret:ident),* $(,)?
            $(; optional_redacted: $($opt_secret:ident),* $(,)?)?
        }
    ) => {
        impl std::fmt::Debug for $ty {
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                let mut ds = f.debug_struct(stringify!($ty));
                $(ds.field(stringify!($field), &self.$field);)*
                $(ds.field(stringify!($secret), &"[REDACTED]");)*
                $($(
                    ds.field(
                        stringify!($opt_secret),
                        &self.$opt_secret.as_ref().map(|_| "[REDACTED]"),
                    );
                )*)?
                ds.finish()
            }
        }
    };
}

#[cfg(any(
    feature = "curseforge",
    feature = "mojang",
    feature = "yggdrasil",
    feature = "blessing"
))]
pub(crate) use impl_redacted_debug;