xmtp_content_types/
text.rs1use std::collections::HashMap;
2
3use xmtp_proto::xmtp::mls::message_contents::{ContentTypeId, EncodedContent};
4
5use super::{CodecError, ContentCodec};
6
7pub struct TextCodec {}
8
9impl TextCodec {
10 const AUTHORITY_ID: &'static str = "xmtp.org";
11 pub const TYPE_ID: &'static str = "text";
12 const ENCODING_KEY: &'static str = "encoding";
13 const ENCODING_UTF8: &'static str = "UTF-8";
14 pub const MAJOR_VERSION: u32 = 1;
15 pub const MINOR_VERSION: u32 = 0;
16}
17
18impl ContentCodec<String> for TextCodec {
19 fn content_type() -> ContentTypeId {
20 ContentTypeId {
21 authority_id: TextCodec::AUTHORITY_ID.to_string(),
22 type_id: TextCodec::TYPE_ID.to_string(),
23 version_major: TextCodec::MAJOR_VERSION,
24 version_minor: TextCodec::MINOR_VERSION,
25 }
26 }
27
28 fn encode(text: String) -> Result<EncodedContent, CodecError> {
29 Ok(EncodedContent {
30 r#type: Some(TextCodec::content_type()),
31 parameters: HashMap::from([(
32 TextCodec::ENCODING_KEY.to_string(),
33 TextCodec::ENCODING_UTF8.to_string(),
34 )]),
35 fallback: None,
36 compression: None,
37 content: text.into_bytes(),
38 })
39 }
40
41 fn decode(content: EncodedContent) -> Result<String, CodecError> {
42 let encoding = content
43 .parameters
44 .get(TextCodec::ENCODING_KEY)
45 .map_or(TextCodec::ENCODING_UTF8, String::as_str);
46 if encoding != TextCodec::ENCODING_UTF8 {
47 return Err(CodecError::Decode(format!(
48 "Unsupported text encoding {encoding}"
49 )));
50 }
51 let text = std::str::from_utf8(&content.content)
52 .map_err(|utf8_err| CodecError::Decode(utf8_err.to_string()))?;
53 Ok(text.to_string())
54 }
55
56 fn should_push() -> bool {
57 true
58 }
59}
60
61#[cfg(test)]
62pub(crate) mod tests {
63 use crate::{ContentCodec, text::TextCodec};
64
65 #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
66 #[cfg_attr(not(target_arch = "wasm32"), test)]
67 fn can_encode_and_decode_text() {
68 let text = "Hello, world!";
69 let encoded_content =
70 TextCodec::encode(text.to_string()).expect("Should encode successfully");
71 let decoded_content =
72 TextCodec::decode(encoded_content).expect("Should decode successfully");
73 assert!(decoded_content == text);
74 }
75}