prodriguezdefino commented on code in PR #41484:
URL: https://github.com/apache/beam/pull/41484#discussion_r4634809588


##########
sdks/rust/beam/core/src/coders/traits.rs:
##########
@@ -0,0 +1,225 @@
+/*
+ * 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.
+ */
+
+//! Core traits and context definitions for Beam coders.
+
+use std::sync::Arc;
+use thiserror::Error;
+
+/// Error encountered during element encoding or decoding.
+#[derive(Error, Debug)]
+pub enum CoderError {
+    #[error("IO error during encoding/decoding: {0}")]
+    Io(#[from] std::io::Error),
+    #[error("UTF-8 decoding error: {0}")]
+    Utf8(#[from] std::string::FromUtf8Error),
+    #[error("Schema error during encoding/decoding: {0}")]
+    Schema(#[from] crate::schema::SchemaError),
+    #[error("Decoding format error: {0}")]
+    Format(String),
+    /// Error from a runner state stream backing a state-backed iterable.
+    #[error("{0}")]
+    StateStream(String),
+}
+
+/// Position of an element in the byte stream, which sets how it is delimited. 
In `Nested`
+/// context (inside a tuple, a KV or a stream), a variable-length element must 
have a length
+/// prefix. In `WholeStream` context, the element extends to the end of the 
stream.
+#[derive(Copy, Clone, Debug, PartialEq, Eq)]
+pub enum Context {
+    WholeStream,
+    Nested,
+}
+
+/// Maps each reader schema field to its position in a writer schema.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub enum FieldMap {
+    /// The writer schema has the wire layout of the reader type.
+    Same,
+    /// For each reader field, the writer field index, or `None` for an absent 
nullable field.
+    /// The `Arc` lets a lazy iterable decoder share the map with no copy.
+    ByName(Arc<[Option<usize>]>),
+}
+
+/// Keeps the [`FieldMap`] of one type for the last writer schema. A hit costs 
one pointer
+/// compare, so call [`get`](Self::get) for each element.
+#[derive(Clone, Debug, Default)]
+pub struct FieldMapCache {
+    resolved: Option<(Arc<crate::schema::Schema>, Option<FieldMap>)>,
+}
+
+impl FieldMapCache {
+    pub fn new() -> Self {
+        Self::default()
+    }
+
+    /// Returns [`DefaultCoder::resolve_field_map`] of `T` for `schema`. 
Resolves again only
+    /// when `schema` is a different `Arc`. Returns `Ok(None)` when `schema` 
is `None` or `T`
+    /// has no field map.
+    pub fn get<T: DefaultCoder>(
+        &mut self,
+        schema: Option<&Arc<crate::schema::Schema>>,
+    ) -> Result<Option<&FieldMap>, crate::schema::SchemaError> {
+        let Some(schema) = schema else {
+            return Ok(None);
+        };
+        let resolved = match self.resolved.take() {
+            Some((cached, map)) if Arc::ptr_eq(&cached, schema) => (cached, 
map),
+            Some(_) | None => (Arc::clone(schema), 
T::resolve_field_map(schema)?),
+        };
+        Ok(self.resolved.insert(resolved).1.as_ref())
+    }
+
+    /// Decodes one element of `T` from `bytes` with the field map for 
`schema`.
+    pub fn decode<T: DefaultCoder>(
+        &mut self,
+        bytes: &[u8],
+        schema: Option<&Arc<crate::schema::Schema>>,
+        state_reader: Option<&Arc<dyn super::iterable::StateStreamReader>>,
+    ) -> Result<T, CoderError> {
+        let map = self.get::<T>(schema)?;
+        T::decode_with_context(bytes, schema, map, state_reader)
+    }
+}
+
+/// Encodes and decodes values of type `T` in a Beam wire format.
+pub trait Coder<T>: Send + Sync + 'static {
+    /// Returns the Runner API coder URN, standard or custom.
+    fn urn(&self) -> &'static str;
+
+    fn encode(&self, value: &T, writer: &mut Vec<u8>, context: Context) -> 
Result<(), CoderError>;
+
+    fn decode(&self, reader: &mut &[u8], context: Context) -> Result<T, 
CoderError>;
+}
+
+/// Records coders in the Runner API pipeline components.
+pub trait CoderRegistry {
+    fn register_coder(&self, urn: &str, component_coder_ids: Vec<String>) -> 
String;
+
+    fn register_coder_with_payload(

Review Comment:
   This is intentional.
   
   `Pipeline` is the only production `CoderRegistry` in the SDK and implements 
both methods. 
   
   Users implement `Coder` and `DefaultCoder`, not `CoderRegistry`. 
   
   The default lets URN-only test registries record `(urn, components)` without 
boilerplate. Documented this on `register_coder_with_payload` in `af34003ad4d`.



-- 
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