martin-g commented on code in PR #430:
URL: https://github.com/apache/avro-rs/pull/430#discussion_r2722789111


##########
avro/src/serde/with.rs:
##########
@@ -0,0 +1,793 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::cell::Cell;
+
+thread_local! {
+    /// A thread local that is used to decide how to serialize Rust bytes into 
an Avro
+    /// `types::Value` of type bytes.
+    ///
+    /// Relies on the fact that serde's serialization process is 
single-threaded.
+    pub(crate) static SER_BYTES_TYPE: Cell<BytesType> = const { 
Cell::new(BytesType::Bytes) };
+
+    /// A thread local that is used to decide how to deserialize an Avro 
`types::Value`
+    /// of type bytes into Rust bytes.
+    ///
+    /// Relies on the fact that serde's deserialization process is 
single-threaded.
+    pub(crate) static DE_BYTES_BORROWED: Cell<bool> = const { Cell::new(false) 
};
+}
+
+#[derive(Debug, Clone, Copy)]
+pub(crate) enum BytesType {
+    Bytes,
+    Fixed,
+}
+
+/// Efficient (de)serialization of Avro bytes values.
+///
+/// This module is intended to be used through the Serde `with` attribute.
+/// Use [`apache_avro::serde::bytes_opt`] for optional bytes.
+///
+/// See usage with below example:
+/// ```
+/// # use apache_avro::AvroSchema;
+/// # use serde::{Deserialize, Serialize};
+///
+/// #[derive(AvroSchema, Serialize, Deserialize)]
+/// struct StructWithBytes {
+///     #[avro(with)]
+///     #[serde(with = "apache_avro::serde::bytes")]
+///     vec_field: Vec<u8>,
+///
+///     #[avro(with = apache_avro::serde::fixed::get_schema_in_ctxt::<6>)]
+///     #[serde(with = "apache_avro::serde::fixed")]
+///     fixed_field: [u8; 6],
+/// }
+/// ```
+///
+/// [`apache_avro::serde::bytes_opt`]: bytes_opt
+pub mod bytes {
+    use serde::{Deserializer, Serializer};
+
+    use crate::{
+        Schema,
+        schema::{Names, Namespace},
+    };
+
+    /// Returns [`Schema::Bytes`]
+    pub fn get_schema_in_ctxt(_names: &mut Names, _enclosing_namespace: 
&Namespace) -> Schema {
+        Schema::Bytes
+    }
+
+    pub fn serialize<S>(bytes: &[u8], serializer: S) -> Result<S::Ok, S::Error>
+    where
+        S: Serializer,
+    {
+        serde_bytes::serialize(bytes, serializer)
+    }
+
+    pub fn deserialize<'de, D>(deserializer: D) -> Result<Vec<u8>, D::Error>
+    where
+        D: Deserializer<'de>,
+    {
+        serde_bytes::deserialize(deserializer)
+    }
+}
+
+/// Efficient (de)serialization of optional Avro bytes values.
+///
+/// This module is intended to be used through the Serde `with` attribute.
+/// Use [`apache_avro::serde::bytes`] for non-optional bytes.
+///
+/// See usage with below example:
+/// ```
+/// # use apache_avro::AvroSchema;
+/// # use serde::{Deserialize, Serialize};
+///
+/// #[derive(AvroSchema, Serialize, Deserialize)]
+/// struct StructWithBytes {
+///     #[avro(with)]
+///     #[serde(with = "apache_avro::serde::bytes_opt")]
+///     vec_field: Option<Vec<u8>>,
+///
+///     #[avro(with = apache_avro::serde::fixed_opt::get_schema_in_ctxt::<6>)]
+///     #[serde(with = "apache_avro::serde::fixed_opt")]
+///     fixed_field: Option<[u8; 6]>,
+/// }
+/// ```
+///
+/// [`apache_avro::serde::bytes`]: bytes
+pub mod bytes_opt {
+    use serde::{Deserializer, Serializer};
+    use std::borrow::Borrow;
+
+    use crate::{
+        Schema,
+        schema::{Names, Namespace, UnionSchema},
+    };
+
+    /// Returns `Schema::Union(Schema::Null, Schema::Bytes)`
+    pub fn get_schema_in_ctxt(_names: &mut Names, _enclosing_namespace: 
&Namespace) -> Schema {
+        Schema::Union(
+            UnionSchema::new(vec![Schema::Null, Schema::Bytes]).expect("This 
is a valid union"),
+        )
+    }
+
+    pub fn serialize<S, B>(bytes: &Option<B>, serializer: S) -> Result<S::Ok, 
S::Error>
+    where
+        S: Serializer,
+        B: Borrow<[u8]> + serde_bytes::Serialize,
+    {
+        serde_bytes::serialize(bytes, serializer)
+    }
+
+    pub fn deserialize<'de, D>(deserializer: D) -> Result<Option<Vec<u8>>, 
D::Error>
+    where
+        D: Deserializer<'de>,
+    {
+        serde_bytes::deserialize(deserializer)
+    }
+}
+
+/// Efficient (de)serialization of Avro fixed values.
+///
+/// This module is intended to be used through the Serde `with` attribute.
+/// Use [`apache_avro::serde::fixed_opt`] for optional fixed values.
+///
+/// See usage with below example:
+/// ```
+/// # use apache_avro::AvroSchema;
+/// # use serde::{Deserialize, Serialize};
+///
+/// #[derive(AvroSchema, Serialize, Deserialize)]
+/// struct StructWithBytes {
+///     #[avro(with)]
+///     #[serde(with = "apache_avro::serde::bytes")]
+///     vec_field: Vec<u8>,
+///
+///     #[avro(with = apache_avro::serde::fixed::get_schema_in_ctxt::<6>)]
+///     #[serde(with = "apache_avro::serde::fixed")]
+///     fixed_field: [u8; 6],
+/// }
+/// ```
+///
+/// [`apache_avro::serde::fixed_opt`]: fixed_opt
+pub mod fixed {
+    use super::{BytesType, SER_BYTES_TYPE};
+    use serde::{Deserializer, Serializer};
+
+    use crate::{
+        Schema,
+        schema::{FixedSchema, Name, Names, Namespace},
+    };
+
+    /// Returns `Schema::Fixed(N)` named `serde_avro_fixed_{N}`
+    #[expect(clippy::map_entry, reason = "We don't use the value from the 
map")]
+    pub fn get_schema_in_ctxt<const N: usize>(
+        named_schemas: &mut Names,
+        enclosing_namespace: &Namespace,
+    ) -> Schema {
+        let name = Name::new(&format!("serde_avro_fixed_{N}"))
+            .expect("Name is valid")
+            .fully_qualified_name(enclosing_namespace);
+        if named_schemas.contains_key(&name) {
+            Schema::Ref { name }
+        } else {
+            let schema = 
Schema::Fixed(FixedSchema::builder().name(name.clone()).size(N).build());
+            named_schemas.insert(name, schema.clone());
+            schema
+        }
+    }
+
+    pub fn serialize<S>(bytes: &[u8], serializer: S) -> Result<S::Ok, S::Error>
+    where
+        S: Serializer,
+    {
+        SER_BYTES_TYPE.set(BytesType::Fixed);
+        let res = serde_bytes::serialize(bytes, serializer);
+        SER_BYTES_TYPE.set(BytesType::Bytes);
+        res
+    }
+
+    pub fn deserialize<'de, D, const N: usize>(deserializer: D) -> Result<[u8; 
N], D::Error>
+    where
+        D: Deserializer<'de>,
+    {
+        serde_bytes::deserialize(deserializer)
+    }
+}
+
+/// Efficient (de)serialization of optional Avro fixed values.
+///
+/// This module is intended to be used through the Serde `with` attribute.
+/// Use [`apache_avro::serde::fixed`] for non-optional fixed values.
+///
+/// See usage with below example:
+/// ```
+/// # use apache_avro::AvroSchema;
+/// # use serde::{Deserialize, Serialize};
+///
+/// #[derive(AvroSchema, Serialize, Deserialize)]
+/// struct StructWithBytes {
+///     #[avro(with)]
+///     #[serde(with = "apache_avro::serde::bytes_opt")]
+///     vec_field: Option<Vec<u8>>,
+///
+///     #[avro(with = apache_avro::serde::fixed_opt::get_schema_in_ctxt::<6>)]
+///     #[serde(with = "apache_avro::serde::fixed_opt")]
+///     fixed_field: Option<[u8; 6]>,
+/// }
+/// ```
+///
+/// [`apache_avro::serde::fixed`]: fixed
+pub mod fixed_opt {
+    use super::{BytesType, SER_BYTES_TYPE};
+    use serde::{Deserializer, Serializer};
+    use std::borrow::Borrow;
+
+    use crate::{
+        Schema,
+        schema::{Names, Namespace, UnionSchema},
+    };
+
+    /// Returns `Schema::Union(Schema::Null, Schema::Fixed(N))` where the 
fixed schema is named `serde_avro_fixed_{N}`
+    pub fn get_schema_in_ctxt<const N: usize>(
+        named_schemas: &mut Names,
+        enclosing_namespace: &Namespace,
+    ) -> Schema {
+        Schema::Union(
+            UnionSchema::new(vec![
+                Schema::Null,
+                super::fixed::get_schema_in_ctxt::<N>(named_schemas, 
enclosing_namespace),
+            ])
+            .expect("This is a valid union"),
+        )
+    }
+
+    pub fn serialize<S, B>(bytes: &Option<B>, serializer: S) -> Result<S::Ok, 
S::Error>
+    where
+        S: Serializer,
+        B: Borrow<[u8]> + serde_bytes::Serialize,
+    {
+        SER_BYTES_TYPE.set(BytesType::Fixed);
+        let res = serde_bytes::serialize(bytes, serializer);
+        SER_BYTES_TYPE.set(BytesType::Bytes);
+        res
+    }
+
+    pub fn deserialize<'de, D, const N: usize>(deserializer: D) -> 
Result<Option<[u8; N]>, D::Error>
+    where
+        D: Deserializer<'de>,
+    {
+        serde_bytes::deserialize(deserializer)
+    }
+}
+
+/// Efficient (de)serialization of Avro bytes/fixed borrowed values.
+///
+/// This module is intended to be used through the Serde `with` attribute.
+///
+/// Note that `&[u8]` are always serialized as [`Value::Bytes`]. However,
+/// both [`Value::Bytes`] and [`Value::Fixed`] can be deserialized as `&[u8]`.
+///
+/// Use [`apache_avro::serde::slice`] for optional bytes/fixed borrowed values.

Review Comment:
   ```suggestion
   /// Use [`apache_avro::serde::slice_opt`] for optional bytes/fixed borrowed 
values.
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to