confluent_kafka/common/serialization/
string_serializer.rs1use std::borrow::Cow;
24
25use crate::common::Error;
26use crate::common::serialization::Serializer;
27
28#[derive(Clone, Debug, Default)]
38#[non_exhaustive]
39#[doc(alias = "org.apache.kafka.common.serialization.StringSerializer")]
40pub struct StringSerializer;
41
42impl StringSerializer {
43 #[doc(alias = "org.apache.kafka.common.serialization.StringSerializer#StringSerializer")]
45 pub fn new() -> Self {
46 Self
47 }
48}
49
50impl Serializer<str> for StringSerializer {
51 async fn serialize<'a>(&'a self, _topic: &'a str, data: Option<&'a str>) -> Result<Option<Cow<'a, [u8]>>, Error> {
52 Ok(data.map(|s| Cow::Borrowed(s.as_bytes())))
53 }
54}
55
56impl Serializer<String> for StringSerializer {
57 async fn serialize<'a>(
58 &'a self,
59 _topic: &'a str,
60 data: Option<&'a String>,
61 ) -> Result<Option<Cow<'a, [u8]>>, Error> {
62 Ok(data.map(|s| Cow::Borrowed(s.as_bytes())))
63 }
64}
65
66#[cfg(test)]
67mod tests {
68 use super::*;
69
70 #[tokio::test]
71 async fn test_serialize_null() {
72 let serializer = StringSerializer::new();
73 let result = Serializer::<str>::serialize(&serializer, "topic", None).await;
74 assert_eq!(result.unwrap(), None);
75 }
76
77 #[tokio::test]
78 async fn test_serialize_string() {
79 let serializer = StringSerializer::new();
80 let result = Serializer::<str>::serialize(&serializer, "topic", Some("my string"))
81 .await
82 .unwrap();
83 assert_eq!(result.as_deref(), Some(&b"my string"[..]));
84 }
85
86 #[tokio::test]
87 async fn test_serialize_owned_string() {
88 let serializer = StringSerializer::new();
89 let data = "my string".to_string();
90 let result = Serializer::<String>::serialize(&serializer, "topic", Some(&data))
91 .await
92 .unwrap();
93 assert_eq!(result.as_deref(), Some(&b"my string"[..]));
94 }
95
96 #[tokio::test]
97 async fn test_serialize_empty_string() {
98 let serializer = StringSerializer::new();
99 let result = Serializer::<str>::serialize(&serializer, "topic", Some("")).await.unwrap();
100 assert_eq!(result.as_deref(), Some(&[][..]));
101 }
102
103 #[tokio::test]
104 async fn test_serialize_utf8() {
105 let serializer = StringSerializer::new();
106 let unicode_str = "\u{00e9}\u{00e8}\u{00ea}"; let result = Serializer::<str>::serialize(&serializer, "topic", Some(unicode_str))
108 .await
109 .unwrap();
110 assert_eq!(result.as_deref(), Some(unicode_str.as_bytes()));
111 }
112
113 #[tokio::test]
115 async fn test_serialize_borrows_the_input() {
116 let serializer = StringSerializer::new();
117 let data = "borrowed".to_string();
118 for result in [
119 Serializer::<str>::serialize(&serializer, "topic", Some(data.as_str())).await,
120 Serializer::<String>::serialize(&serializer, "topic", Some(&data)).await,
121 ] {
122 match result.unwrap() {
123 Some(Cow::Borrowed(bytes)) => assert_eq!(data.as_ptr(), bytes.as_ptr()),
124 other => panic!("expected borrowed bytes, got {other:?}"),
125 }
126 }
127 }
128}