recoco_utils/
deser.rs

1// ReCoco is a Rust-only fork of CocoIndex, by [CocoIndex](https://CocoIndex)
2// Original code from CocoIndex is copyrighted by CocoIndex
3// SPDX-FileCopyrightText: 2025-2026 CocoIndex (upstream)
4// SPDX-FileContributor: CocoIndex Contributors
5//
6// All modifications from the upstream for ReCoco are copyrighted by Knitli Inc.
7// SPDX-FileCopyrightText: 2026 Knitli Inc. (ReCoco)
8// SPDX-FileContributor: Adam Poulemanos <adam@knit.li>
9//
10// Both the upstream CocoIndex code and the ReCoco modifications are licensed under the Apache-2.0 License.
11// SPDX-License-Identifier: Apache-2.0
12
13use anyhow::{Result, anyhow};
14use serde::de::DeserializeOwned;
15
16fn map_serde_path_err<T: DeserializeOwned>(
17    err: serde_path_to_error::Error<serde_json::Error>,
18) -> anyhow::Error {
19    let ty = std::any::type_name::<T>().replace("::", ".");
20    let path = err.path();
21    let full_path = if path.iter().next().is_none() {
22        format!("<{ty}>")
23    } else {
24        format!("<{ty}>.{path}")
25    };
26    let inner = err.into_inner();
27    anyhow!("while deserializing `{full_path}`: {inner}")
28}
29
30pub fn from_json_value<T: DeserializeOwned>(value: serde_json::Value) -> Result<T> {
31    serde_path_to_error::deserialize::<_, T>(value).map_err(map_serde_path_err::<T>)
32}
33
34pub fn from_json_str<T: DeserializeOwned>(s: &str) -> Result<T> {
35    let mut de = serde_json::Deserializer::from_str(s);
36    serde_path_to_error::deserialize::<_, T>(&mut de).map_err(map_serde_path_err::<T>)
37}