confluent_kafka/common/serialization/byte_array_deserializer.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 deserializer.
16//!
17//! Passes through byte arrays unchanged.
18//!
19//! Corresponds to Java's `org.apache.kafka.common.serialization.ByteArrayDeserializer`.
20
21use crate::common::Error;
22use crate::common::serialization::Deserializer;
23
24/// Deserializes byte arrays by returning the bytes unchanged.
25///
26/// In Java the input array is returned by reference (no copy). In Rust the
27/// [`Deserializer`] trait hands `deserialize` a `&[u8]` borrowed from the
28/// `CompletedFetch` buffer (`consumer-threading.md` §27), so the only way to
29/// return the owned `Vec<u8>` the API promises is to copy via
30/// [`slice::to_vec`]. That single allocation is the user-deserializer's
31/// budget per §27 and is unavoidable for an owned-`Vec<u8>` value type.
32#[derive(Clone, Debug, Default)]
33#[non_exhaustive]
34#[doc(alias = "org.apache.kafka.common.serialization.ByteArrayDeserializer")]
35pub struct ByteArrayDeserializer;
36
37impl ByteArrayDeserializer {
38 /// Create a new `ByteArrayDeserializer`.
39 #[doc(alias = "org.apache.kafka.common.serialization.ByteArrayDeserializer#ByteArrayDeserializer")]
40 pub fn new() -> Self {
41 Self
42 }
43}
44
45impl Deserializer<Vec<u8>> for ByteArrayDeserializer {
46 async fn deserialize(&self, _topic: &str, data: &[u8]) -> Result<Vec<u8>, Error> {
47 Ok(data.to_vec())
48 }
49}
50
51#[cfg(test)]
52mod tests {
53 use super::*;
54
55 #[tokio::test]
56 async fn test_deserialize_bytes() {
57 let deserializer = ByteArrayDeserializer::new();
58 let data = b"my bytes";
59 let result = deserializer.deserialize("topic", data.as_slice()).await.unwrap();
60 assert_eq!(result, b"my bytes".to_vec());
61 }
62
63 #[tokio::test]
64 async fn test_deserialize_empty() {
65 let deserializer = ByteArrayDeserializer::new();
66 let data: &[u8] = &[];
67 let result = deserializer.deserialize("topic", data).await.unwrap();
68 assert_eq!(result, Vec::<u8>::new());
69 }
70}