Skip to main content

confluent_kafka/common/serialization/
byte_array_serializer.rs

1// Copyright 2025 Confluent Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Byte array serializer.
16//!
17//! Passes through byte arrays unchanged.
18//!
19//! Corresponds to Java's `org.apache.kafka.common.serialization.ByteArraySerializer`.
20
21use std::borrow::Cow;
22
23use crate::common::Error;
24use crate::common::serialization::Serializer;
25
26/// Serializes byte arrays by passing them through unchanged.
27///
28/// The serialized bytes borrow the input ([`Cow::Borrowed`]): Java returns the
29/// input `byte[]` itself, and this neither allocates nor copies.
30#[derive(Clone, Debug, Default)]
31#[non_exhaustive]
32#[doc(alias = "org.apache.kafka.common.serialization.ByteArraySerializer")]
33pub struct ByteArraySerializer;
34
35impl ByteArraySerializer {
36    /// Create a new `ByteArraySerializer`.
37    #[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    /// The output borrows the input: no allocation and no copy, for both the
100    /// slice and the `Vec<u8>` form, with and without headers.
101    #[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}