#[cfg(any(feature = "curseforge", feature = "mojang"))]
use serde::{Deserialize, Deserializer};
#[cfg(any(feature = "curseforge", feature = "modrinth"))]
use serde::{Serialize, Serializer};
#[cfg(any(
feature = "curseforge",
feature = "mojang",
feature = "yggdrasil",
feature = "blessing"
))]
use url::Url;
#[cfg(any(
feature = "mojang",
feature = "modrinth",
feature = "curseforge",
feature = "yggdrasil",
feature = "blessing",
feature = "loaders",
feature = "bmclapi",
feature = "java"
))]
use crate::{Error, Result};
#[cfg(any(
feature = "mojang",
feature = "modrinth",
feature = "curseforge",
feature = "blessing",
feature = "loaders",
feature = "bmclapi",
feature = "java"
))]
pub(crate) 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)
}
#[cfg(any(
feature = "mojang",
feature = "modrinth",
feature = "curseforge",
feature = "blessing",
feature = "loaders",
feature = "bmclapi",
feature = "java"
))]
#[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!(),
}
}
#[cfg(any(
feature = "mojang",
feature = "modrinth",
feature = "curseforge",
feature = "yggdrasil-authlib",
feature = "blessing",
feature = "loaders",
feature = "bmclapi",
feature = "java"
))]
pub(crate) fn trim_trailing_slash(url: impl Into<String>) -> String {
let mut s = url.into();
while s.ends_with('/') {
s.pop();
}
s
}
#[cfg(any(feature = "yggdrasil", feature = "blessing"))]
pub(crate) fn validate_http_url(raw: &str) -> Result<Url> {
let parsed = Url::parse(raw.trim())?;
if !matches!(parsed.scheme(), "http" | "https") || parsed.host_str().is_none() {
return Err(Error::InvalidInput(format!(
"URL must use http:// or https:// with a host: {raw:?}"
)));
}
Ok(parsed)
}
#[cfg(any(feature = "curseforge", feature = "mojang"))]
pub(crate) 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)
}
}
}
}
#[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(),
}
}
#[cfg(any(
feature = "mojang",
feature = "modrinth",
feature = "yggdrasil",
feature = "blessing"
))]
macro_rules! define_authed {
($client:ty) => {
#[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> {
#[must_use]
pub const fn new(client: &'a $client, token: &'a str) -> Self {
Self { client, token }
}
#[must_use]
pub const fn client(&self) -> &'a $client {
self.client
}
#[must_use]
pub const fn token(&self) -> &'a str {
self.token
}
}
};
}
#[cfg(any(
feature = "mojang",
feature = "modrinth",
feature = "yggdrasil",
feature = "blessing"
))]
pub(crate) use define_authed;
#[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;
#[cfg(all(
test,
any(
feature = "mojang",
feature = "modrinth",
feature = "curseforge",
feature = "blessing",
feature = "loaders",
feature = "bmclapi",
feature = "java"
)
))]
mod tests {
use super::encode_path_segment;
#[test]
fn encode_path_segment_validates_and_percent_encodes() {
assert_eq!(
encode_path_segment("1.0.0+fabric").unwrap(),
"1.0.0%2Bfabric"
);
assert_eq!(
encode_path_segment("史蒂夫").unwrap(),
"%E5%8F%B2%E8%92%82%E5%A4%AB"
);
assert!(encode_path_segment("../etc").is_err());
assert!(encode_path_segment("..").is_err());
assert!(encode_path_segment("").is_err());
}
}