From 3a371e5b0675803c2d5cbeae1d5a03b7a53d8cf7 Mon Sep 17 00:00:00 2001 From: Ruihang Xia Date: Tue, 9 Apr 2024 19:50:05 +0800 Subject: [PATCH 1/2] feat: add to Schema Signed-off-by: Ruihang Xia --- arrow-schema/src/schema.rs | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/arrow-schema/src/schema.rs b/arrow-schema/src/schema.rs index ede158fcf248..e422ac4de3a2 100644 --- a/arrow-schema/src/schema.rs +++ b/arrow-schema/src/schema.rs @@ -335,6 +335,10 @@ impl Schema { &self.fields[i] } + pub fn try_field(&self, i: usize) -> Option<&Field> { + self.fields.get(i).map(|f| f.as_ref()) + } + /// Returns an immutable reference of a specific [`Field`] instance selected by name. pub fn field_with_name(&self, name: &str) -> Result<&Field, ArrowError> { Ok(&self.fields[self.index_of(name)?]) @@ -650,6 +654,13 @@ mod tests { schema.index_of("nickname").unwrap(); } + #[test] + fn schema_try_field() { + let schema = person_schema(); + assert!(schema.try_field(0).is_some()); + assert!(schema.try_field(99999).is_none()); + } + #[test] #[should_panic( expected = "Unable to get field named \\\"nickname\\\". Valid fields: [\\\"first_name\\\", \\\"last_name\\\", \\\"address\\\", \\\"interests\\\"]" From 83da48b2926ba21d2bd2d2d6a6baf312f291544a Mon Sep 17 00:00:00 2001 From: Ruihang Xia Date: Tue, 9 Apr 2024 19:55:02 +0800 Subject: [PATCH 2/2] add docs Signed-off-by: Ruihang Xia --- arrow-schema/src/schema.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/arrow-schema/src/schema.rs b/arrow-schema/src/schema.rs index e422ac4de3a2..72ca56d7fbdc 100644 --- a/arrow-schema/src/schema.rs +++ b/arrow-schema/src/schema.rs @@ -331,10 +331,16 @@ impl Schema { /// Returns an immutable reference of a specific [`Field`] instance selected using an /// offset within the internal `fields` vector. + /// + /// Also consider using `try_field()` method with bounds check. pub fn field(&self, i: usize) -> &Field { &self.fields[i] } + /// Like `field()` but with bound check. + /// + /// Returns an immutable reference of a specific [`Field`] instance selected using an + /// offset within the internal `fields` vector. And `None` if the index is out of bounds. pub fn try_field(&self, i: usize) -> Option<&Field> { self.fields.get(i).map(|f| f.as_ref()) }