Skip to main content

confluent_kafka/common/serialization/
string_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//! String serializer.
16//!
17//! String encoding defaults to UTF-8. Unlike the Java implementation which
18//! supports configurable charsets, Rust strings are always valid UTF-8, so
19//! this serializer simply converts to UTF-8 bytes.
20//!
21//! Corresponds to Java's `org.apache.kafka.common.serialization.StringSerializer`.
22
23use std::borrow::Cow;
24
25use crate::common::Error;
26use crate::common::serialization::Serializer;
27
28/// String encoding defaults to UTF8 and can be customized by setting the
29/// property key.serializer.encoding, value.serializer.encoding or
30/// serializer.encoding. The first two take precedence over the last.
31///
32/// # Translation notes
33///
34/// WARNING: the encoding is always UTF-8; the properties are ignored.
35// A Rust string already is its UTF-8 bytes, so the serialized bytes borrow it
36// (`Cow::Borrowed`) and nothing is allocated or copied.
37#[derive(Clone, Debug, Default)]
38#[non_exhaustive]
39#[doc(alias = "org.apache.kafka.common.serialization.StringSerializer")]
40pub struct StringSerializer;
41
42impl StringSerializer {
43    /// Create a new `StringSerializer`.
44    #[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}"; // accented chars
107        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    /// The output borrows the string's own UTF-8 bytes: no allocation, no copy.
114    #[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}