#[cfg(feature = "client")]
use serde::Serialize;
#[cfg(feature = "client")]
use crate::core::error::{DelopayError, Result};
pub(crate) fn hex_decode(s: &str) -> Option<Vec<u8>> {
let bytes = s.as_bytes();
if !bytes.len().is_multiple_of(2) {
return None;
}
let mut out = Vec::with_capacity(bytes.len() / 2);
for pair in bytes.chunks_exact(2) {
out.push((hex_val(pair[0])? << 4) | hex_val(pair[1])?);
}
Some(out)
}
fn hex_val(b: u8) -> Option<u8> {
match b {
b'0'..=b'9' => Some(b - b'0'),
b'a'..=b'f' => Some(b - b'a' + 10),
b'A'..=b'F' => Some(b - b'A' + 10),
_ => None,
}
}
#[cfg(feature = "client")]
pub(crate) fn encode_segment(s: &str) -> String {
let mut out = String::with_capacity(s.len());
for b in s.bytes() {
match b {
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
out.push(b as char)
}
_ => out.push_str(&format!("%{b:02X}")),
}
}
out
}
#[cfg(feature = "client")]
pub(crate) fn to_json_vec<T: Serialize>(v: &T) -> Result<Vec<u8>> {
serde_json::to_vec(v).map_err(|e| DelopayError::Decode(e.to_string()))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn hex_decode_roundtrip() {
assert_eq!(hex_decode("00ff10"), Some(vec![0x00, 0xff, 0x10]));
}
#[test]
fn hex_decode_accepts_uppercase() {
assert_eq!(hex_decode("00FF10"), Some(vec![0x00, 0xff, 0x10]));
}
#[test]
fn hex_decode_rejects_odd_length() {
assert_eq!(hex_decode("abc"), None);
}
#[test]
fn hex_decode_rejects_non_hex() {
assert_eq!(hex_decode("zz"), None);
assert_eq!(hex_decode("00 f"), None);
assert_eq!(hex_decode("00é"), None);
}
#[test]
fn hex_decode_empty_is_empty() {
assert_eq!(hex_decode(""), Some(Vec::new()));
}
#[cfg(feature = "client")]
#[test]
fn encode_segment_passes_unreserved() {
assert_eq!(encode_segment("pay_abc-123._~"), "pay_abc-123._~");
}
#[cfg(feature = "client")]
#[test]
fn encode_segment_escapes_reserved() {
assert_eq!(encode_segment("a/b"), "a%2Fb");
assert_eq!(encode_segment("a b"), "a%20b");
assert_eq!(encode_segment("a?b#c"), "a%3Fb%23c");
}
#[cfg(feature = "client")]
#[test]
fn to_json_vec_serializes_once() {
#[derive(serde::Serialize)]
struct Body {
amount: i64,
currency: &'static str,
}
let out = to_json_vec(&Body {
amount: 1999,
currency: "EUR",
})
.unwrap();
assert_eq!(out, br#"{"amount":1999,"currency":"EUR"}"#);
}
}