use crate::error::{CanonicalError, CanonicalErrorKind};
use crate::value::Value;
pub const MAX_SAFE_INTEGER: f64 = 9_007_199_254_740_991.0;
pub trait ByteSink {
fn write_bytes(&mut self, bytes: &[u8]) -> Result<(), CanonicalError>;
}
impl ByteSink for Vec<u8> {
fn write_bytes(&mut self, bytes: &[u8]) -> Result<(), CanonicalError> {
self.extend_from_slice(bytes);
Ok(())
}
}
#[allow(
clippy::float_cmp,
reason = "exact comparisons are the domain rule itself: the zero check and the integrality check must be exact, never approximate"
)]
pub fn check_number_domain(value: f64) -> Result<(), CanonicalError> {
if !value.is_finite() {
return Err(CanonicalError::new(
CanonicalErrorKind::NonFiniteNumber,
format!("number {value} is not finite; RFC 8785 has no encoding for it"),
));
}
if value.fract() == 0.0 && value.abs() > MAX_SAFE_INTEGER {
return Err(CanonicalError::new(
CanonicalErrorKind::IntegerOutOfSafeRange,
format!("integer {value} exceeds the safe bound {MAX_SAFE_INTEGER} (2^53 minus 1)"),
));
}
Ok(())
}
#[allow(
clippy::float_cmp,
reason = "the zero and sign checks here are exact by specification"
)]
pub fn format_number(value: f64) -> Result<String, CanonicalError> {
check_number_domain(value)?;
if value == 0.0 {
return Ok("0".to_string());
}
let sign = if value < 0.0 { "-" } else { "" };
let rendered = format!("{}", value.abs());
let (int_part, frac_part) = match rendered.split_once('.') {
Some((int, frac)) => (int, frac),
None => (rendered.as_str(), ""),
};
let mut digit_text = String::with_capacity(int_part.len() + frac_part.len());
digit_text.push_str(int_part);
digit_text.push_str(frac_part);
let mut exp10 = -i32::try_from(frac_part.len()).unwrap_or(i32::MAX);
let leading_zeros = digit_text.bytes().take_while(|byte| *byte == b'0').count();
digit_text.drain(..leading_zeros);
while digit_text.len() > 1 && digit_text.ends_with('0') {
digit_text.pop();
exp10 += 1;
}
let k = i32::try_from(digit_text.len()).unwrap_or(i32::MAX);
let n = exp10 + k;
let body = layout(&digit_text, k, n);
if sign.is_empty() {
Ok(body)
} else {
Ok(format!("{sign}{body}"))
}
}
fn layout(s: &str, k: i32, n: i32) -> String {
if k <= n && n <= 21 {
let zeros = usize::try_from(n - k).unwrap_or(0);
let mut out = String::with_capacity(s.len() + zeros);
out.push_str(s);
for _ in 0..zeros {
out.push('0');
}
out
} else if 0 < n && n <= 21 {
let point = usize::try_from(n).unwrap_or(0);
format!("{}.{}", &s[..point], &s[point..])
} else if -6 < n && n <= 0 {
let zeros = usize::try_from(-n).unwrap_or(0);
let mut out = String::from("0.");
for _ in 0..zeros {
out.push('0');
}
out.push_str(s);
out
} else if k == 1 {
format!("{s}e{}{}", exponent_sign(n - 1), (n - 1).abs())
} else {
format!(
"{}.{}e{}{}",
&s[..1],
&s[1..],
exponent_sign(n - 1),
(n - 1).abs()
)
}
}
const fn exponent_sign(exponent: i32) -> char {
if exponent >= 0 { '+' } else { '-' }
}
pub fn encode<S: ByteSink + ?Sized>(value: &Value, sink: &mut S) -> Result<(), CanonicalError> {
encode_at(value, sink, 1)
}
fn encode_at<S: ByteSink + ?Sized>(
value: &Value,
sink: &mut S,
depth: usize,
) -> Result<(), CanonicalError> {
match value {
Value::Null => sink.write_bytes(b"null"),
Value::Bool(true) => sink.write_bytes(b"true"),
Value::Bool(false) => sink.write_bytes(b"false"),
Value::Number(number) => {
let text = format_number(*number)?;
sink.write_bytes(text.as_bytes())
}
Value::String(text) => encode_string(text, sink),
Value::Array(items) => {
check_depth(depth)?;
sink.write_bytes(b"[")?;
for (index, item) in items.iter().enumerate() {
if index > 0 {
sink.write_bytes(b",")?;
}
encode_at(item, sink, depth + 1)?;
}
sink.write_bytes(b"]")
}
Value::Object(pairs) => {
check_depth(depth)?;
encode_object(pairs, sink, depth)
}
}
}
fn check_depth(depth: usize) -> Result<(), CanonicalError> {
if depth > crate::parse::MAX_DEPTH {
return Err(CanonicalError::new(
CanonicalErrorKind::DepthLimitExceeded,
format!(
"nesting exceeds the depth limit of {}",
crate::parse::MAX_DEPTH
),
));
}
Ok(())
}
fn encode_object<S: ByteSink + ?Sized>(
pairs: &[(String, Value)],
sink: &mut S,
depth: usize,
) -> Result<(), CanonicalError> {
let mut refs: Vec<(&String, &Value)> = pairs.iter().map(|pair| (&pair.0, &pair.1)).collect();
refs.sort_by(|left, right| left.0.encode_utf16().cmp(right.0.encode_utf16()));
for window in refs.windows(2) {
if window[0].0 == window[1].0 {
return Err(CanonicalError::new(
CanonicalErrorKind::DuplicateKey,
format!("duplicate object key {:?}", window[0].0),
));
}
}
sink.write_bytes(b"{")?;
for (index, (key, value)) in refs.iter().enumerate() {
if index > 0 {
sink.write_bytes(b",")?;
}
encode_string(key, sink)?;
sink.write_bytes(b":")?;
encode_at(value, sink, depth + 1)?;
}
sink.write_bytes(b"}")
}
fn encode_string<S: ByteSink + ?Sized>(text: &str, sink: &mut S) -> Result<(), CanonicalError> {
const HEX: &[u8; 16] = b"0123456789abcdef";
let bytes = text.as_bytes();
sink.write_bytes(b"\"")?;
let mut run_start = 0;
for (index, ch) in text.char_indices() {
let escape: &[u8] = match ch {
'"' => b"\\\"",
'\\' => b"\\\\",
'\u{08}' => b"\\b",
'\u{09}' => b"\\t",
'\u{0A}' => b"\\n",
'\u{0C}' => b"\\f",
'\u{0D}' => b"\\r",
control if (control as u32) < 0x20 => {
sink.write_bytes(&bytes[run_start..index])?;
let code = control as u32;
let escape = [
b'\\',
b'u',
b'0',
b'0',
HEX[usize::try_from((code >> 4) & 0xF).unwrap_or(0)],
HEX[usize::try_from(code & 0xF).unwrap_or(0)],
];
sink.write_bytes(&escape)?;
run_start = index + 1;
continue;
}
_ => continue,
};
sink.write_bytes(&bytes[run_start..index])?;
sink.write_bytes(escape)?;
run_start = index + ch.len_utf8();
}
sink.write_bytes(&bytes[run_start..])?;
sink.write_bytes(b"\"")
}
pub fn to_vec(value: &Value) -> Result<Vec<u8>, CanonicalError> {
let mut out = Vec::new();
encode(value, &mut out)?;
Ok(out)
}