threatflux_binary_analysis/utils/
serde_utils.rs1use crate::{error::BinaryError, Result};
2#[cfg(feature = "serde-support")]
3use serde::{de::DeserializeOwned, Serialize};
4
5#[cfg(feature = "serde-support")]
7pub fn to_json<T: Serialize>(value: &T) -> Result<String> {
8 serde_json::to_string_pretty(value).map_err(|e| BinaryError::internal(e.to_string()))
9}
10
11#[cfg(feature = "serde-support")]
13pub fn from_json<T: DeserializeOwned>(s: &str) -> Result<T> {
14 serde_json::from_str(s).map_err(|e| BinaryError::internal(e.to_string()))
15}
16
17#[cfg(test)]
18mod tests {
19 use super::*;
20 use crate::types::{AnalysisResult, BinaryFormat};
21
22 #[cfg(feature = "serde-support")]
23 #[test]
24 fn test_json_roundtrip() {
25 let result = AnalysisResult {
26 format: BinaryFormat::Elf,
27 ..Default::default()
28 };
29 let json = to_json(&result).unwrap();
30 assert!(json.contains("\"Elf\""));
31 let de: AnalysisResult = from_json(&json).unwrap();
32 assert_eq!(de.format, BinaryFormat::Elf);
33 }
34}