Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
295 changes: 290 additions & 5 deletions src/ser.rs
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
use half::{bf16, f16};
use serde::{
ser::{
Error as _, Impossible, SerializeMap, SerializeSeq, SerializeStruct,
Expand All@@ -7,7 +8,53 @@ use serde::{
};
use serde_json::error::Error;

use crate::{array::TryCollect, DestructuredRef, IArray, INumber, IObject, IString, IValue};
use crate::{
array::{ArraySliceRef, TryCollect},
DestructuredRef, IArray, INumber, IObject, IString, IValue,
};

/// Rounds an f64 to the given number of significant decimal digits.
#[inline]
fn round_to_sig_digits(val: f64, sig_digits: u32) -> f64 {
// how many digits are left of the decimal point, minus one
// OR: what power of 10 is this number closest to? (e.g. 100 -> 10^2, 0.001 -> 10^-3)
let order_of_magnitude = val.abs().log10().floor() as i32;
// Multiplier that shifts the desired significant digits into the integer part,
// so that f64::round() can snap to the nearest integer and discard the rest.
// e.g. for val=3.14, order_of_magnitude = 0, sig_digits=2: scale=10, so 3.14*10=31.4 → round→31 → 31/10=3.1
let scale = 10f64.powi(sig_digits as i32 - 1 - order_of_magnitude);
(val * scale).round() / scale
}

/// Finds an f64 value that, when formatted by ryu's f64 algorithm, produces
/// the shortest decimal string that still round-trips through the target
/// half-precision type (f16 or bf16).
///
/// ryu only supports f32/f64, and serde has no `serialize_f16`. Since f16/bf16
/// have far fewer distinct values than f32, there exist shorter representations
/// that uniquely identify the half value. For example, f16(0.3) = 0.300048828125,
/// and "0.3" parsed as f16 gives back the same bits — so "0.3" is valid.
///
/// The approach: try rounding to increasing significant digits until the
/// rounded value round-trips through the type. Then return that f64
/// value, so that `serialize_f64` (via ryu) reproduces it.
fn find_shortest_roundtrip_f64(f64_val: f64, roundtrips: impl Fn(f64) -> bool) -> f64 {
if !f64_val.is_finite() || f64_val.fract() == 0.0 {
return f64_val;
}
// With our usage(F16/BF16), the loop will need only ~4 iterations, since max significant digits needed is ~4
// Example: f16(3.14159) stores 3.140625
// sig_digits=1 → 3.0 → f16(3.0)=3.0 ≠ 3.140625 ❌
// sig_digits=2 → 3.1 → f16(3.1)=3.099.. ≠ 3.140625 ❌
// sig_digits=3 → 3.14 → f16(3.14)=3.140625 ✅ → returns 3.14
for sig_digits in 1..=5u32 {
let rounded = round_to_sig_digits(f64_val, sig_digits);
if roundtrips(rounded) {
return rounded;
}
}
f64_val
}

impl Serialize for IValue {
#[inline]
Expand DownExpand Up@@ -55,11 +102,50 @@ impl Serialize for IArray {
where
S: Serializer,
{
let mut s = serializer.serialize_seq(Some(self.len()))?;
for v in self {
s.serialize_element(&v)?;
match self.as_slice() {
// Serialize typed float arrays with the shortest representation that
// round-trips through the stored precision. Without this, all floats
// would be promoted to f64 via INumber, and ryu's f64 algorithm would
// emit unnecessarily long strings (e.g. "0.3" stored as f32 would
// serialize as "0.30000001192092896" instead of "0.3").
//
// F32: serialize directly as f32 so ryu uses its f32 algorithm.
// F16/BF16: ryu has no f16 mode and serde has no serialize_f16, so we
// find the shortest decimal that round-trips through the half type and
// pass the corresponding f64 value to serialize_f64.
ArraySliceRef::F32(slice) => {
let mut s = serializer.serialize_seq(Some(slice.len()))?;
for &v in slice {
s.serialize_element(&v)?;
}
s.end()
}
ArraySliceRef::F16(slice) => {
let mut s = serializer.serialize_seq(Some(slice.len()))?;
for &v in slice {
let f64_val = f64::from(v);
let shortest = find_shortest_roundtrip_f64(f64_val, |p| f16::from_f64(p) == v);
s.serialize_element(&shortest)?;
}
s.end()
}
ArraySliceRef::BF16(slice) => {
let mut s = serializer.serialize_seq(Some(slice.len()))?;
for &v in slice {
let f64_val = f64::from(v);
let shortest = find_shortest_roundtrip_f64(f64_val, |p| bf16::from_f64(p) == v);
s.serialize_element(&shortest)?;
}
s.end()
}
Comment thread
AvivDavid23 marked this conversation as resolved.
_ => {
let mut s = serializer.serialize_seq(Some(self.len()))?;
for v in self {
s.serialize_element(&v)?;
}
s.end()
}
}
s.end()
}
}

Expand DownExpand Up@@ -635,3 +721,202 @@ where
{
value.serialize(ValueSerializer)
}

#[cfg(test)]
mod tests {
use crate::array::{ArraySliceRef, FloatType};
use crate::{FPHAConfig, IArray, IValue, IValueDeserSeed};

#[test]
fn test_f32_array_serialization_preserves_short_representation() {
let mut arr = IArray::new();
arr.push_with_fp_type(IValue::from(0.3), FloatType::F32)
.unwrap();
assert!(matches!(arr.as_slice(), ArraySliceRef::F32(_)));

let json = serde_json::to_string(&arr).unwrap();
assert_eq!(
json, "[0.3]",
"F32 array should serialize 0.3 as '0.3', not with extra f64 precision digits"
);
}

#[test]
fn test_f64_array_serialization_preserves_short_representation() {
let mut arr = IArray::new();
arr.push_with_fp_type(IValue::from(0.3), FloatType::F64)
.unwrap();
assert!(matches!(arr.as_slice(), ArraySliceRef::F64(_)));

let json = serde_json::to_string(&arr).unwrap();
assert_eq!(json, "[0.3]");
}

#[test]
fn test_f16_array_serialization_preserves_short_representation() {
let mut arr = IArray::new();
arr.push_with_fp_type(IValue::from(1.5), FloatType::F16)
.unwrap();
assert_eq!(serde_json::to_string(&arr).unwrap(), "[1.5]");

let mut arr2 = IArray::new();
arr2.push_with_fp_type(IValue::from(0.3), FloatType::F16)
.unwrap();
assert_eq!(
serde_json::to_string(&arr2).unwrap(),
"[0.3]",
"F16 array should serialize 0.3 as '0.3', not '0.30004883' or '0.300048828125'"
);
}

#[test]
fn test_bf16_array_serialization_preserves_short_representation() {
let mut arr = IArray::new();
arr.push_with_fp_type(IValue::from(1.5), FloatType::BF16)
.unwrap();
assert_eq!(serde_json::to_string(&arr).unwrap(), "[1.5]");

let mut arr2 = IArray::new();
arr2.push_with_fp_type(IValue::from(0.3), FloatType::BF16)
.unwrap();
assert_eq!(
serde_json::to_string(&arr2).unwrap(),
"[0.3]",
"BF16 array should serialize 0.3 as '0.3'"
);
}

#[test]
fn test_typed_float_array_serialization_roundtrip() {
let input = "[0.3,0.1,0.7,1.0,2.5,100.0]";
let fp_types = [
FloatType::F16,
FloatType::BF16,
FloatType::F32,
FloatType::F64,
];

let jsons: Vec<String> = fp_types
.iter()
.map(|&fp_type| {
let seed = IValueDeserSeed::new(Some(FPHAConfig::new_with_type(fp_type)));
let mut de = serde_json::Deserializer::from_str(input);
let arr = serde::de::DeserializeSeed::deserialize(seed, &mut de)
.unwrap()
.into_array()
.unwrap();
let json_out = serde_json::to_string(&arr).unwrap();
assert_eq!(
json_out, input,
"{fp_type} round-trip should preserve the original JSON string"
);
json_out
})
.collect();

for pair in jsons.windows(2) {
assert_eq!(
pair[0], pair[1],
"all float types should produce identical JSON"
);
}
}

#[test]
fn test_f16_precision_loss_produces_different_but_short_representation() {
// Values with more significant digits than f16 can represent (~3.3 digits).
// The stored f16 value differs from the original, so the serialized string
// must differ too — but it should still be the shortest string that
// round-trips through f16.
let cases: &[(&str, &str)] = &[
("3.14159", "3.14"), // pi truncated: f16 stores 3.140625
("42.42", "42.4"), // f16 stores 42.40625
("12.345", "12.34"), // f16 stores 12.34375
("0.5678", "0.568"), // f16 stores 0.56787109375
];

for &(input, expected_f16) in cases {
let json_input = format!("[{input}]");

let f16_arr: IArray = {
let seed = IValueDeserSeed::new(Some(FPHAConfig::new_with_type(FloatType::F16)));
let mut de = serde_json::Deserializer::from_str(&json_input);
serde::de::DeserializeSeed::deserialize(seed, &mut de)
.unwrap()
.into_array()
.unwrap()
};
let f16_json = serde_json::to_string(&f16_arr).unwrap();
assert_eq!(
f16_json,
format!("[{expected_f16}]"),
"F16 of {input}: should serialize as shortest f16 representation"
);

// Same values through F32 should preserve the original (enough precision)
let f32_arr: IArray = {
let seed = IValueDeserSeed::new(Some(FPHAConfig::new_with_type(FloatType::F32)));
let mut de = serde_json::Deserializer::from_str(&json_input);
serde::de::DeserializeSeed::deserialize(seed, &mut de)
.unwrap()
.into_array()
.unwrap()
};
let f32_json = serde_json::to_string(&f32_arr).unwrap();
assert_eq!(
f32_json, json_input,
"F32 of {input}: should preserve the original representation"
);
}
}

#[test]
fn test_negative_float_array_serialization() {
let input = "[-0.3,-0.1,-1.0,-2.5,-100.0]";
let fp_types = [
FloatType::F16,
FloatType::BF16,
FloatType::F32,
FloatType::F64,
];

for &fp_type in &fp_types {
let seed = IValueDeserSeed::new(Some(FPHAConfig::new_with_type(fp_type)));
let mut de = serde_json::Deserializer::from_str(input);
let arr = serde::de::DeserializeSeed::deserialize(seed, &mut de)
.unwrap()
.into_array()
.unwrap();
let json_out = serde_json::to_string(&arr).unwrap();
assert_eq!(
json_out, input,
"{fp_type} negative round-trip should preserve the original JSON string"
);
}
}

#[test]
fn test_negative_f16_precision_loss_produces_short_representation() {
let cases: &[(&str, &str)] = &[
("-3.14159", "-3.14"),
("-42.42", "-42.4"),
("-0.5678", "-0.568"),
];

for &(input, expected_f16) in cases {
let json_input = format!("[{input}]");
let seed = IValueDeserSeed::new(Some(FPHAConfig::new_with_type(FloatType::F16)));
let mut de = serde_json::Deserializer::from_str(&json_input);
let arr = serde::de::DeserializeSeed::deserialize(seed, &mut de)
.unwrap()
.into_array()
.unwrap();
let json_out = serde_json::to_string(&arr).unwrap();
assert_eq!(
json_out,
format!("[{expected_f16}]"),
"F16 of {input}: negative should serialize as shortest f16 representation"
);
}
}
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
295 changes: 290 additions & 5 deletions src/ser.rs
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
use half::{bf16, f16};
use serde::{
ser::{
Error as _, Impossible, SerializeMap, SerializeSeq, SerializeStruct,
Expand All@@ -7,7 +8,53 @@ use serde::{
};
use serde_json::error::Error;

use crate::{array::TryCollect, DestructuredRef, IArray, INumber, IObject, IString, IValue};
use crate::{
array::{ArraySliceRef, TryCollect},
DestructuredRef, IArray, INumber, IObject, IString, IValue,
};

/// Rounds an f64 to the given number of significant decimal digits.
#[inline]
fn round_to_sig_digits(val: f64, sig_digits: u32) -> f64 {
// how many digits are left of the decimal point, minus one
// OR: what power of 10 is this number closest to? (e.g. 100 -> 10^2, 0.001 -> 10^-3)
let order_of_magnitude = val.abs().log10().floor() as i32;
// Multiplier that shifts the desired significant digits into the integer part,
// so that f64::round() can snap to the nearest integer and discard the rest.
// e.g. for val=3.14, order_of_magnitude = 0, sig_digits=2: scale=10, so 3.14*10=31.4 → round→31 → 31/10=3.1
let scale = 10f64.powi(sig_digits as i32 - 1 - order_of_magnitude);
(val * scale).round() / scale
}

/// Finds an f64 value that, when formatted by ryu's f64 algorithm, produces
/// the shortest decimal string that still round-trips through the target
/// half-precision type (f16 or bf16).
///
/// ryu only supports f32/f64, and serde has no `serialize_f16`. Since f16/bf16
/// have far fewer distinct values than f32, there exist shorter representations
/// that uniquely identify the half value. For example, f16(0.3) = 0.300048828125,
/// and "0.3" parsed as f16 gives back the same bits — so "0.3" is valid.
///
/// The approach: try rounding to increasing significant digits until the
/// rounded value round-trips through the type. Then return that f64
/// value, so that `serialize_f64` (via ryu) reproduces it.
fn find_shortest_roundtrip_f64(f64_val: f64, roundtrips: impl Fn(f64) -> bool) -> f64 {
if !f64_val.is_finite() || f64_val.fract() == 0.0 {
return f64_val;
}
// With our usage(F16/BF16), the loop will need only ~4 iterations, since max significant digits needed is ~4
// Example: f16(3.14159) stores 3.140625
// sig_digits=1 → 3.0 → f16(3.0)=3.0 ≠ 3.140625 ❌
// sig_digits=2 → 3.1 → f16(3.1)=3.099.. ≠ 3.140625 ❌
// sig_digits=3 → 3.14 → f16(3.14)=3.140625 ✅ → returns 3.14
for sig_digits in 1..=5u32 {
let rounded = round_to_sig_digits(f64_val, sig_digits);
if roundtrips(rounded) {
return rounded;
}
}
f64_val
}

impl Serialize for IValue {
#[inline]
Expand DownExpand Up@@ -55,11 +102,50 @@ impl Serialize for IArray {
where
S: Serializer,
{
let mut s = serializer.serialize_seq(Some(self.len()))?;
for v in self {
s.serialize_element(&v)?;
match self.as_slice() {
// Serialize typed float arrays with the shortest representation that
// round-trips through the stored precision. Without this, all floats
// would be promoted to f64 via INumber, and ryu's f64 algorithm would
// emit unnecessarily long strings (e.g. "0.3" stored as f32 would
// serialize as "0.30000001192092896" instead of "0.3").
//
// F32: serialize directly as f32 so ryu uses its f32 algorithm.
// F16/BF16: ryu has no f16 mode and serde has no serialize_f16, so we
// find the shortest decimal that round-trips through the half type and
// pass the corresponding f64 value to serialize_f64.
ArraySliceRef::F32(slice) => {
let mut s = serializer.serialize_seq(Some(slice.len()))?;
for &v in slice {
s.serialize_element(&v)?;
}
s.end()
}
ArraySliceRef::F16(slice) => {
let mut s = serializer.serialize_seq(Some(slice.len()))?;
for &v in slice {
let f64_val = f64::from(v);
let shortest = find_shortest_roundtrip_f64(f64_val, |p| f16::from_f64(p) == v);
s.serialize_element(&shortest)?;
}
s.end()
}
ArraySliceRef::BF16(slice) => {
let mut s = serializer.serialize_seq(Some(slice.len()))?;
for &v in slice {
let f64_val = f64::from(v);
let shortest = find_shortest_roundtrip_f64(f64_val, |p| bf16::from_f64(p) == v);
s.serialize_element(&shortest)?;
}
s.end()
}
Comment thread
AvivDavid23 marked this conversation as resolved.
_ => {
let mut s = serializer.serialize_seq(Some(self.len()))?;
for v in self {
s.serialize_element(&v)?;
}
s.end()
}
}
s.end()
}
}

Expand DownExpand Up@@ -635,3 +721,202 @@ where
{
value.serialize(ValueSerializer)
}

#[cfg(test)]
mod tests {
use crate::array::{ArraySliceRef, FloatType};
use crate::{FPHAConfig, IArray, IValue, IValueDeserSeed};

#[test]
fn test_f32_array_serialization_preserves_short_representation() {
let mut arr = IArray::new();
arr.push_with_fp_type(IValue::from(0.3), FloatType::F32)
.unwrap();
assert!(matches!(arr.as_slice(), ArraySliceRef::F32(_)));

let json = serde_json::to_string(&arr).unwrap();
assert_eq!(
json, "[0.3]",
"F32 array should serialize 0.3 as '0.3', not with extra f64 precision digits"
);
}

#[test]
fn test_f64_array_serialization_preserves_short_representation() {
let mut arr = IArray::new();
arr.push_with_fp_type(IValue::from(0.3), FloatType::F64)
.unwrap();
assert!(matches!(arr.as_slice(), ArraySliceRef::F64(_)));

let json = serde_json::to_string(&arr).unwrap();
assert_eq!(json, "[0.3]");
}

#[test]
fn test_f16_array_serialization_preserves_short_representation() {
let mut arr = IArray::new();
arr.push_with_fp_type(IValue::from(1.5), FloatType::F16)
.unwrap();
assert_eq!(serde_json::to_string(&arr).unwrap(), "[1.5]");

let mut arr2 = IArray::new();
arr2.push_with_fp_type(IValue::from(0.3), FloatType::F16)
.unwrap();
assert_eq!(
serde_json::to_string(&arr2).unwrap(),
"[0.3]",
"F16 array should serialize 0.3 as '0.3', not '0.30004883' or '0.300048828125'"
);
}

#[test]
fn test_bf16_array_serialization_preserves_short_representation() {
let mut arr = IArray::new();
arr.push_with_fp_type(IValue::from(1.5), FloatType::BF16)
.unwrap();
assert_eq!(serde_json::to_string(&arr).unwrap(), "[1.5]");

let mut arr2 = IArray::new();
arr2.push_with_fp_type(IValue::from(0.3), FloatType::BF16)
.unwrap();
assert_eq!(
serde_json::to_string(&arr2).unwrap(),
"[0.3]",
"BF16 array should serialize 0.3 as '0.3'"
);
}

#[test]
fn test_typed_float_array_serialization_roundtrip() {
let input = "[0.3,0.1,0.7,1.0,2.5,100.0]";
let fp_types = [
FloatType::F16,
FloatType::BF16,
FloatType::F32,
FloatType::F64,
];

let jsons: Vec<String> = fp_types
.iter()
.map(|&fp_type| {
let seed = IValueDeserSeed::new(Some(FPHAConfig::new_with_type(fp_type)));
let mut de = serde_json::Deserializer::from_str(input);
let arr = serde::de::DeserializeSeed::deserialize(seed, &mut de)
.unwrap()
.into_array()
.unwrap();
let json_out = serde_json::to_string(&arr).unwrap();
assert_eq!(
json_out, input,
"{fp_type} round-trip should preserve the original JSON string"
);
json_out
})
.collect();

for pair in jsons.windows(2) {
assert_eq!(
pair[0], pair[1],
"all float types should produce identical JSON"
);
}
}

#[test]
fn test_f16_precision_loss_produces_different_but_short_representation() {
// Values with more significant digits than f16 can represent (~3.3 digits).
// The stored f16 value differs from the original, so the serialized string
// must differ too — but it should still be the shortest string that
// round-trips through f16.
let cases: &[(&str, &str)] = &[
("3.14159", "3.14"), // pi truncated: f16 stores 3.140625
("42.42", "42.4"), // f16 stores 42.40625
("12.345", "12.34"), // f16 stores 12.34375
("0.5678", "0.568"), // f16 stores 0.56787109375
];

for &(input, expected_f16) in cases {
let json_input = format!("[{input}]");

let f16_arr: IArray = {
let seed = IValueDeserSeed::new(Some(FPHAConfig::new_with_type(FloatType::F16)));
let mut de = serde_json::Deserializer::from_str(&json_input);
serde::de::DeserializeSeed::deserialize(seed, &mut de)
.unwrap()
.into_array()
.unwrap()
};
let f16_json = serde_json::to_string(&f16_arr).unwrap();
assert_eq!(
f16_json,
format!("[{expected_f16}]"),
"F16 of {input}: should serialize as shortest f16 representation"
);

// Same values through F32 should preserve the original (enough precision)
let f32_arr: IArray = {
let seed = IValueDeserSeed::new(Some(FPHAConfig::new_with_type(FloatType::F32)));
let mut de = serde_json::Deserializer::from_str(&json_input);
serde::de::DeserializeSeed::deserialize(seed, &mut de)
.unwrap()
.into_array()
.unwrap()
};
let f32_json = serde_json::to_string(&f32_arr).unwrap();
assert_eq!(
f32_json, json_input,
"F32 of {input}: should preserve the original representation"
);
}
}

#[test]
fn test_negative_float_array_serialization() {
let input = "[-0.3,-0.1,-1.0,-2.5,-100.0]";
let fp_types = [
FloatType::F16,
FloatType::BF16,
FloatType::F32,
FloatType::F64,
];

for &fp_type in &fp_types {
let seed = IValueDeserSeed::new(Some(FPHAConfig::new_with_type(fp_type)));
let mut de = serde_json::Deserializer::from_str(input);
let arr = serde::de::DeserializeSeed::deserialize(seed, &mut de)
.unwrap()
.into_array()
.unwrap();
let json_out = serde_json::to_string(&arr).unwrap();
assert_eq!(
json_out, input,
"{fp_type} negative round-trip should preserve the original JSON string"
);
}
}

#[test]
fn test_negative_f16_precision_loss_produces_short_representation() {
let cases: &[(&str, &str)] = &[
("-3.14159", "-3.14"),
("-42.42", "-42.4"),
("-0.5678", "-0.568"),
];

for &(input, expected_f16) in cases {
let json_input = format!("[{input}]");
let seed = IValueDeserSeed::new(Some(FPHAConfig::new_with_type(FloatType::F16)));
let mut de = serde_json::Deserializer::from_str(&json_input);
let arr = serde::de::DeserializeSeed::deserialize(seed, &mut de)
.unwrap()
.into_array()
.unwrap();
let json_out = serde_json::to_string(&arr).unwrap();
assert_eq!(
json_out,
format!("[{expected_f16}]"),
"F16 of {input}: negative should serialize as shortest f16 representation"
);
}
}
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
295 changes: 290 additions & 5 deletions src/ser.rs
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
use half::{bf16, f16};
use serde::{
ser::{
Error as _, Impossible, SerializeMap, SerializeSeq, SerializeStruct,
Expand All@@ -7,7 +8,53 @@ use serde::{
};
use serde_json::error::Error;

use crate::{array::TryCollect, DestructuredRef, IArray, INumber, IObject, IString, IValue};
use crate::{
array::{ArraySliceRef, TryCollect},
DestructuredRef, IArray, INumber, IObject, IString, IValue,
};

/// Rounds an f64 to the given number of significant decimal digits.
#[inline]
fn round_to_sig_digits(val: f64, sig_digits: u32) -> f64 {
// how many digits are left of the decimal point, minus one
// OR: what power of 10 is this number closest to? (e.g. 100 -> 10^2, 0.001 -> 10^-3)
let order_of_magnitude = val.abs().log10().floor() as i32;
// Multiplier that shifts the desired significant digits into the integer part,
// so that f64::round() can snap to the nearest integer and discard the rest.
// e.g. for val=3.14, order_of_magnitude = 0, sig_digits=2: scale=10, so 3.14*10=31.4 → round→31 → 31/10=3.1
let scale = 10f64.powi(sig_digits as i32 - 1 - order_of_magnitude);
(val * scale).round() / scale
}

/// Finds an f64 value that, when formatted by ryu's f64 algorithm, produces
/// the shortest decimal string that still round-trips through the target
/// half-precision type (f16 or bf16).
///
/// ryu only supports f32/f64, and serde has no `serialize_f16`. Since f16/bf16
/// have far fewer distinct values than f32, there exist shorter representations
/// that uniquely identify the half value. For example, f16(0.3) = 0.300048828125,
/// and "0.3" parsed as f16 gives back the same bits — so "0.3" is valid.
///
/// The approach: try rounding to increasing significant digits until the
/// rounded value round-trips through the type. Then return that f64
/// value, so that `serialize_f64` (via ryu) reproduces it.
fn find_shortest_roundtrip_f64(f64_val: f64, roundtrips: impl Fn(f64) -> bool) -> f64 {
if !f64_val.is_finite() || f64_val.fract() == 0.0 {
return f64_val;
}
// With our usage(F16/BF16), the loop will need only ~4 iterations, since max significant digits needed is ~4
// Example: f16(3.14159) stores 3.140625
// sig_digits=1 → 3.0 → f16(3.0)=3.0 ≠ 3.140625 ❌
// sig_digits=2 → 3.1 → f16(3.1)=3.099.. ≠ 3.140625 ❌
// sig_digits=3 → 3.14 → f16(3.14)=3.140625 ✅ → returns 3.14
for sig_digits in 1..=5u32 {
let rounded = round_to_sig_digits(f64_val, sig_digits);
if roundtrips(rounded) {
return rounded;
}
}
f64_val
}

impl Serialize for IValue {
#[inline]
Expand DownExpand Up@@ -55,11 +102,50 @@ impl Serialize for IArray {
where
S: Serializer,
{
let mut s = serializer.serialize_seq(Some(self.len()))?;
for v in self {
s.serialize_element(&v)?;
match self.as_slice() {
// Serialize typed float arrays with the shortest representation that
// round-trips through the stored precision. Without this, all floats
// would be promoted to f64 via INumber, and ryu's f64 algorithm would
// emit unnecessarily long strings (e.g. "0.3" stored as f32 would
// serialize as "0.30000001192092896" instead of "0.3").
//
// F32: serialize directly as f32 so ryu uses its f32 algorithm.
// F16/BF16: ryu has no f16 mode and serde has no serialize_f16, so we
// find the shortest decimal that round-trips through the half type and
// pass the corresponding f64 value to serialize_f64.
ArraySliceRef::F32(slice) => {
let mut s = serializer.serialize_seq(Some(slice.len()))?;
for &v in slice {
s.serialize_element(&v)?;
}
s.end()
}
ArraySliceRef::F16(slice) => {
let mut s = serializer.serialize_seq(Some(slice.len()))?;
for &v in slice {
let f64_val = f64::from(v);
let shortest = find_shortest_roundtrip_f64(f64_val, |p| f16::from_f64(p) == v);
s.serialize_element(&shortest)?;
}
s.end()
}
ArraySliceRef::BF16(slice) => {
let mut s = serializer.serialize_seq(Some(slice.len()))?;
for &v in slice {
let f64_val = f64::from(v);
let shortest = find_shortest_roundtrip_f64(f64_val, |p| bf16::from_f64(p) == v);
s.serialize_element(&shortest)?;
}
s.end()
}
Comment thread
AvivDavid23 marked this conversation as resolved.
_ => {
let mut s = serializer.serialize_seq(Some(self.len()))?;
for v in self {
s.serialize_element(&v)?;
}
s.end()
}
}
s.end()
}
}

Expand DownExpand Up@@ -635,3 +721,202 @@ where
{
value.serialize(ValueSerializer)
}

#[cfg(test)]
mod tests {
use crate::array::{ArraySliceRef, FloatType};
use crate::{FPHAConfig, IArray, IValue, IValueDeserSeed};

#[test]
fn test_f32_array_serialization_preserves_short_representation() {
let mut arr = IArray::new();
arr.push_with_fp_type(IValue::from(0.3), FloatType::F32)
.unwrap();
assert!(matches!(arr.as_slice(), ArraySliceRef::F32(_)));

let json = serde_json::to_string(&arr).unwrap();
assert_eq!(
json, "[0.3]",
"F32 array should serialize 0.3 as '0.3', not with extra f64 precision digits"
);
}

#[test]
fn test_f64_array_serialization_preserves_short_representation() {
let mut arr = IArray::new();
arr.push_with_fp_type(IValue::from(0.3), FloatType::F64)
.unwrap();
assert!(matches!(arr.as_slice(), ArraySliceRef::F64(_)));

let json = serde_json::to_string(&arr).unwrap();
assert_eq!(json, "[0.3]");
}

#[test]
fn test_f16_array_serialization_preserves_short_representation() {
let mut arr = IArray::new();
arr.push_with_fp_type(IValue::from(1.5), FloatType::F16)
.unwrap();
assert_eq!(serde_json::to_string(&arr).unwrap(), "[1.5]");

let mut arr2 = IArray::new();
arr2.push_with_fp_type(IValue::from(0.3), FloatType::F16)
.unwrap();
assert_eq!(
serde_json::to_string(&arr2).unwrap(),
"[0.3]",
"F16 array should serialize 0.3 as '0.3', not '0.30004883' or '0.300048828125'"
);
}

#[test]
fn test_bf16_array_serialization_preserves_short_representation() {
let mut arr = IArray::new();
arr.push_with_fp_type(IValue::from(1.5), FloatType::BF16)
.unwrap();
assert_eq!(serde_json::to_string(&arr).unwrap(), "[1.5]");

let mut arr2 = IArray::new();
arr2.push_with_fp_type(IValue::from(0.3), FloatType::BF16)
.unwrap();
assert_eq!(
serde_json::to_string(&arr2).unwrap(),
"[0.3]",
"BF16 array should serialize 0.3 as '0.3'"
);
}

#[test]
fn test_typed_float_array_serialization_roundtrip() {
let input = "[0.3,0.1,0.7,1.0,2.5,100.0]";
let fp_types = [
FloatType::F16,
FloatType::BF16,
FloatType::F32,
FloatType::F64,
];

let jsons: Vec<String> = fp_types
.iter()
.map(|&fp_type| {
let seed = IValueDeserSeed::new(Some(FPHAConfig::new_with_type(fp_type)));
let mut de = serde_json::Deserializer::from_str(input);
let arr = serde::de::DeserializeSeed::deserialize(seed, &mut de)
.unwrap()
.into_array()
.unwrap();
let json_out = serde_json::to_string(&arr).unwrap();
assert_eq!(
json_out, input,
"{fp_type} round-trip should preserve the original JSON string"
);
json_out
})
.collect();

for pair in jsons.windows(2) {
assert_eq!(
pair[0], pair[1],
"all float types should produce identical JSON"
);
}
}

#[test]
fn test_f16_precision_loss_produces_different_but_short_representation() {
// Values with more significant digits than f16 can represent (~3.3 digits).
// The stored f16 value differs from the original, so the serialized string
// must differ too — but it should still be the shortest string that
// round-trips through f16.
let cases: &[(&str, &str)] = &[
("3.14159", "3.14"), // pi truncated: f16 stores 3.140625
("42.42", "42.4"), // f16 stores 42.40625
("12.345", "12.34"), // f16 stores 12.34375
("0.5678", "0.568"), // f16 stores 0.56787109375
];

for &(input, expected_f16) in cases {
let json_input = format!("[{input}]");

let f16_arr: IArray = {
let seed = IValueDeserSeed::new(Some(FPHAConfig::new_with_type(FloatType::F16)));
let mut de = serde_json::Deserializer::from_str(&json_input);
serde::de::DeserializeSeed::deserialize(seed, &mut de)
.unwrap()
.into_array()
.unwrap()
};
let f16_json = serde_json::to_string(&f16_arr).unwrap();
assert_eq!(
f16_json,
format!("[{expected_f16}]"),
"F16 of {input}: should serialize as shortest f16 representation"
);

// Same values through F32 should preserve the original (enough precision)
let f32_arr: IArray = {
let seed = IValueDeserSeed::new(Some(FPHAConfig::new_with_type(FloatType::F32)));
let mut de = serde_json::Deserializer::from_str(&json_input);
serde::de::DeserializeSeed::deserialize(seed, &mut de)
.unwrap()
.into_array()
.unwrap()
};
let f32_json = serde_json::to_string(&f32_arr).unwrap();
assert_eq!(
f32_json, json_input,
"F32 of {input}: should preserve the original representation"
);
}
}

#[test]
fn test_negative_float_array_serialization() {
let input = "[-0.3,-0.1,-1.0,-2.5,-100.0]";
let fp_types = [
FloatType::F16,
FloatType::BF16,
FloatType::F32,
FloatType::F64,
];

for &fp_type in &fp_types {
let seed = IValueDeserSeed::new(Some(FPHAConfig::new_with_type(fp_type)));
let mut de = serde_json::Deserializer::from_str(input);
let arr = serde::de::DeserializeSeed::deserialize(seed, &mut de)
.unwrap()
.into_array()
.unwrap();
let json_out = serde_json::to_string(&arr).unwrap();
assert_eq!(
json_out, input,
"{fp_type} negative round-trip should preserve the original JSON string"
);
}
}

#[test]
fn test_negative_f16_precision_loss_produces_short_representation() {
let cases: &[(&str, &str)] = &[
("-3.14159", "-3.14"),
("-42.42", "-42.4"),
("-0.5678", "-0.568"),
];

for &(input, expected_f16) in cases {
let json_input = format!("[{input}]");
let seed = IValueDeserSeed::new(Some(FPHAConfig::new_with_type(FloatType::F16)));
let mut de = serde_json::Deserializer::from_str(&json_input);
let arr = serde::de::DeserializeSeed::deserialize(seed, &mut de)
.unwrap()
.into_array()
.unwrap();
let json_out = serde_json::to_string(&arr).unwrap();
assert_eq!(
json_out,
format!("[{expected_f16}]"),
"F16 of {input}: negative should serialize as shortest f16 representation"
);
}
}
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
295 changes: 290 additions & 5 deletions src/ser.rs
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
use half::{bf16, f16};
use serde::{
ser::{
Error as _, Impossible, SerializeMap, SerializeSeq, SerializeStruct,
Expand All@@ -7,7 +8,53 @@ use serde::{
};
use serde_json::error::Error;

use crate::{array::TryCollect, DestructuredRef, IArray, INumber, IObject, IString, IValue};
use crate::{
array::{ArraySliceRef, TryCollect},
DestructuredRef, IArray, INumber, IObject, IString, IValue,
};

/// Rounds an f64 to the given number of significant decimal digits.
#[inline]
fn round_to_sig_digits(val: f64, sig_digits: u32) -> f64 {
// how many digits are left of the decimal point, minus one
// OR: what power of 10 is this number closest to? (e.g. 100 -> 10^2, 0.001 -> 10^-3)
let order_of_magnitude = val.abs().log10().floor() as i32;
// Multiplier that shifts the desired significant digits into the integer part,
// so that f64::round() can snap to the nearest integer and discard the rest.
// e.g. for val=3.14, order_of_magnitude = 0, sig_digits=2: scale=10, so 3.14*10=31.4 → round→31 → 31/10=3.1
let scale = 10f64.powi(sig_digits as i32 - 1 - order_of_magnitude);
(val * scale).round() / scale
}

/// Finds an f64 value that, when formatted by ryu's f64 algorithm, produces
/// the shortest decimal string that still round-trips through the target
/// half-precision type (f16 or bf16).
///
/// ryu only supports f32/f64, and serde has no `serialize_f16`. Since f16/bf16
/// have far fewer distinct values than f32, there exist shorter representations
/// that uniquely identify the half value. For example, f16(0.3) = 0.300048828125,
/// and "0.3" parsed as f16 gives back the same bits — so "0.3" is valid.
///
/// The approach: try rounding to increasing significant digits until the
/// rounded value round-trips through the type. Then return that f64
/// value, so that `serialize_f64` (via ryu) reproduces it.
fn find_shortest_roundtrip_f64(f64_val: f64, roundtrips: impl Fn(f64) -> bool) -> f64 {
if !f64_val.is_finite() || f64_val.fract() == 0.0 {
return f64_val;
}
// With our usage(F16/BF16), the loop will need only ~4 iterations, since max significant digits needed is ~4
// Example: f16(3.14159) stores 3.140625
// sig_digits=1 → 3.0 → f16(3.0)=3.0 ≠ 3.140625 ❌
// sig_digits=2 → 3.1 → f16(3.1)=3.099.. ≠ 3.140625 ❌
// sig_digits=3 → 3.14 → f16(3.14)=3.140625 ✅ → returns 3.14
for sig_digits in 1..=5u32 {
let rounded = round_to_sig_digits(f64_val, sig_digits);
if roundtrips(rounded) {
return rounded;
}
}
f64_val
}

impl Serialize for IValue {
#[inline]
Expand DownExpand Up@@ -55,11 +102,50 @@ impl Serialize for IArray {
where
S: Serializer,
{
let mut s = serializer.serialize_seq(Some(self.len()))?;
for v in self {
s.serialize_element(&v)?;
match self.as_slice() {
// Serialize typed float arrays with the shortest representation that
// round-trips through the stored precision. Without this, all floats
// would be promoted to f64 via INumber, and ryu's f64 algorithm would
// emit unnecessarily long strings (e.g. "0.3" stored as f32 would
// serialize as "0.30000001192092896" instead of "0.3").
//
// F32: serialize directly as f32 so ryu uses its f32 algorithm.
// F16/BF16: ryu has no f16 mode and serde has no serialize_f16, so we
// find the shortest decimal that round-trips through the half type and
// pass the corresponding f64 value to serialize_f64.
ArraySliceRef::F32(slice) => {
let mut s = serializer.serialize_seq(Some(slice.len()))?;
for &v in slice {
s.serialize_element(&v)?;
}
s.end()
}
ArraySliceRef::F16(slice) => {
let mut s = serializer.serialize_seq(Some(slice.len()))?;
for &v in slice {
let f64_val = f64::from(v);
let shortest = find_shortest_roundtrip_f64(f64_val, |p| f16::from_f64(p) == v);
s.serialize_element(&shortest)?;
}
s.end()
}
ArraySliceRef::BF16(slice) => {
let mut s = serializer.serialize_seq(Some(slice.len()))?;
for &v in slice {
let f64_val = f64::from(v);
let shortest = find_shortest_roundtrip_f64(f64_val, |p| bf16::from_f64(p) == v);
s.serialize_element(&shortest)?;
}
s.end()
}
Comment thread
AvivDavid23 marked this conversation as resolved.
_ => {
let mut s = serializer.serialize_seq(Some(self.len()))?;
for v in self {
s.serialize_element(&v)?;
}
s.end()
}
}
s.end()
}
}

Expand DownExpand Up@@ -635,3 +721,202 @@ where
{
value.serialize(ValueSerializer)
}

#[cfg(test)]
mod tests {
use crate::array::{ArraySliceRef, FloatType};
use crate::{FPHAConfig, IArray, IValue, IValueDeserSeed};

#[test]
fn test_f32_array_serialization_preserves_short_representation() {
let mut arr = IArray::new();
arr.push_with_fp_type(IValue::from(0.3), FloatType::F32)
.unwrap();
assert!(matches!(arr.as_slice(), ArraySliceRef::F32(_)));

let json = serde_json::to_string(&arr).unwrap();
assert_eq!(
json, "[0.3]",
"F32 array should serialize 0.3 as '0.3', not with extra f64 precision digits"
);
}

#[test]
fn test_f64_array_serialization_preserves_short_representation() {
let mut arr = IArray::new();
arr.push_with_fp_type(IValue::from(0.3), FloatType::F64)
.unwrap();
assert!(matches!(arr.as_slice(), ArraySliceRef::F64(_)));

let json = serde_json::to_string(&arr).unwrap();
assert_eq!(json, "[0.3]");
}

#[test]
fn test_f16_array_serialization_preserves_short_representation() {
let mut arr = IArray::new();
arr.push_with_fp_type(IValue::from(1.5), FloatType::F16)
.unwrap();
assert_eq!(serde_json::to_string(&arr).unwrap(), "[1.5]");

let mut arr2 = IArray::new();
arr2.push_with_fp_type(IValue::from(0.3), FloatType::F16)
.unwrap();
assert_eq!(
serde_json::to_string(&arr2).unwrap(),
"[0.3]",
"F16 array should serialize 0.3 as '0.3', not '0.30004883' or '0.300048828125'"
);
}

#[test]
fn test_bf16_array_serialization_preserves_short_representation() {
let mut arr = IArray::new();
arr.push_with_fp_type(IValue::from(1.5), FloatType::BF16)
.unwrap();
assert_eq!(serde_json::to_string(&arr).unwrap(), "[1.5]");

let mut arr2 = IArray::new();
arr2.push_with_fp_type(IValue::from(0.3), FloatType::BF16)
.unwrap();
assert_eq!(
serde_json::to_string(&arr2).unwrap(),
"[0.3]",
"BF16 array should serialize 0.3 as '0.3'"
);
}

#[test]
fn test_typed_float_array_serialization_roundtrip() {
let input = "[0.3,0.1,0.7,1.0,2.5,100.0]";
let fp_types = [
FloatType::F16,
FloatType::BF16,
FloatType::F32,
FloatType::F64,
];

let jsons: Vec<String> = fp_types
.iter()
.map(|&fp_type| {
let seed = IValueDeserSeed::new(Some(FPHAConfig::new_with_type(fp_type)));
let mut de = serde_json::Deserializer::from_str(input);
let arr = serde::de::DeserializeSeed::deserialize(seed, &mut de)
.unwrap()
.into_array()
.unwrap();
let json_out = serde_json::to_string(&arr).unwrap();
assert_eq!(
json_out, input,
"{fp_type} round-trip should preserve the original JSON string"
);
json_out
})
.collect();

for pair in jsons.windows(2) {
assert_eq!(
pair[0], pair[1],
"all float types should produce identical JSON"
);
}
}

#[test]
fn test_f16_precision_loss_produces_different_but_short_representation() {
// Values with more significant digits than f16 can represent (~3.3 digits).
// The stored f16 value differs from the original, so the serialized string
// must differ too — but it should still be the shortest string that
// round-trips through f16.
let cases: &[(&str, &str)] = &[
("3.14159", "3.14"), // pi truncated: f16 stores 3.140625
("42.42", "42.4"), // f16 stores 42.40625
("12.345", "12.34"), // f16 stores 12.34375
("0.5678", "0.568"), // f16 stores 0.56787109375
];

for &(input, expected_f16) in cases {
let json_input = format!("[{input}]");

let f16_arr: IArray = {
let seed = IValueDeserSeed::new(Some(FPHAConfig::new_with_type(FloatType::F16)));
let mut de = serde_json::Deserializer::from_str(&json_input);
serde::de::DeserializeSeed::deserialize(seed, &mut de)
.unwrap()
.into_array()
.unwrap()
};
let f16_json = serde_json::to_string(&f16_arr).unwrap();
assert_eq!(
f16_json,
format!("[{expected_f16}]"),
"F16 of {input}: should serialize as shortest f16 representation"
);

// Same values through F32 should preserve the original (enough precision)
let f32_arr: IArray = {
let seed = IValueDeserSeed::new(Some(FPHAConfig::new_with_type(FloatType::F32)));
let mut de = serde_json::Deserializer::from_str(&json_input);
serde::de::DeserializeSeed::deserialize(seed, &mut de)
.unwrap()
.into_array()
.unwrap()
};
let f32_json = serde_json::to_string(&f32_arr).unwrap();
assert_eq!(
f32_json, json_input,
"F32 of {input}: should preserve the original representation"
);
}
}

#[test]
fn test_negative_float_array_serialization() {
let input = "[-0.3,-0.1,-1.0,-2.5,-100.0]";
let fp_types = [
FloatType::F16,
FloatType::BF16,
FloatType::F32,
FloatType::F64,
];

for &fp_type in &fp_types {
let seed = IValueDeserSeed::new(Some(FPHAConfig::new_with_type(fp_type)));
let mut de = serde_json::Deserializer::from_str(input);
let arr = serde::de::DeserializeSeed::deserialize(seed, &mut de)
.unwrap()
.into_array()
.unwrap();
let json_out = serde_json::to_string(&arr).unwrap();
assert_eq!(
json_out, input,
"{fp_type} negative round-trip should preserve the original JSON string"
);
}
}

#[test]
fn test_negative_f16_precision_loss_produces_short_representation() {
let cases: &[(&str, &str)] = &[
("-3.14159", "-3.14"),
("-42.42", "-42.4"),
("-0.5678", "-0.568"),
];

for &(input, expected_f16) in cases {
let json_input = format!("[{input}]");
let seed = IValueDeserSeed::new(Some(FPHAConfig::new_with_type(FloatType::F16)));
let mut de = serde_json::Deserializer::from_str(&json_input);
let arr = serde::de::DeserializeSeed::deserialize(seed, &mut de)
.unwrap()
.into_array()
.unwrap();
let json_out = serde_json::to_string(&arr).unwrap();
assert_eq!(
json_out,
format!("[{expected_f16}]"),
"F16 of {input}: negative should serialize as shortest f16 representation"
);
}
}
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
295 changes: 290 additions & 5 deletions src/ser.rs
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
use half::{bf16, f16};
use serde::{
ser::{
Error as _, Impossible, SerializeMap, SerializeSeq, SerializeStruct,
Expand All@@ -7,7 +8,53 @@ use serde::{
};
use serde_json::error::Error;

use crate::{array::TryCollect, DestructuredRef, IArray, INumber, IObject, IString, IValue};
use crate::{
array::{ArraySliceRef, TryCollect},
DestructuredRef, IArray, INumber, IObject, IString, IValue,
};

/// Rounds an f64 to the given number of significant decimal digits.
#[inline]
fn round_to_sig_digits(val: f64, sig_digits: u32) -> f64 {
// how many digits are left of the decimal point, minus one
// OR: what power of 10 is this number closest to? (e.g. 100 -> 10^2, 0.001 -> 10^-3)
let order_of_magnitude = val.abs().log10().floor() as i32;
// Multiplier that shifts the desired significant digits into the integer part,
// so that f64::round() can snap to the nearest integer and discard the rest.
// e.g. for val=3.14, order_of_magnitude = 0, sig_digits=2: scale=10, so 3.14*10=31.4 → round→31 → 31/10=3.1
let scale = 10f64.powi(sig_digits as i32 - 1 - order_of_magnitude);
(val * scale).round() / scale
}

/// Finds an f64 value that, when formatted by ryu's f64 algorithm, produces
/// the shortest decimal string that still round-trips through the target
/// half-precision type (f16 or bf16).
///
/// ryu only supports f32/f64, and serde has no `serialize_f16`. Since f16/bf16
/// have far fewer distinct values than f32, there exist shorter representations
/// that uniquely identify the half value. For example, f16(0.3) = 0.300048828125,
/// and "0.3" parsed as f16 gives back the same bits — so "0.3" is valid.
///
/// The approach: try rounding to increasing significant digits until the
/// rounded value round-trips through the type. Then return that f64
/// value, so that `serialize_f64` (via ryu) reproduces it.
fn find_shortest_roundtrip_f64(f64_val: f64, roundtrips: impl Fn(f64) -> bool) -> f64 {
if !f64_val.is_finite() || f64_val.fract() == 0.0 {
return f64_val;
}
// With our usage(F16/BF16), the loop will need only ~4 iterations, since max significant digits needed is ~4
// Example: f16(3.14159) stores 3.140625
// sig_digits=1 → 3.0 → f16(3.0)=3.0 ≠ 3.140625 ❌
// sig_digits=2 → 3.1 → f16(3.1)=3.099.. ≠ 3.140625 ❌
// sig_digits=3 → 3.14 → f16(3.14)=3.140625 ✅ → returns 3.14
for sig_digits in 1..=5u32 {
let rounded = round_to_sig_digits(f64_val, sig_digits);
if roundtrips(rounded) {
return rounded;
}
}
f64_val
}

impl Serialize for IValue {
#[inline]
Expand DownExpand Up@@ -55,11 +102,50 @@ impl Serialize for IArray {
where
S: Serializer,
{
let mut s = serializer.serialize_seq(Some(self.len()))?;
for v in self {
s.serialize_element(&v)?;
match self.as_slice() {
// Serialize typed float arrays with the shortest representation that
// round-trips through the stored precision. Without this, all floats
// would be promoted to f64 via INumber, and ryu's f64 algorithm would
// emit unnecessarily long strings (e.g. "0.3" stored as f32 would
// serialize as "0.30000001192092896" instead of "0.3").
//
// F32: serialize directly as f32 so ryu uses its f32 algorithm.
// F16/BF16: ryu has no f16 mode and serde has no serialize_f16, so we
// find the shortest decimal that round-trips through the half type and
// pass the corresponding f64 value to serialize_f64.
ArraySliceRef::F32(slice) => {
let mut s = serializer.serialize_seq(Some(slice.len()))?;
for &v in slice {
s.serialize_element(&v)?;
}
s.end()
}
ArraySliceRef::F16(slice) => {
let mut s = serializer.serialize_seq(Some(slice.len()))?;
for &v in slice {
let f64_val = f64::from(v);
let shortest = find_shortest_roundtrip_f64(f64_val, |p| f16::from_f64(p) == v);
s.serialize_element(&shortest)?;
}
s.end()
}
ArraySliceRef::BF16(slice) => {
let mut s = serializer.serialize_seq(Some(slice.len()))?;
for &v in slice {
let f64_val = f64::from(v);
let shortest = find_shortest_roundtrip_f64(f64_val, |p| bf16::from_f64(p) == v);
s.serialize_element(&shortest)?;
}
s.end()
}
Comment thread
AvivDavid23 marked this conversation as resolved.
_ => {
let mut s = serializer.serialize_seq(Some(self.len()))?;
for v in self {
s.serialize_element(&v)?;
}
s.end()
}
}
s.end()
}
}

Expand DownExpand Up@@ -635,3 +721,202 @@ where
{
value.serialize(ValueSerializer)
}

#[cfg(test)]
mod tests {
use crate::array::{ArraySliceRef, FloatType};
use crate::{FPHAConfig, IArray, IValue, IValueDeserSeed};

#[test]
fn test_f32_array_serialization_preserves_short_representation() {
let mut arr = IArray::new();
arr.push_with_fp_type(IValue::from(0.3), FloatType::F32)
.unwrap();
assert!(matches!(arr.as_slice(), ArraySliceRef::F32(_)));

let json = serde_json::to_string(&arr).unwrap();
assert_eq!(
json, "[0.3]",
"F32 array should serialize 0.3 as '0.3', not with extra f64 precision digits"
);
}

#[test]
fn test_f64_array_serialization_preserves_short_representation() {
let mut arr = IArray::new();
arr.push_with_fp_type(IValue::from(0.3), FloatType::F64)
.unwrap();
assert!(matches!(arr.as_slice(), ArraySliceRef::F64(_)));

let json = serde_json::to_string(&arr).unwrap();
assert_eq!(json, "[0.3]");
}

#[test]
fn test_f16_array_serialization_preserves_short_representation() {
let mut arr = IArray::new();
arr.push_with_fp_type(IValue::from(1.5), FloatType::F16)
.unwrap();
assert_eq!(serde_json::to_string(&arr).unwrap(), "[1.5]");

let mut arr2 = IArray::new();
arr2.push_with_fp_type(IValue::from(0.3), FloatType::F16)
.unwrap();
assert_eq!(
serde_json::to_string(&arr2).unwrap(),
"[0.3]",
"F16 array should serialize 0.3 as '0.3', not '0.30004883' or '0.300048828125'"
);
}

#[test]
fn test_bf16_array_serialization_preserves_short_representation() {
let mut arr = IArray::new();
arr.push_with_fp_type(IValue::from(1.5), FloatType::BF16)
.unwrap();
assert_eq!(serde_json::to_string(&arr).unwrap(), "[1.5]");

let mut arr2 = IArray::new();
arr2.push_with_fp_type(IValue::from(0.3), FloatType::BF16)
.unwrap();
assert_eq!(
serde_json::to_string(&arr2).unwrap(),
"[0.3]",
"BF16 array should serialize 0.3 as '0.3'"
);
}

#[test]
fn test_typed_float_array_serialization_roundtrip() {
let input = "[0.3,0.1,0.7,1.0,2.5,100.0]";
let fp_types = [
FloatType::F16,
FloatType::BF16,
FloatType::F32,
FloatType::F64,
];

let jsons: Vec<String> = fp_types
.iter()
.map(|&fp_type| {
let seed = IValueDeserSeed::new(Some(FPHAConfig::new_with_type(fp_type)));
let mut de = serde_json::Deserializer::from_str(input);
let arr = serde::de::DeserializeSeed::deserialize(seed, &mut de)
.unwrap()
.into_array()
.unwrap();
let json_out = serde_json::to_string(&arr).unwrap();
assert_eq!(
json_out, input,
"{fp_type} round-trip should preserve the original JSON string"
);
json_out
})
.collect();

for pair in jsons.windows(2) {
assert_eq!(
pair[0], pair[1],
"all float types should produce identical JSON"
);
}
}

#[test]
fn test_f16_precision_loss_produces_different_but_short_representation() {
// Values with more significant digits than f16 can represent (~3.3 digits).
// The stored f16 value differs from the original, so the serialized string
// must differ too — but it should still be the shortest string that
// round-trips through f16.
let cases: &[(&str, &str)] = &[
("3.14159", "3.14"), // pi truncated: f16 stores 3.140625
("42.42", "42.4"), // f16 stores 42.40625
("12.345", "12.34"), // f16 stores 12.34375
("0.5678", "0.568"), // f16 stores 0.56787109375
];

for &(input, expected_f16) in cases {
let json_input = format!("[{input}]");

let f16_arr: IArray = {
let seed = IValueDeserSeed::new(Some(FPHAConfig::new_with_type(FloatType::F16)));
let mut de = serde_json::Deserializer::from_str(&json_input);
serde::de::DeserializeSeed::deserialize(seed, &mut de)
.unwrap()
.into_array()
.unwrap()
};
let f16_json = serde_json::to_string(&f16_arr).unwrap();
assert_eq!(
f16_json,
format!("[{expected_f16}]"),
"F16 of {input}: should serialize as shortest f16 representation"
);

// Same values through F32 should preserve the original (enough precision)
let f32_arr: IArray = {
let seed = IValueDeserSeed::new(Some(FPHAConfig::new_with_type(FloatType::F32)));
let mut de = serde_json::Deserializer::from_str(&json_input);
serde::de::DeserializeSeed::deserialize(seed, &mut de)
.unwrap()
.into_array()
.unwrap()
};
let f32_json = serde_json::to_string(&f32_arr).unwrap();
assert_eq!(
f32_json, json_input,
"F32 of {input}: should preserve the original representation"
);
}
}

#[test]
fn test_negative_float_array_serialization() {
let input = "[-0.3,-0.1,-1.0,-2.5,-100.0]";
let fp_types = [
FloatType::F16,
FloatType::BF16,
FloatType::F32,
FloatType::F64,
];

for &fp_type in &fp_types {
let seed = IValueDeserSeed::new(Some(FPHAConfig::new_with_type(fp_type)));
let mut de = serde_json::Deserializer::from_str(input);
let arr = serde::de::DeserializeSeed::deserialize(seed, &mut de)
.unwrap()
.into_array()
.unwrap();
let json_out = serde_json::to_string(&arr).unwrap();
assert_eq!(
json_out, input,
"{fp_type} negative round-trip should preserve the original JSON string"
);
}
}

#[test]
fn test_negative_f16_precision_loss_produces_short_representation() {
let cases: &[(&str, &str)] = &[
("-3.14159", "-3.14"),
("-42.42", "-42.4"),
("-0.5678", "-0.568"),
];

for &(input, expected_f16) in cases {
let json_input = format!("[{input}]");
let seed = IValueDeserSeed::new(Some(FPHAConfig::new_with_type(FloatType::F16)));
let mut de = serde_json::Deserializer::from_str(&json_input);
let arr = serde::de::DeserializeSeed::deserialize(seed, &mut de)
.unwrap()
.into_array()
.unwrap();
let json_out = serde_json::to_string(&arr).unwrap();
assert_eq!(
json_out,
format!("[{expected_f16}]"),
"F16 of {input}: negative should serialize as shortest f16 representation"
);
}
}
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
295 changes: 290 additions & 5 deletions src/ser.rs
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
use half::{bf16, f16};
use serde::{
ser::{
Error as _, Impossible, SerializeMap, SerializeSeq, SerializeStruct,
Expand All@@ -7,7 +8,53 @@ use serde::{
};
use serde_json::error::Error;

use crate::{array::TryCollect, DestructuredRef, IArray, INumber, IObject, IString, IValue};
use crate::{
array::{ArraySliceRef, TryCollect},
DestructuredRef, IArray, INumber, IObject, IString, IValue,
};

/// Rounds an f64 to the given number of significant decimal digits.
#[inline]
fn round_to_sig_digits(val: f64, sig_digits: u32) -> f64 {
// how many digits are left of the decimal point, minus one
// OR: what power of 10 is this number closest to? (e.g. 100 -> 10^2, 0.001 -> 10^-3)
let order_of_magnitude = val.abs().log10().floor() as i32;
// Multiplier that shifts the desired significant digits into the integer part,
// so that f64::round() can snap to the nearest integer and discard the rest.
// e.g. for val=3.14, order_of_magnitude = 0, sig_digits=2: scale=10, so 3.14*10=31.4 → round→31 → 31/10=3.1
let scale = 10f64.powi(sig_digits as i32 - 1 - order_of_magnitude);
(val * scale).round() / scale
}

/// Finds an f64 value that, when formatted by ryu's f64 algorithm, produces
/// the shortest decimal string that still round-trips through the target
/// half-precision type (f16 or bf16).
///
/// ryu only supports f32/f64, and serde has no `serialize_f16`. Since f16/bf16
/// have far fewer distinct values than f32, there exist shorter representations
/// that uniquely identify the half value. For example, f16(0.3) = 0.300048828125,
/// and "0.3" parsed as f16 gives back the same bits — so "0.3" is valid.
///
/// The approach: try rounding to increasing significant digits until the
/// rounded value round-trips through the type. Then return that f64
/// value, so that `serialize_f64` (via ryu) reproduces it.
fn find_shortest_roundtrip_f64(f64_val: f64, roundtrips: impl Fn(f64) -> bool) -> f64 {
if !f64_val.is_finite() || f64_val.fract() == 0.0 {
return f64_val;
}
// With our usage(F16/BF16), the loop will need only ~4 iterations, since max significant digits needed is ~4
// Example: f16(3.14159) stores 3.140625
// sig_digits=1 → 3.0 → f16(3.0)=3.0 ≠ 3.140625 ❌
// sig_digits=2 → 3.1 → f16(3.1)=3.099.. ≠ 3.140625 ❌
// sig_digits=3 → 3.14 → f16(3.14)=3.140625 ✅ → returns 3.14
for sig_digits in 1..=5u32 {
let rounded = round_to_sig_digits(f64_val, sig_digits);
if roundtrips(rounded) {
return rounded;
}
}
f64_val
}

impl Serialize for IValue {
#[inline]
Expand DownExpand Up@@ -55,11 +102,50 @@ impl Serialize for IArray {
where
S: Serializer,
{
let mut s = serializer.serialize_seq(Some(self.len()))?;
for v in self {
s.serialize_element(&v)?;
match self.as_slice() {
// Serialize typed float arrays with the shortest representation that
// round-trips through the stored precision. Without this, all floats
// would be promoted to f64 via INumber, and ryu's f64 algorithm would
// emit unnecessarily long strings (e.g. "0.3" stored as f32 would
// serialize as "0.30000001192092896" instead of "0.3").
//
// F32: serialize directly as f32 so ryu uses its f32 algorithm.
// F16/BF16: ryu has no f16 mode and serde has no serialize_f16, so we
// find the shortest decimal that round-trips through the half type and
// pass the corresponding f64 value to serialize_f64.
ArraySliceRef::F32(slice) => {
let mut s = serializer.serialize_seq(Some(slice.len()))?;
for &v in slice {
s.serialize_element(&v)?;
}
s.end()
}
ArraySliceRef::F16(slice) => {
let mut s = serializer.serialize_seq(Some(slice.len()))?;
for &v in slice {
let f64_val = f64::from(v);
let shortest = find_shortest_roundtrip_f64(f64_val, |p| f16::from_f64(p) == v);
s.serialize_element(&shortest)?;
}
s.end()
}
ArraySliceRef::BF16(slice) => {
let mut s = serializer.serialize_seq(Some(slice.len()))?;
for &v in slice {
let f64_val = f64::from(v);
let shortest = find_shortest_roundtrip_f64(f64_val, |p| bf16::from_f64(p) == v);
s.serialize_element(&shortest)?;
}
s.end()
}
Comment thread
AvivDavid23 marked this conversation as resolved.
_ => {
let mut s = serializer.serialize_seq(Some(self.len()))?;
for v in self {
s.serialize_element(&v)?;
}
s.end()
}
}
s.end()
}
}

Expand DownExpand Up@@ -635,3 +721,202 @@ where
{
value.serialize(ValueSerializer)
}

#[cfg(test)]
mod tests {
use crate::array::{ArraySliceRef, FloatType};
use crate::{FPHAConfig, IArray, IValue, IValueDeserSeed};

#[test]
fn test_f32_array_serialization_preserves_short_representation() {
let mut arr = IArray::new();
arr.push_with_fp_type(IValue::from(0.3), FloatType::F32)
.unwrap();
assert!(matches!(arr.as_slice(), ArraySliceRef::F32(_)));

let json = serde_json::to_string(&arr).unwrap();
assert_eq!(
json, "[0.3]",
"F32 array should serialize 0.3 as '0.3', not with extra f64 precision digits"
);
}

#[test]
fn test_f64_array_serialization_preserves_short_representation() {
let mut arr = IArray::new();
arr.push_with_fp_type(IValue::from(0.3), FloatType::F64)
.unwrap();
assert!(matches!(arr.as_slice(), ArraySliceRef::F64(_)));

let json = serde_json::to_string(&arr).unwrap();
assert_eq!(json, "[0.3]");
}

#[test]
fn test_f16_array_serialization_preserves_short_representation() {
let mut arr = IArray::new();
arr.push_with_fp_type(IValue::from(1.5), FloatType::F16)
.unwrap();
assert_eq!(serde_json::to_string(&arr).unwrap(), "[1.5]");

let mut arr2 = IArray::new();
arr2.push_with_fp_type(IValue::from(0.3), FloatType::F16)
.unwrap();
assert_eq!(
serde_json::to_string(&arr2).unwrap(),
"[0.3]",
"F16 array should serialize 0.3 as '0.3', not '0.30004883' or '0.300048828125'"
);
}

#[test]
fn test_bf16_array_serialization_preserves_short_representation() {
let mut arr = IArray::new();
arr.push_with_fp_type(IValue::from(1.5), FloatType::BF16)
.unwrap();
assert_eq!(serde_json::to_string(&arr).unwrap(), "[1.5]");

let mut arr2 = IArray::new();
arr2.push_with_fp_type(IValue::from(0.3), FloatType::BF16)
.unwrap();
assert_eq!(
serde_json::to_string(&arr2).unwrap(),
"[0.3]",
"BF16 array should serialize 0.3 as '0.3'"
);
}

#[test]
fn test_typed_float_array_serialization_roundtrip() {
let input = "[0.3,0.1,0.7,1.0,2.5,100.0]";
let fp_types = [
FloatType::F16,
FloatType::BF16,
FloatType::F32,
FloatType::F64,
];

let jsons: Vec<String> = fp_types
.iter()
.map(|&fp_type| {
let seed = IValueDeserSeed::new(Some(FPHAConfig::new_with_type(fp_type)));
let mut de = serde_json::Deserializer::from_str(input);
let arr = serde::de::DeserializeSeed::deserialize(seed, &mut de)
.unwrap()
.into_array()
.unwrap();
let json_out = serde_json::to_string(&arr).unwrap();
assert_eq!(
json_out, input,
"{fp_type} round-trip should preserve the original JSON string"
);
json_out
})
.collect();

for pair in jsons.windows(2) {
assert_eq!(
pair[0], pair[1],
"all float types should produce identical JSON"
);
}
}

#[test]
fn test_f16_precision_loss_produces_different_but_short_representation() {
// Values with more significant digits than f16 can represent (~3.3 digits).
// The stored f16 value differs from the original, so the serialized string
// must differ too — but it should still be the shortest string that
// round-trips through f16.
let cases: &[(&str, &str)] = &[
("3.14159", "3.14"), // pi truncated: f16 stores 3.140625
("42.42", "42.4"), // f16 stores 42.40625
("12.345", "12.34"), // f16 stores 12.34375
("0.5678", "0.568"), // f16 stores 0.56787109375
];

for &(input, expected_f16) in cases {
let json_input = format!("[{input}]");

let f16_arr: IArray = {
let seed = IValueDeserSeed::new(Some(FPHAConfig::new_with_type(FloatType::F16)));
let mut de = serde_json::Deserializer::from_str(&json_input);
serde::de::DeserializeSeed::deserialize(seed, &mut de)
.unwrap()
.into_array()
.unwrap()
};
let f16_json = serde_json::to_string(&f16_arr).unwrap();
assert_eq!(
f16_json,
format!("[{expected_f16}]"),
"F16 of {input}: should serialize as shortest f16 representation"
);

// Same values through F32 should preserve the original (enough precision)
let f32_arr: IArray = {
let seed = IValueDeserSeed::new(Some(FPHAConfig::new_with_type(FloatType::F32)));
let mut de = serde_json::Deserializer::from_str(&json_input);
serde::de::DeserializeSeed::deserialize(seed, &mut de)
.unwrap()
.into_array()
.unwrap()
};
let f32_json = serde_json::to_string(&f32_arr).unwrap();
assert_eq!(
f32_json, json_input,
"F32 of {input}: should preserve the original representation"
);
}
}

#[test]
fn test_negative_float_array_serialization() {
let input = "[-0.3,-0.1,-1.0,-2.5,-100.0]";
let fp_types = [
FloatType::F16,
FloatType::BF16,
FloatType::F32,
FloatType::F64,
];

for &fp_type in &fp_types {
let seed = IValueDeserSeed::new(Some(FPHAConfig::new_with_type(fp_type)));
let mut de = serde_json::Deserializer::from_str(input);
let arr = serde::de::DeserializeSeed::deserialize(seed, &mut de)
.unwrap()
.into_array()
.unwrap();
let json_out = serde_json::to_string(&arr).unwrap();
assert_eq!(
json_out, input,
"{fp_type} negative round-trip should preserve the original JSON string"
);
}
}

#[test]
fn test_negative_f16_precision_loss_produces_short_representation() {
let cases: &[(&str, &str)] = &[
("-3.14159", "-3.14"),
("-42.42", "-42.4"),
("-0.5678", "-0.568"),
];

for &(input, expected_f16) in cases {
let json_input = format!("[{input}]");
let seed = IValueDeserSeed::new(Some(FPHAConfig::new_with_type(FloatType::F16)));
let mut de = serde_json::Deserializer::from_str(&json_input);
let arr = serde::de::DeserializeSeed::deserialize(seed, &mut de)
.unwrap()
.into_array()
.unwrap();
let json_out = serde_json::to_string(&arr).unwrap();
assert_eq!(
json_out,
format!("[{expected_f16}]"),
"F16 of {input}: negative should serialize as shortest f16 representation"
);
}
}
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
295 changes: 290 additions & 5 deletions src/ser.rs
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
use half::{bf16, f16};
use serde::{
ser::{
Error as _, Impossible, SerializeMap, SerializeSeq, SerializeStruct,
Expand All@@ -7,7 +8,53 @@ use serde::{
};
use serde_json::error::Error;

use crate::{array::TryCollect, DestructuredRef, IArray, INumber, IObject, IString, IValue};
use crate::{
array::{ArraySliceRef, TryCollect},
DestructuredRef, IArray, INumber, IObject, IString, IValue,
};

/// Rounds an f64 to the given number of significant decimal digits.
#[inline]
fn round_to_sig_digits(val: f64, sig_digits: u32) -> f64 {
// how many digits are left of the decimal point, minus one
// OR: what power of 10 is this number closest to? (e.g. 100 -> 10^2, 0.001 -> 10^-3)
let order_of_magnitude = val.abs().log10().floor() as i32;
// Multiplier that shifts the desired significant digits into the integer part,
// so that f64::round() can snap to the nearest integer and discard the rest.
// e.g. for val=3.14, order_of_magnitude = 0, sig_digits=2: scale=10, so 3.14*10=31.4 → round→31 → 31/10=3.1
let scale = 10f64.powi(sig_digits as i32 - 1 - order_of_magnitude);
(val * scale).round() / scale
}

/// Finds an f64 value that, when formatted by ryu's f64 algorithm, produces
/// the shortest decimal string that still round-trips through the target
/// half-precision type (f16 or bf16).
///
/// ryu only supports f32/f64, and serde has no `serialize_f16`. Since f16/bf16
/// have far fewer distinct values than f32, there exist shorter representations
/// that uniquely identify the half value. For example, f16(0.3) = 0.300048828125,
/// and "0.3" parsed as f16 gives back the same bits — so "0.3" is valid.
///
/// The approach: try rounding to increasing significant digits until the
/// rounded value round-trips through the type. Then return that f64
/// value, so that `serialize_f64` (via ryu) reproduces it.
fn find_shortest_roundtrip_f64(f64_val: f64, roundtrips: impl Fn(f64) -> bool) -> f64 {
if !f64_val.is_finite() || f64_val.fract() == 0.0 {
return f64_val;
}
// With our usage(F16/BF16), the loop will need only ~4 iterations, since max significant digits needed is ~4
// Example: f16(3.14159) stores 3.140625
// sig_digits=1 → 3.0 → f16(3.0)=3.0 ≠ 3.140625 ❌
// sig_digits=2 → 3.1 → f16(3.1)=3.099.. ≠ 3.140625 ❌
// sig_digits=3 → 3.14 → f16(3.14)=3.140625 ✅ → returns 3.14
for sig_digits in 1..=5u32 {
let rounded = round_to_sig_digits(f64_val, sig_digits);
if roundtrips(rounded) {
return rounded;
}
}
f64_val
}

impl Serialize for IValue {
#[inline]
Expand DownExpand Up@@ -55,11 +102,50 @@ impl Serialize for IArray {
where
S: Serializer,
{
let mut s = serializer.serialize_seq(Some(self.len()))?;
for v in self {
s.serialize_element(&v)?;
match self.as_slice() {
// Serialize typed float arrays with the shortest representation that
// round-trips through the stored precision. Without this, all floats
// would be promoted to f64 via INumber, and ryu's f64 algorithm would
// emit unnecessarily long strings (e.g. "0.3" stored as f32 would
// serialize as "0.30000001192092896" instead of "0.3").
//
// F32: serialize directly as f32 so ryu uses its f32 algorithm.
// F16/BF16: ryu has no f16 mode and serde has no serialize_f16, so we
// find the shortest decimal that round-trips through the half type and
// pass the corresponding f64 value to serialize_f64.
ArraySliceRef::F32(slice) => {
let mut s = serializer.serialize_seq(Some(slice.len()))?;
for &v in slice {
s.serialize_element(&v)?;
}
s.end()
}
ArraySliceRef::F16(slice) => {
let mut s = serializer.serialize_seq(Some(slice.len()))?;
for &v in slice {
let f64_val = f64::from(v);
let shortest = find_shortest_roundtrip_f64(f64_val, |p| f16::from_f64(p) == v);
s.serialize_element(&shortest)?;
}
s.end()
}
ArraySliceRef::BF16(slice) => {
let mut s = serializer.serialize_seq(Some(slice.len()))?;
for &v in slice {
let f64_val = f64::from(v);
let shortest = find_shortest_roundtrip_f64(f64_val, |p| bf16::from_f64(p) == v);
s.serialize_element(&shortest)?;
}
s.end()
}
Comment thread
AvivDavid23 marked this conversation as resolved.
_ => {
let mut s = serializer.serialize_seq(Some(self.len()))?;
for v in self {
s.serialize_element(&v)?;
}
s.end()
}
}
s.end()
}
}

Expand DownExpand Up@@ -635,3 +721,202 @@ where
{
value.serialize(ValueSerializer)
}

#[cfg(test)]
mod tests {
use crate::array::{ArraySliceRef, FloatType};
use crate::{FPHAConfig, IArray, IValue, IValueDeserSeed};

#[test]
fn test_f32_array_serialization_preserves_short_representation() {
let mut arr = IArray::new();
arr.push_with_fp_type(IValue::from(0.3), FloatType::F32)
.unwrap();
assert!(matches!(arr.as_slice(), ArraySliceRef::F32(_)));

let json = serde_json::to_string(&arr).unwrap();
assert_eq!(
json, "[0.3]",
"F32 array should serialize 0.3 as '0.3', not with extra f64 precision digits"
);
}

#[test]
fn test_f64_array_serialization_preserves_short_representation() {
let mut arr = IArray::new();
arr.push_with_fp_type(IValue::from(0.3), FloatType::F64)
.unwrap();
assert!(matches!(arr.as_slice(), ArraySliceRef::F64(_)));

let json = serde_json::to_string(&arr).unwrap();
assert_eq!(json, "[0.3]");
}

#[test]
fn test_f16_array_serialization_preserves_short_representation() {
let mut arr = IArray::new();
arr.push_with_fp_type(IValue::from(1.5), FloatType::F16)
.unwrap();
assert_eq!(serde_json::to_string(&arr).unwrap(), "[1.5]");

let mut arr2 = IArray::new();
arr2.push_with_fp_type(IValue::from(0.3), FloatType::F16)
.unwrap();
assert_eq!(
serde_json::to_string(&arr2).unwrap(),
"[0.3]",
"F16 array should serialize 0.3 as '0.3', not '0.30004883' or '0.300048828125'"
);
}

#[test]
fn test_bf16_array_serialization_preserves_short_representation() {
let mut arr = IArray::new();
arr.push_with_fp_type(IValue::from(1.5), FloatType::BF16)
.unwrap();
assert_eq!(serde_json::to_string(&arr).unwrap(), "[1.5]");

let mut arr2 = IArray::new();
arr2.push_with_fp_type(IValue::from(0.3), FloatType::BF16)
.unwrap();
assert_eq!(
serde_json::to_string(&arr2).unwrap(),
"[0.3]",
"BF16 array should serialize 0.3 as '0.3'"
);
}

#[test]
fn test_typed_float_array_serialization_roundtrip() {
let input = "[0.3,0.1,0.7,1.0,2.5,100.0]";
let fp_types = [
FloatType::F16,
FloatType::BF16,
FloatType::F32,
FloatType::F64,
];

let jsons: Vec<String> = fp_types
.iter()
.map(|&fp_type| {
let seed = IValueDeserSeed::new(Some(FPHAConfig::new_with_type(fp_type)));
let mut de = serde_json::Deserializer::from_str(input);
let arr = serde::de::DeserializeSeed::deserialize(seed, &mut de)
.unwrap()
.into_array()
.unwrap();
let json_out = serde_json::to_string(&arr).unwrap();
assert_eq!(
json_out, input,
"{fp_type} round-trip should preserve the original JSON string"
);
json_out
})
.collect();

for pair in jsons.windows(2) {
assert_eq!(
pair[0], pair[1],
"all float types should produce identical JSON"
);
}
}

#[test]
fn test_f16_precision_loss_produces_different_but_short_representation() {
// Values with more significant digits than f16 can represent (~3.3 digits).
// The stored f16 value differs from the original, so the serialized string
// must differ too — but it should still be the shortest string that
// round-trips through f16.
let cases: &[(&str, &str)] = &[
("3.14159", "3.14"), // pi truncated: f16 stores 3.140625
("42.42", "42.4"), // f16 stores 42.40625
("12.345", "12.34"), // f16 stores 12.34375
("0.5678", "0.568"), // f16 stores 0.56787109375
];

for &(input, expected_f16) in cases {
let json_input = format!("[{input}]");

let f16_arr: IArray = {
let seed = IValueDeserSeed::new(Some(FPHAConfig::new_with_type(FloatType::F16)));
let mut de = serde_json::Deserializer::from_str(&json_input);
serde::de::DeserializeSeed::deserialize(seed, &mut de)
.unwrap()
.into_array()
.unwrap()
};
let f16_json = serde_json::to_string(&f16_arr).unwrap();
assert_eq!(
f16_json,
format!("[{expected_f16}]"),
"F16 of {input}: should serialize as shortest f16 representation"
);

// Same values through F32 should preserve the original (enough precision)
let f32_arr: IArray = {
let seed = IValueDeserSeed::new(Some(FPHAConfig::new_with_type(FloatType::F32)));
let mut de = serde_json::Deserializer::from_str(&json_input);
serde::de::DeserializeSeed::deserialize(seed, &mut de)
.unwrap()
.into_array()
.unwrap()
};
let f32_json = serde_json::to_string(&f32_arr).unwrap();
assert_eq!(
f32_json, json_input,
"F32 of {input}: should preserve the original representation"
);
}
}

#[test]
fn test_negative_float_array_serialization() {
let input = "[-0.3,-0.1,-1.0,-2.5,-100.0]";
let fp_types = [
FloatType::F16,
FloatType::BF16,
FloatType::F32,
FloatType::F64,
];

for &fp_type in &fp_types {
let seed = IValueDeserSeed::new(Some(FPHAConfig::new_with_type(fp_type)));
let mut de = serde_json::Deserializer::from_str(input);
let arr = serde::de::DeserializeSeed::deserialize(seed, &mut de)
.unwrap()
.into_array()
.unwrap();
let json_out = serde_json::to_string(&arr).unwrap();
assert_eq!(
json_out, input,
"{fp_type} negative round-trip should preserve the original JSON string"
);
}
}

#[test]
fn test_negative_f16_precision_loss_produces_short_representation() {
let cases: &[(&str, &str)] = &[
("-3.14159", "-3.14"),
("-42.42", "-42.4"),
("-0.5678", "-0.568"),
];

for &(input, expected_f16) in cases {
let json_input = format!("[{input}]");
let seed = IValueDeserSeed::new(Some(FPHAConfig::new_with_type(FloatType::F16)));
let mut de = serde_json::Deserializer::from_str(&json_input);
let arr = serde::de::DeserializeSeed::deserialize(seed, &mut de)
.unwrap()
.into_array()
.unwrap();
let json_out = serde_json::to_string(&arr).unwrap();
assert_eq!(
json_out,
format!("[{expected_f16}]"),
"F16 of {input}: negative should serialize as shortest f16 representation"
);
}
}
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
295 changes: 290 additions & 5 deletions src/ser.rs
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
use half::{bf16, f16};
use serde::{
ser::{
Error as _, Impossible, SerializeMap, SerializeSeq, SerializeStruct,
Expand All@@ -7,7 +8,53 @@ use serde::{
};
use serde_json::error::Error;

use crate::{array::TryCollect, DestructuredRef, IArray, INumber, IObject, IString, IValue};
use crate::{
array::{ArraySliceRef, TryCollect},
DestructuredRef, IArray, INumber, IObject, IString, IValue,
};

/// Rounds an f64 to the given number of significant decimal digits.
#[inline]
fn round_to_sig_digits(val: f64, sig_digits: u32) -> f64 {
// how many digits are left of the decimal point, minus one
// OR: what power of 10 is this number closest to? (e.g. 100 -> 10^2, 0.001 -> 10^-3)
let order_of_magnitude = val.abs().log10().floor() as i32;
// Multiplier that shifts the desired significant digits into the integer part,
// so that f64::round() can snap to the nearest integer and discard the rest.
// e.g. for val=3.14, order_of_magnitude = 0, sig_digits=2: scale=10, so 3.14*10=31.4 → round→31 → 31/10=3.1
let scale = 10f64.powi(sig_digits as i32 - 1 - order_of_magnitude);
(val * scale).round() / scale
}

/// Finds an f64 value that, when formatted by ryu's f64 algorithm, produces
/// the shortest decimal string that still round-trips through the target
/// half-precision type (f16 or bf16).
///
/// ryu only supports f32/f64, and serde has no `serialize_f16`. Since f16/bf16
/// have far fewer distinct values than f32, there exist shorter representations
/// that uniquely identify the half value. For example, f16(0.3) = 0.300048828125,
/// and "0.3" parsed as f16 gives back the same bits — so "0.3" is valid.
///
/// The approach: try rounding to increasing significant digits until the
/// rounded value round-trips through the type. Then return that f64
/// value, so that `serialize_f64` (via ryu) reproduces it.
fn find_shortest_roundtrip_f64(f64_val: f64, roundtrips: impl Fn(f64) -> bool) -> f64 {
if !f64_val.is_finite() || f64_val.fract() == 0.0 {
return f64_val;
}
// With our usage(F16/BF16), the loop will need only ~4 iterations, since max significant digits needed is ~4
// Example: f16(3.14159) stores 3.140625
// sig_digits=1 → 3.0 → f16(3.0)=3.0 ≠ 3.140625 ❌
// sig_digits=2 → 3.1 → f16(3.1)=3.099.. ≠ 3.140625 ❌
// sig_digits=3 → 3.14 → f16(3.14)=3.140625 ✅ → returns 3.14
for sig_digits in 1..=5u32 {
let rounded = round_to_sig_digits(f64_val, sig_digits);
if roundtrips(rounded) {
return rounded;
}
}
f64_val
}

impl Serialize for IValue {
#[inline]
Expand DownExpand Up@@ -55,11 +102,50 @@ impl Serialize for IArray {
where
S: Serializer,
{
let mut s = serializer.serialize_seq(Some(self.len()))?;
for v in self {
s.serialize_element(&v)?;
match self.as_slice() {
// Serialize typed float arrays with the shortest representation that
// round-trips through the stored precision. Without this, all floats
// would be promoted to f64 via INumber, and ryu's f64 algorithm would
// emit unnecessarily long strings (e.g. "0.3" stored as f32 would
// serialize as "0.30000001192092896" instead of "0.3").
//
// F32: serialize directly as f32 so ryu uses its f32 algorithm.
// F16/BF16: ryu has no f16 mode and serde has no serialize_f16, so we
// find the shortest decimal that round-trips through the half type and
// pass the corresponding f64 value to serialize_f64.
ArraySliceRef::F32(slice) => {
let mut s = serializer.serialize_seq(Some(slice.len()))?;
for &v in slice {
s.serialize_element(&v)?;
}
s.end()
}
ArraySliceRef::F16(slice) => {
let mut s = serializer.serialize_seq(Some(slice.len()))?;
for &v in slice {
let f64_val = f64::from(v);
let shortest = find_shortest_roundtrip_f64(f64_val, |p| f16::from_f64(p) == v);
s.serialize_element(&shortest)?;
}
s.end()
}
ArraySliceRef::BF16(slice) => {
let mut s = serializer.serialize_seq(Some(slice.len()))?;
for &v in slice {
let f64_val = f64::from(v);
let shortest = find_shortest_roundtrip_f64(f64_val, |p| bf16::from_f64(p) == v);
s.serialize_element(&shortest)?;
}
s.end()
}
Comment thread
AvivDavid23 marked this conversation as resolved.
_ => {
let mut s = serializer.serialize_seq(Some(self.len()))?;
for v in self {
s.serialize_element(&v)?;
}
s.end()
}
}
s.end()
}
}

Expand DownExpand Up@@ -635,3 +721,202 @@ where
{
value.serialize(ValueSerializer)
}

#[cfg(test)]
mod tests {
use crate::array::{ArraySliceRef, FloatType};
use crate::{FPHAConfig, IArray, IValue, IValueDeserSeed};

#[test]
fn test_f32_array_serialization_preserves_short_representation() {
let mut arr = IArray::new();
arr.push_with_fp_type(IValue::from(0.3), FloatType::F32)
.unwrap();
assert!(matches!(arr.as_slice(), ArraySliceRef::F32(_)));

let json = serde_json::to_string(&arr).unwrap();
assert_eq!(
json, "[0.3]",
"F32 array should serialize 0.3 as '0.3', not with extra f64 precision digits"
);
}

#[test]
fn test_f64_array_serialization_preserves_short_representation() {
let mut arr = IArray::new();
arr.push_with_fp_type(IValue::from(0.3), FloatType::F64)
.unwrap();
assert!(matches!(arr.as_slice(), ArraySliceRef::F64(_)));

let json = serde_json::to_string(&arr).unwrap();
assert_eq!(json, "[0.3]");
}

#[test]
fn test_f16_array_serialization_preserves_short_representation() {
let mut arr = IArray::new();
arr.push_with_fp_type(IValue::from(1.5), FloatType::F16)
.unwrap();
assert_eq!(serde_json::to_string(&arr).unwrap(), "[1.5]");

let mut arr2 = IArray::new();
arr2.push_with_fp_type(IValue::from(0.3), FloatType::F16)
.unwrap();
assert_eq!(
serde_json::to_string(&arr2).unwrap(),
"[0.3]",
"F16 array should serialize 0.3 as '0.3', not '0.30004883' or '0.300048828125'"
);
}

#[test]
fn test_bf16_array_serialization_preserves_short_representation() {
let mut arr = IArray::new();
arr.push_with_fp_type(IValue::from(1.5), FloatType::BF16)
.unwrap();
assert_eq!(serde_json::to_string(&arr).unwrap(), "[1.5]");

let mut arr2 = IArray::new();
arr2.push_with_fp_type(IValue::from(0.3), FloatType::BF16)
.unwrap();
assert_eq!(
serde_json::to_string(&arr2).unwrap(),
"[0.3]",
"BF16 array should serialize 0.3 as '0.3'"
);
}

#[test]
fn test_typed_float_array_serialization_roundtrip() {
let input = "[0.3,0.1,0.7,1.0,2.5,100.0]";
let fp_types = [
FloatType::F16,
FloatType::BF16,
FloatType::F32,
FloatType::F64,
];

let jsons: Vec<String> = fp_types
.iter()
.map(|&fp_type| {
let seed = IValueDeserSeed::new(Some(FPHAConfig::new_with_type(fp_type)));
let mut de = serde_json::Deserializer::from_str(input);
let arr = serde::de::DeserializeSeed::deserialize(seed, &mut de)
.unwrap()
.into_array()
.unwrap();
let json_out = serde_json::to_string(&arr).unwrap();
assert_eq!(
json_out, input,
"{fp_type} round-trip should preserve the original JSON string"
);
json_out
})
.collect();

for pair in jsons.windows(2) {
assert_eq!(
pair[0], pair[1],
"all float types should produce identical JSON"
);
}
}

#[test]
fn test_f16_precision_loss_produces_different_but_short_representation() {
// Values with more significant digits than f16 can represent (~3.3 digits).
// The stored f16 value differs from the original, so the serialized string
// must differ too — but it should still be the shortest string that
// round-trips through f16.
let cases: &[(&str, &str)] = &[
("3.14159", "3.14"), // pi truncated: f16 stores 3.140625
("42.42", "42.4"), // f16 stores 42.40625
("12.345", "12.34"), // f16 stores 12.34375
("0.5678", "0.568"), // f16 stores 0.56787109375
];

for &(input, expected_f16) in cases {
let json_input = format!("[{input}]");

let f16_arr: IArray = {
let seed = IValueDeserSeed::new(Some(FPHAConfig::new_with_type(FloatType::F16)));
let mut de = serde_json::Deserializer::from_str(&json_input);
serde::de::DeserializeSeed::deserialize(seed, &mut de)
.unwrap()
.into_array()
.unwrap()
};
let f16_json = serde_json::to_string(&f16_arr).unwrap();
assert_eq!(
f16_json,
format!("[{expected_f16}]"),
"F16 of {input}: should serialize as shortest f16 representation"
);

// Same values through F32 should preserve the original (enough precision)
let f32_arr: IArray = {
let seed = IValueDeserSeed::new(Some(FPHAConfig::new_with_type(FloatType::F32)));
let mut de = serde_json::Deserializer::from_str(&json_input);
serde::de::DeserializeSeed::deserialize(seed, &mut de)
.unwrap()
.into_array()
.unwrap()
};
let f32_json = serde_json::to_string(&f32_arr).unwrap();
assert_eq!(
f32_json, json_input,
"F32 of {input}: should preserve the original representation"
);
}
}

#[test]
fn test_negative_float_array_serialization() {
let input = "[-0.3,-0.1,-1.0,-2.5,-100.0]";
let fp_types = [
FloatType::F16,
FloatType::BF16,
FloatType::F32,
FloatType::F64,
];

for &fp_type in &fp_types {
let seed = IValueDeserSeed::new(Some(FPHAConfig::new_with_type(fp_type)));
let mut de = serde_json::Deserializer::from_str(input);
let arr = serde::de::DeserializeSeed::deserialize(seed, &mut de)
.unwrap()
.into_array()
.unwrap();
let json_out = serde_json::to_string(&arr).unwrap();
assert_eq!(
json_out, input,
"{fp_type} negative round-trip should preserve the original JSON string"
);
}
}

#[test]
fn test_negative_f16_precision_loss_produces_short_representation() {
let cases: &[(&str, &str)] = &[
("-3.14159", "-3.14"),
("-42.42", "-42.4"),
("-0.5678", "-0.568"),
];

for &(input, expected_f16) in cases {
let json_input = format!("[{input}]");
let seed = IValueDeserSeed::new(Some(FPHAConfig::new_with_type(FloatType::F16)));
let mut de = serde_json::Deserializer::from_str(&json_input);
let arr = serde::de::DeserializeSeed::deserialize(seed, &mut de)
.unwrap()
.into_array()
.unwrap();
let json_out = serde_json::to_string(&arr).unwrap();
assert_eq!(
json_out,
format!("[{expected_f16}]"),
"F16 of {input}: negative should serialize as shortest f16 representation"
);
}
}
}
Loading