#[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};
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!(),
}
}
pub fn trim_trailing_slash(url: impl Into<String>) -> String {
let mut s = url.into();
while s.ends_with('/') {
s.pop();
}
s
}
#[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)
}
}
}
}
#[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> {
pub const fn new(client: &'a $client, token: &'a str) -> Self {
Self { client, token }
}
pub const fn client(&self) -> &'a $client {
self.client
}
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;