confluent_kafka/common/serialization/
byte_array_serializer.rs1use std::borrow::Cow;
22
23use crate::common::Error;
24use crate::common::serialization::Serializer;
25
26#[derive(Clone, Debug, Default)]
31#[non_exhaustive]
32#[doc(alias = "org.apache.kafka.common.serialization.ByteArraySerializer")]
33pub struct ByteArraySerializer;
34
35impl ByteArraySerializer {
36 #[doc(alias = "org.apache.kafka.common.serialization.ByteArraySerializer#ByteArraySerializer")]
38 pub fn new() -> Self {
39 Self
40 }
41}
42
43impl Serializer<[u8]> for ByteArraySerializer {
44 async fn serialize<'a>(&'a self, _topic: &'a str, data: Option<&'a [u8]>) -> Result<Option<Cow<'a, [u8]>>, Error> {
45 Ok(data.map(Cow::Borrowed))
46 }
47}
48
49impl Serializer<Vec<u8>> for ByteArraySerializer {
50 async fn serialize<'a>(
51 &'a self,
52 _topic: &'a str,
53 data: Option<&'a Vec<u8>>,
54 ) -> Result<Option<Cow<'a, [u8]>>, Error> {
55 Ok(data.map(|d| Cow::Borrowed(d.as_slice())))
56 }
57}
58
59#[cfg(test)]
60mod tests {
61 use super::*;
62 use crate::common::header::RecordHeaders;
63
64 #[tokio::test]
65 async fn test_serialize_null() {
66 let serializer = ByteArraySerializer::new();
67 let result = Serializer::<[u8]>::serialize(&serializer, "topic", None).await;
68 assert_eq!(result.unwrap(), None);
69 }
70
71 #[tokio::test]
72 async fn test_serialize_bytes() {
73 let serializer = ByteArraySerializer::new();
74 let data = b"my bytes";
75 let result = Serializer::<[u8]>::serialize(&serializer, "topic", Some(data.as_slice()))
76 .await
77 .unwrap();
78 assert_eq!(result.as_deref(), Some(&b"my bytes"[..]));
79 }
80
81 #[tokio::test]
82 async fn test_serialize_vec() {
83 let serializer = ByteArraySerializer::new();
84 let data = vec![1u8, 2, 3, 4, 5];
85 let result = Serializer::<Vec<u8>>::serialize(&serializer, "topic", Some(&data))
86 .await
87 .unwrap();
88 assert_eq!(result.as_deref(), Some(&[1u8, 2, 3, 4, 5][..]));
89 }
90
91 #[tokio::test]
92 async fn test_serialize_empty() {
93 let serializer = ByteArraySerializer::new();
94 let data: &[u8] = &[];
95 let result = Serializer::<[u8]>::serialize(&serializer, "topic", Some(data)).await.unwrap();
96 assert_eq!(result.as_deref(), Some(&[][..]));
97 }
98
99 #[tokio::test]
102 async fn test_serialize_borrows_the_input() {
103 let serializer = ByteArraySerializer::new();
104 let mut headers = RecordHeaders::new();
105 let data = vec![7u8, 8, 9];
106 for result in [
107 Serializer::<[u8]>::serialize(&serializer, "topic", Some(&data[..])).await,
108 Serializer::<[u8]>::serialize_with_headers(&serializer, "topic", &mut headers, Some(&data[..])).await,
109 Serializer::<Vec<u8>>::serialize(&serializer, "topic", Some(&data)).await,
110 Serializer::<Vec<u8>>::serialize_with_headers(&serializer, "topic", &mut headers, Some(&data)).await,
111 ] {
112 match result.unwrap() {
113 Some(Cow::Borrowed(bytes)) => assert_eq!(data.as_ptr(), bytes.as_ptr()),
114 other => panic!("expected borrowed bytes, got {other:?}"),
115 }
116 }
117 }
118}