xmpp_parsers/
json_containers.rs

1// Copyright (c) 2025 Maxime “pep” Buquet <pep@bouah.net>
2//
3// This Source Code Form is subject to the terms of the Mozilla Public
4// License, v. 2.0. If a copy of the MPL was not distributed with this
5// file, You can obtain one at http://mozilla.org/MPL/2.0/.
6
7use crate::ns;
8
9use xso::{AsXml, FromXml};
10
11/// Structure representing a `<json xmlns='urn:xmpp:json:0'/>` element.
12#[derive(FromXml, AsXml, Debug, Clone, PartialEq)]
13#[xml(namespace = ns::JSON_CONTAINERS, name = "json")]
14pub struct JsonContainer(#[xml(text)] serde_json::Value);
15
16#[cfg(test)]
17mod tests {
18    use super::*;
19    use minidom::Element;
20
21    use crate::Error::TextParseError;
22    use xso::error::FromElementError;
23
24    #[cfg(target_pointer_width = "32")]
25    #[test]
26    fn test_size() {
27        assert_size!(JsonContainer, 16);
28    }
29
30    #[cfg(target_pointer_width = "64")]
31    #[test]
32    fn test_size() {
33        assert_size!(JsonContainer, 32);
34    }
35
36    #[test]
37    fn test_empty() {
38        let elem: Element = "<json xmlns='urn:xmpp:json:0'/>".parse().unwrap();
39        let error = JsonContainer::try_from(elem.clone()).unwrap_err();
40        match error {
41            FromElementError::Invalid(TextParseError(err)) => {
42                assert_eq!(
43                    err.to_string(),
44                    "EOF while parsing a value at line 1 column 0"
45                );
46            }
47            _ => panic!(),
48        }
49    }
50
51    #[test]
52    fn test_simple() {
53        let elem: Element = "<json xmlns='urn:xmpp:json:0'>{\"a\": 1}</json>"
54            .parse()
55            .unwrap();
56        let result: serde_json::Value = "{\"a\": 1}".parse().unwrap();
57        match JsonContainer::try_from(elem.clone()) {
58            Ok(json) => assert_eq!(json.0, result),
59            _ => panic!(),
60        };
61    }
62}