jasn/
ser.rs

1//! Serialization of Rust values to JASN text.
2
3use jasn_core::ser;
4use serde::Serialize;
5
6use crate::{Value, formatter};
7
8/// Error type for serialization.
9pub type Error = ser::Error;
10
11/// Result type for serialization.
12pub type Result<T> = std::result::Result<T, Error>;
13
14/// Serialize a Rust value to a JASN string.
15pub fn to_string<T>(value: &T) -> Result<String>
16where
17    T: Serialize,
18{
19    let jasn_value = ser::to_value(value)?;
20    Ok(formatter::format(&jasn_value))
21}
22
23/// Serialize a Rust value to a JASN string with pretty formatting.
24pub fn to_string_pretty<T>(value: &T) -> Result<String>
25where
26    T: Serialize,
27{
28    let jasn_value = ser::to_value(value)?;
29    Ok(formatter::format_pretty(&jasn_value))
30}
31
32/// Serialize a Rust value to a JASN string with custom formatting options.
33pub fn to_string_opts<T>(value: &T, options: &formatter::Options) -> Result<String>
34where
35    T: Serialize,
36{
37    // TODO: optimize by directly serializing to string instead of going through Value
38    let jasn_value = ser::to_value(value)?;
39    Ok(formatter::format_with_opts(&jasn_value, options))
40}
41
42/// Serialize a Rust value to a JASN [`Value`].
43pub fn to_value<T>(value: &T) -> Result<Value>
44where
45    T: Serialize + ?Sized,
46{
47    ser::to_value(value)
48}