serde_cqcode/ser/
mod.rs

1use core::CQSerializer;
2
3use serde::Serialize;
4
5use crate::Result;
6
7pub(crate) mod core;
8pub(crate) mod util;
9
10/// Serializes a given value into a CQCode formatted string.
11///
12/// # Arguments
13///
14/// * `value` - A reference to the value that implements the `Serialize` trait.
15///
16/// # Returns
17///
18/// * `Result<String>` - A result containing the serialized string on success, or an error if serialization fails.
19pub fn to_string<T: Serialize>(value: &T) -> Result<String> {
20    let mut ser = CQSerializer::default();
21    value.serialize(&mut ser)?;
22    Ok(ser.finish())
23}
24
25
26mod test {
27
28    #[test]
29    fn test_ser() {
30        use super::*;
31        use crate::data::CQCode;
32
33        assert_eq!(
34            "&#91;你好&#93;[CQ:face,id=1][CQ:image,file=example.jpg][CQ:at,qq=123456][CQ:emoji,id=128512]",
35            to_string(&[
36                CQCode::from(("text", [("text", "[你好]")])),
37                CQCode::from(("face", [("id", "1")])),
38                CQCode::from(("image", [("file", "example.jpg")])),
39                CQCode::from(("at", [("qq", "123456")])),
40                CQCode::from(("emoji", [("id", "128512")])),
41            ])
42            .unwrap()
43        )
44    }
45
46    #[test]
47    fn test_enum_ser() {
48        use super::*;
49        use serde::*;
50
51        #[derive(Serialize, Deserialize, Debug)]
52        #[serde(rename_all = "lowercase")]
53        enum Segment {
54            Text { text: String },
55            Face { id: u32 },
56            Image { file: String },
57            At { qq: u64 },
58            Emoji { id: u32 },
59        }
60
61        let input =
62            "&#91;你好&#93;[CQ:face,id=1][CQ:image,file=example.jpg][CQ:at,qq=123456][CQ:emoji,id=128512]";
63        let expected = vec![
64            Segment::Text {
65                text: "[你好]".to_string(),
66            },
67            Segment::Face { id: 1 },
68            Segment::Image {
69                file: "example.jpg".to_string(),
70            },
71            Segment::At { qq: 123456 },
72            Segment::Emoji { id: 128512 },
73        ];
74
75        let serialized = to_string(&expected).unwrap();
76        assert_eq!(serialized, input);
77    }
78}