serde_lexpr/ser.rs
1use serde::Serialize;
2
3use lexpr::print;
4
5use crate::error::Result;
6use crate::value::to_value;
7
8use std::io;
9
10/// Serialize an instance of type `T` into an S-expression string, using the
11/// default printer options.
12///
13/// ```
14/// use serde_lexpr::to_string;
15///
16/// assert_eq!(to_string(&("foo", 1)).unwrap(), r#"#("foo" 1)"#.to_string())
17/// ```
18pub fn to_string<T>(value: &T) -> Result<String>
19where
20 T: Serialize,
21{
22 Ok(lexpr::to_string(&to_value(value)?)?)
23}
24
25/// Serialize an instance of type `T` into an S-expression string.
26///
27/// ```
28/// use serde_lexpr::{print, to_string_custom};
29///
30/// assert_eq!(to_string_custom(&("foo", 1), print::Options::elisp()).unwrap(), r#"["foo" 1]"#.to_string())
31/// ```
32pub fn to_string_custom<T>(value: &T, options: print::Options) -> Result<String>
33where
34 T: Serialize,
35{
36 Ok(lexpr::to_string_custom(&to_value(value)?, options)?)
37}
38
39/// Serialize an instance of type `T` into an S-expression byte vector, using the
40/// default printer options.
41///
42/// ```
43/// use serde_lexpr::to_vec;
44///
45/// let expected: Vec<u8> = r#"#("foo" 1)"#.into();
46/// assert_eq!(to_vec(&("foo", 1)).unwrap(), expected);
47/// ```
48pub fn to_vec<T>(value: &T) -> Result<Vec<u8>>
49where
50 T: Serialize,
51{
52 Ok(lexpr::to_vec(&to_value(value)?)?)
53}
54
55/// Serialize an instance of type `T` into an S-expression byte vector.
56///
57/// ```
58/// use serde_lexpr::{print, to_vec_custom};
59///
60/// let expected: Vec<u8> = r#"["foo" 1]"#.into();
61/// assert_eq!(to_vec_custom(&("foo", 1), print::Options::elisp()).unwrap(), expected);
62/// ```
63pub fn to_vec_custom<T>(value: &T, options: print::Options) -> Result<Vec<u8>>
64where
65 T: Serialize,
66{
67 Ok(lexpr::to_vec_custom(&to_value(value)?, options)?)
68}
69
70/// Serialize an instance of type `T` into an S-expression byte vector, using the
71/// default printer options.
72///
73/// ```
74/// use serde_lexpr::to_writer;
75///
76/// let mut output = Vec::new();
77/// to_writer(&mut output, &("foo", 1)).unwrap();
78/// assert_eq!(output, r#"#("foo" 1)"#.as_bytes());
79/// ```
80pub fn to_writer<T, W>(writer: W, value: &T) -> Result<()>
81where
82 T: Serialize,
83 W: io::Write,
84{
85 Ok(lexpr::to_writer(writer, &to_value(value)?)?)
86}
87
88/// Serialize an instance of type `T` into an S-expression byte vector.
89///
90/// ```
91/// use serde_lexpr::{print, to_writer_custom};
92///
93/// let mut output = Vec::new();
94/// to_writer_custom(&mut output, &("foo", 1), print::Options::elisp()).unwrap();
95/// assert_eq!(output, r#"["foo" 1]"#.as_bytes());
96/// ```
97pub fn to_writer_custom<T, W>(writer: W, value: &T, options: print::Options) -> Result<()>
98where
99 T: Serialize,
100 W: io::Write,
101{
102 Ok(lexpr::to_writer_custom(writer, &to_value(value)?, options)?)
103}