use xso::{
text::{Base64, StripWhitespace},
AsXml, FromXml,
};
use crate::hashes::Sha1HexAttribute;
use crate::ns;
use crate::pubsub::PubSubPayload;
generate_element!(
Metadata, "metadata", AVATAR_METADATA,
children: [
infos: Vec<Info> = ("info", AVATAR_METADATA) => Info
]
);
impl PubSubPayload for Metadata {}
#[derive(FromXml, AsXml, PartialEq, Debug, Clone)]
#[xml(namespace = ns::AVATAR_METADATA, name = "info")]
pub struct Info {
#[xml(attribute)]
pub bytes: u32,
#[xml(attribute(default))]
pub width: Option<u16>,
#[xml(attribute(default))]
pub height: Option<u16>,
#[xml(attribute)]
pub id: Sha1HexAttribute,
#[xml(attribute = "type")]
pub type_: String,
#[xml(attribute(default))]
pub url: Option<String>,
}
#[derive(FromXml, AsXml, PartialEq, Debug, Clone)]
#[xml(namespace = ns::AVATAR_DATA, name = "data")]
pub struct Data {
#[xml(text(codec = Base64<StripWhitespace>))]
pub data: Vec<u8>,
}
impl PubSubPayload for Data {}
#[cfg(test)]
mod tests {
use super::*;
use crate::hashes::Algo;
use minidom::Element;
#[cfg(not(feature = "disable-validation"))]
use xso::error::{Error, FromElementError};
#[cfg(target_pointer_width = "32")]
#[test]
fn test_size() {
assert_size!(Metadata, 12);
assert_size!(Info, 60);
assert_size!(Data, 12);
}
#[cfg(target_pointer_width = "64")]
#[test]
fn test_size() {
assert_size!(Metadata, 24);
assert_size!(Info, 112);
assert_size!(Data, 24);
}
#[test]
fn test_simple() {
let elem: Element = "<metadata xmlns='urn:xmpp:avatar:metadata'>
<info bytes='12345' width='64' height='64'
id='111f4b3c50d7b0df729d299bc6f8e9ef9066971f'
type='image/png'/>
</metadata>"
.parse()
.unwrap();
let metadata = Metadata::try_from(elem).unwrap();
assert_eq!(metadata.infos.len(), 1);
let info = &metadata.infos[0];
assert_eq!(info.bytes, 12345);
assert_eq!(info.width, Some(64));
assert_eq!(info.height, Some(64));
assert_eq!(info.id.algo, Algo::Sha_1);
assert_eq!(info.type_, "image/png");
assert_eq!(info.url, None);
assert_eq!(
info.id.hash,
[
17, 31, 75, 60, 80, 215, 176, 223, 114, 157, 41, 155, 198, 248, 233, 239, 144, 102,
151, 31
]
);
let elem: Element = "<data xmlns='urn:xmpp:avatar:data'>AAAA</data>"
.parse()
.unwrap();
let data = Data::try_from(elem).unwrap();
assert_eq!(data.data, b"\0\0\0");
}
#[cfg(not(feature = "disable-validation"))]
#[test]
fn test_invalid() {
let elem: Element = "<data xmlns='urn:xmpp:avatar:data' id='coucou'/>"
.parse()
.unwrap();
let error = Data::try_from(elem).unwrap_err();
let message = match error {
FromElementError::Invalid(Error::Other(string)) => string,
_ => panic!(),
};
assert_eq!(message, "Unknown attribute in Data element.")
}
}