This is an automated email from the ASF dual-hosted git repository.

mgrigorov pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/avro-rs.git


The following commit(s) were added to refs/heads/main by this push:
     new 6f1a042  feat: Add `Record::get(str)` - getter for record fields (#130)
6f1a042 is described below

commit 6f1a0425b61a22dc4f32c6ceb912737464c030f7
Author: Igor Artamonov <[email protected]>
AuthorDate: Fri Feb 21 07:15:10 2025 +0000

    feat: Add `Record::get(str)` - getter for record fields (#130)
    
    * `get` from a Record
    
    * Fix the formatting
    
    Signed-off-by: Martin Tzvetanov Grigorov <[email protected]>
    
    * Minor cleanup
    
    Signed-off-by: Martin Tzvetanov Grigorov <[email protected]>
    
    ---------
    
    Signed-off-by: Martin Tzvetanov Grigorov <[email protected]>
    Co-authored-by: Martin Tzvetanov Grigorov <[email protected]>
---
 avro/src/types.rs | 45 +++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 45 insertions(+)

diff --git a/avro/src/types.rs b/avro/src/types.rs
index 8c062f0..5eda809 100644
--- a/avro/src/types.rs
+++ b/avro/src/types.rs
@@ -269,6 +269,14 @@ impl Record<'_> {
             self.fields[position].1 = value.into()
         }
     }
+
+    /// Get the value for a given field name.
+    /// Returns `None` if the field is not present in the schema
+    pub fn get(&self, field: &str) -> Option<&Value> {
+        self.schema_lookup
+            .get(field)
+            .map(|&position| &self.fields[position].1)
+    }
 }
 
 impl<'a> From<Record<'a>> for Value {
@@ -3224,4 +3232,41 @@ Field with name '"b"' is not a member of the map items"#,
         }
         Ok(())
     }
+
+    #[test]
+    fn avro_rs_130_get_from_record() -> TestResult {
+        let schema = r#"
+        {
+            "type": "record",
+            "name": "NamespacedMessage",
+            "namespace": "space",
+            "fields": [
+                {
+                    "name": "foo",
+                    "type": "string"
+                },
+                {
+                    "name": "bar",
+                    "type": "long"
+                }
+            ]
+        }
+        "#;
+
+        let schema = Schema::parse_str(schema)?;
+        let mut record = Record::new(&schema).unwrap();
+        record.put("foo", "hello");
+        record.put("bar", 123_i64);
+
+        assert_eq!(
+            record.get("foo").unwrap(),
+            &Value::String("hello".to_string())
+        );
+        assert_eq!(record.get("bar").unwrap(), &Value::Long(123));
+
+        // also make sure it doesn't fail but return None for non-existing 
field
+        assert_eq!(record.get("baz"), None);
+
+        Ok(())
+    }
 }

Reply via email to