Skip to main content

cortex_hybrid/
reference_json.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2
3//! Bounded loading for untrusted reference-backend JSON fixtures.
4//!
5//! Direct Serde deserialization remains available for trusted inputs. Callers
6//! processing untrusted JSON should choose a byte limit for the complete input
7//! before parsing; the limit is applied before any tensor data is allocated.
8
9use crate::error::{CortexError, Result};
10use serde::de::{DeserializeOwned, MapAccess, Visitor, value::MapAccessDeserializer};
11use serde::{Deserialize, Deserializer};
12use std::marker::PhantomData;
13
14/// Deserialize a complete reference JSON payload only when it fits `max_bytes`.
15/// The limit covers the entire JSON document, including nested model weights.
16pub fn from_slice_with_limit<T: DeserializeOwned>(input: &[u8], max_bytes: usize) -> Result<T> {
17    if input.len() > max_bytes {
18        return Err(CortexError::SerdeInputTooLarge {
19            max_bytes,
20            actual_bytes: input.len(),
21        });
22    }
23    Ok(serde_json::from_slice(input)?)
24}
25
26/// Require an object at each versioned reference-wire boundary. Derived struct
27/// deserializers accept positional sequences too, which JSON fixtures do not.
28pub(crate) fn deserialize_object<'de, D, T>(deserializer: D) -> std::result::Result<T, D::Error>
29where
30    D: Deserializer<'de>,
31    T: Deserialize<'de>,
32{
33    struct ObjectVisitor<T>(PhantomData<T>);
34
35    impl<'de, T: Deserialize<'de>> Visitor<'de> for ObjectVisitor<T> {
36        type Value = T;
37
38        fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
39            formatter.write_str("a versioned reference JSON object")
40        }
41
42        fn visit_map<A: MapAccess<'de>>(self, map: A) -> std::result::Result<T, A::Error> {
43            T::deserialize(MapAccessDeserializer::new(map))
44        }
45    }
46
47    deserializer.deserialize_map(ObjectVisitor(PhantomData))
48}