ViewResultIteratorExt

Trait ViewResultIteratorExt 

Source
pub trait ViewResultIteratorExt: Iterator + Sized {
    type Item;

    // Provided method
    fn try_flatten(
        self,
    ) -> Result<Vec<<Self as ViewResultIteratorExt>::Item>, ViewAccessError>
       where Result<Vec<<Self as ViewResultIteratorExt>::Item>, ViewAccessError>: FromIterator<<Self as Iterator>::Item> { ... }
}
Expand description

Extension trait providing convenience methods for iterators over Result<T, ViewAccessError>.

This trait is automatically implemented for any iterator yielding Result<T, ViewAccessError>, such as the iterators returned by FromRecordBatch::from_record_batch.

Required Associated Types§

Source

type Item

The success type of the Result items.

Provided Methods§

Source

fn try_flatten( self, ) -> Result<Vec<<Self as ViewResultIteratorExt>::Item>, ViewAccessError>

Flatten the Result iterator, returning all views or the first error.

This consumes the iterator and returns a Result containing either:

  • Ok(Vec<T>) with all successfully accessed views
  • Err(ViewAccessError) with the first error encountered
§Errors

Returns the first ViewAccessError encountered while iterating.

§Example
use typed_arrow::prelude::*;

#[derive(typed_arrow::Record)]
struct Row {
    id: i32,
    name: String,
}

// Returns all views or first error
let views = batch.iter_views::<Row>()?.try_flatten()?;
for row in views {
    println!("{}: {}", row.id, row.name);
}
Examples found in repository?
examples/13_record_batch_views.rs (line 78)
43fn flat_record_example() -> Result<(), typed_arrow::schema::SchemaError> {
44    // Build rows
45    let rows = vec![
46        Product {
47            id: 1,
48            name: "Widget".into(),
49            price: 9.99,
50            in_stock: Some(true),
51        },
52        Product {
53            id: 2,
54            name: "Gadget".into(),
55            price: 19.99,
56            in_stock: None,
57        },
58        Product {
59            id: 3,
60            name: "Doohickey".into(),
61            price: 14.50,
62            in_stock: Some(false),
63        },
64    ];
65
66    // Build RecordBatch
67    let mut b = <Product as BuildRows>::new_builders(rows.len());
68    b.append_rows(rows);
69    let arrays = b.finish();
70    let batch: RecordBatch = arrays.into_record_batch();
71
72    println!("RecordBatch has {} rows", batch.num_rows());
73
74    // Create zero-copy views over the batch using the convenient API
75    let views = batch.iter_views::<Product>()?;
76
77    println!("Products in stock:");
78    for view in views.try_flatten()? {
79        // All fields are borrowed references - no copying!
80        // Strings are &str, primitives are copied (they're small)
81        match view.in_stock {
82            Some(true) => println!("  #{}: {} - ${:.2}", view.id, view.name, view.price),
83            Some(false) => {}
84            None => {}
85        }
86    }
87
88    Ok(())
89}
90
91fn nested_record_example() -> Result<(), typed_arrow::schema::SchemaError> {
92    let locations = vec![
93        Location {
94            city: "New York".into(),
95            coords: Some(Coordinates {
96                lat: 40.7128,
97                lon: -74.0060,
98            }),
99        },
100        Location {
101            city: "Unknown City".into(),
102            coords: None,
103        },
104        Location {
105            city: "San Francisco".into(),
106            coords: Some(Coordinates {
107                lat: 37.7749,
108                lon: -122.4194,
109            }),
110        },
111    ];
112
113    let mut b = <Location as BuildRows>::new_builders(locations.len());
114    b.append_rows(locations);
115    let arrays = b.finish();
116    let batch: RecordBatch = arrays.into_record_batch();
117
118    println!("RecordBatch has {} rows", batch.num_rows());
119
120    // Iterate with zero-copy views using the convenient API
121    let views = batch.iter_views::<Location>()?;
122
123    println!("Locations with coordinates:");
124    for view in views.try_flatten()? {
125        print!("  {}: ", view.city);
126        match view.coords {
127            Some(coords) => println!("({:.4}, {:.4})", coords.lat, coords.lon),
128            None => println!("(no coordinates)"),
129        }
130    }
131
132    Ok(())
133}
134
135fn view_conversion_example() -> Result<(), typed_arrow::schema::SchemaError> {
136    let products = vec![
137        Product {
138            id: 100,
139            name: "Laptop".into(),
140            price: 999.99,
141            in_stock: Some(true),
142        },
143        Product {
144            id: 101,
145            name: "Mouse".into(),
146            price: 29.99,
147            in_stock: Some(true),
148        },
149    ];
150
151    let mut b = <Product as BuildRows>::new_builders(products.len());
152    b.append_rows(products);
153    let arrays = b.finish();
154    let batch: RecordBatch = arrays.into_record_batch();
155
156    println!("RecordBatch has {} rows", batch.num_rows());
157
158    // Iterate over views and convert selected ones to owned records
159    let views = batch.iter_views::<Product>()?;
160    let mut owned_products: Vec<Product> = Vec::new();
161
162    for view in views.try_flatten()? {
163        // Views provide zero-copy access - strings are &str, not String
164        println!("View: {} (price: ${:.2})", view.name, view.price);
165
166        // Convert view to owned when you need to store it beyond the batch lifetime
167        if view.price > 50.0 {
168            let owned: Product = view.try_into()?;
169            owned_products.push(owned);
170        }
171    }
172
173    println!(
174        "\nCollected {} expensive products as owned records",
175        owned_products.len()
176    );
177    for product in &owned_products {
178        println!("  Owned: {} - ${:.2}", product.name, product.price);
179    }
180
181    Ok(())
182}

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.

Implementors§

Source§

impl<I, T> ViewResultIteratorExt for I
where I: Iterator<Item = Result<T, ViewAccessError>>,

Available on crate feature views only.
Source§

type Item = T