LazyQuery

Struct LazyQuery 

Source
pub struct LazyQuery<'a, T: 'static, I>
where I: Iterator<Item = &'a T>,
{ /* private fields */ }
Expand description

A lazy query builder that uses iterators for deferred execution.

Unlike the standard Query, LazyQuery doesn’t execute until you call a terminal operation like .collect(), .count(), or .first().

§Benefits

  • Deferred execution: No work until results needed
  • Iterator fusion: Rust optimizes chained operations
  • Early termination: .take() stops as soon as enough items found
  • Composable: Build complex queries by composition

§Example

// Nothing executes yet
let query = LazyQuery::new(&products)
    .where_(Product::price_r(), |&p| p < 100.0)
    .where_(Product::stock_r(), |&s| s > 0);

// Execution happens here
let results: Vec<_> = query.collect();

Implementations§

Source§

impl<'a, T: 'static> LazyQuery<'a, T, Iter<'a, T>>

Source

pub fn new(data: &'a [T]) -> Self

Creates a new lazy query from a slice.

§Example
let query = LazyQuery::new(&products);
Examples found in repository?
examples/lazy_evaluation.rs (line 65)
47fn main() {
48    println!("\n╔════════════════════════════════════════════════════════════════╗");
49    println!("║  Lazy Query Evaluation Demo                                   ║");
50    println!("╚════════════════════════════════════════════════════════════════╝\n");
51
52    let products = create_products();
53    println!("Created {} products\n", products.len());
54
55    // ============================================================================
56    // DEMO 1: Lazy Execution - Nothing Happens Until .collect()
57    // ============================================================================
58    println!("═══════════════════════════════════════════════════════════════");
59    println!("Demo 1: Lazy execution - deferred until needed");
60    println!("═══════════════════════════════════════════════════════════════\n");
61
62    FILTER_EVALUATIONS.store(0, Ordering::SeqCst);
63
64    println!("Building query (should execute nothing)...");
65    let lazy_query = LazyQuery::new(&products)
66        .where_(Product::category_r(), |cat| {
67            FILTER_EVALUATIONS.fetch_add(1, Ordering::SeqCst);
68            cat == "Electronics"
69        });
70
71    let evals_after_build = FILTER_EVALUATIONS.load(Ordering::SeqCst);
72    println!("  Filter evaluations after building query: {}", evals_after_build);
73    
74    if evals_after_build == 0 {
75        println!("  ✅ Confirmed: Query is lazy! Nothing executed yet.\n");
76    }
77
78    println!("Collecting results (now it executes)...");
79    let results: Vec<_> = lazy_query.collect();
80
81    let evals_after_collect = FILTER_EVALUATIONS.load(Ordering::SeqCst);
82    println!("  Filter evaluations after collecting: {}", evals_after_collect);
83    println!("  Results found: {}", results.len());
84    println!("  ✅ Query executed exactly once, when needed!\n");
85
86    // ============================================================================
87    // DEMO 2: Early Termination - Stops as Soon as Enough Items Found
88    // ============================================================================
89    println!("═══════════════════════════════════════════════════════════════");
90    println!("Demo 2: Early termination with .take()");
91    println!("═══════════════════════════════════════════════════════════════\n");
92
93    EXPENSIVE_OPERATIONS.store(0, Ordering::SeqCst);
94
95    println!("Finding first 5 expensive items from 1000 products...");
96    let first_5: Vec<_> = LazyQuery::new(&products)
97        .where_(Product::price_r(), |p| expensive_check(p))
98        .take_lazy(5)
99        .collect();
100
101    let ops = EXPENSIVE_OPERATIONS.load(Ordering::SeqCst);
102    println!("  Found: {} items", first_5.len());
103    println!("  Expensive operations performed: {}", ops);
104    println!("  Items NOT checked: {} (stopped early!)", 1000 - ops);
105    
106    if ops < 1000 {
107        println!("  ✅ Early termination worked! Didn't check all 1000 items.\n");
108    }
109
110    // ============================================================================
111    // DEMO 3: Iterator Fusion - Rust Optimizes Chained Operations
112    // ============================================================================
113    println!("═══════════════════════════════════════════════════════════════");
114    println!("Demo 3: Iterator fusion - chained operations optimized");
115    println!("═══════════════════════════════════════════════════════════════\n");
116
117    println!("Chaining multiple operations...");
118    let chained_query = LazyQuery::new(&products)
119        .where_(Product::category_r(), |cat| cat == "Electronics")
120        .where_(Product::price_r(), |&price| price > 200.0)
121        .where_(Product::stock_r(), |&stock| stock > 10)
122        .take_lazy(10);
123
124    println!("  Built query with 3 filters + take(10)");
125    println!("  ✅ No execution yet - all operations fused into one iterator\n");
126
127    let results: Vec<_> = chained_query.collect();
128    println!("  Executed: Found {} items", results.len());
129    println!("  ✅ All filters applied in single pass!\n");
130
131    // ============================================================================
132    // DEMO 4: Lazy Projection - Only Extract What You Need
133    // ============================================================================
134    println!("═══════════════════════════════════════════════════════════════");
135    println!("Demo 4: Lazy projection");
136    println!("═══════════════════════════════════════════════════════════════\n");
137
138    println!("Selecting names (lazy)...");
139    let names: Vec<String> = LazyQuery::new(&products)
140        .where_(Product::category_r(), |cat| cat == "Electronics")
141        .select_lazy(Product::name_r())
142        .take(5)  // Only process until we have 5
143        .collect();
144
145    println!("  Selected {} names", names.len());
146    println!("  ✅ Only evaluated until 5 names found!\n");
147
148    // ============================================================================
149    // DEMO 5: Lazy Aggregation - Short-Circuit When Possible
150    // ============================================================================
151    println!("═══════════════════════════════════════════════════════════════");
152    println!("Demo 5: Short-circuit with .any()");
153    println!("═══════════════════════════════════════════════════════════════\n");
154
155    FILTER_EVALUATIONS.store(0, Ordering::SeqCst);
156
157    println!("Checking if ANY electronics exist (1000 items to search)...");
158    let exists = LazyQuery::new(&products)
159        .where_(Product::category_r(), |cat| {
160            FILTER_EVALUATIONS.fetch_add(1, Ordering::SeqCst);
161            cat == "Electronics"
162        })
163        .any();
164
165    let checks = FILTER_EVALUATIONS.load(Ordering::SeqCst);
166    println!("  Result: {}", exists);
167    println!("  Items checked: {} out of 1000", checks);
168    println!("  Items skipped: {} (short-circuited!)", 1000 - checks);
169    
170    if checks < 1000 {
171        println!("  ✅ Short-circuit worked! Stopped as soon as first match found.\n");
172    }
173
174    // ============================================================================
175    // DEMO 6: Lazy Find - Stops at First Match
176    // ============================================================================
177    println!("═══════════════════════════════════════════════════════════════");
178    println!("Demo 6: .find() stops at first match");
179    println!("═══════════════════════════════════════════════════════════════\n");
180
181    FILTER_EVALUATIONS.store(0, Ordering::SeqCst);
182
183    println!("Finding first product with price > 500...");
184    let found = LazyQuery::new(&products)
185        .where_(Product::price_r(), |&price| {
186            FILTER_EVALUATIONS.fetch_add(1, Ordering::SeqCst);
187            price > 500.0
188        })
189        .first();
190
191    let checks = FILTER_EVALUATIONS.load(Ordering::SeqCst);
192    if let Some(product) = found {
193        println!("  Found: {} (${:.2})", product.name, product.price);
194    }
195    println!("  Items checked: {} out of 1000", checks);
196    println!("  ✅ Stopped immediately after finding first match!\n");
197
198    // ============================================================================
199    // DEMO 7: Composition - Build Queries Incrementally
200    // ============================================================================
201    println!("═══════════════════════════════════════════════════════════════");
202    println!("Demo 7: Composable queries");
203    println!("═══════════════════════════════════════════════════════════════\n");
204
205    println!("Building base query...");
206    let base_query = LazyQuery::new(&products)
207        .where_(Product::category_r(), |cat| cat == "Electronics");
208
209    println!("  Created base query (not executed)\n");
210
211    println!("  Adding price filter...");
212    let refined_query = base_query
213        .where_(Product::price_r(), |&price| price > 100.0);
214
215    println!("  Still not executed...\n");
216
217    println!("  Adding stock filter and limiting...");
218    let final_query = refined_query
219        .where_(Product::stock_r(), |&stock| stock > 5)
220        .take_lazy(10);
221
222    println!("  Still not executed...\n");
223
224    println!("  Executing...");
225    let results: Vec<_> = final_query.collect();
226    println!("  ✅ Executed once with all filters: Found {} items\n", results.len());
227
228    // ============================================================================
229    // DEMO 8: For Loop - Natural Iteration
230    // ============================================================================
231    println!("═══════════════════════════════════════════════════════════════");
232    println!("Demo 8: Use in for loops");
233    println!("═══════════════════════════════════════════════════════════════\n");
234
235    println!("Iterating over filtered products...");
236    let mut count = 0;
237    for product in LazyQuery::new(&products)
238        .where_(Product::category_r(), |cat| cat == "Electronics")
239        .take_lazy(3)
240    {
241        println!("  • {}: ${:.2}", product.name, product.price);
242        count += 1;
243    }
244    println!("  ✅ Processed {} items lazily\n", count);
245
246    // ============================================================================
247    // DEMO 9: Performance Comparison
248    // ============================================================================
249    println!("═══════════════════════════════════════════════════════════════");
250    println!("Demo 9: Performance benefit demonstration");
251    println!("═══════════════════════════════════════════════════════════════\n");
252
253    println!("Scenario: Find first expensive item from 1000 products\n");
254
255    EXPENSIVE_OPERATIONS.store(0, Ordering::SeqCst);
256    
257    println!("Without lazy (hypothetical - check all, then take first):");
258    println!("  Would check: 1000 items");
259    println!("  Would find: ~300 matching items");
260    println!("  Would return: 1 item");
261    println!("  Wasted work: 299 items processed unnecessarily\n");
262
263    EXPENSIVE_OPERATIONS.store(0, Ordering::SeqCst);
264    
265    println!("With lazy evaluation:");
266    let _first = LazyQuery::new(&products)
267        .where_(Product::price_r(), |p| expensive_check(p))
268        .first();
269
270    let ops = EXPENSIVE_OPERATIONS.load(Ordering::SeqCst);
271    println!("  Checked: {} items", ops);
272    println!("  Found: 1 item");
273    println!("  Wasted work: 0 items");
274    println!("  ✅ Efficiency gain: {}x faster!", 1000 / ops.max(1));
275
276    // ============================================================================
277    // Summary
278    // ============================================================================
279    println!("\n╔════════════════════════════════════════════════════════════════╗");
280    println!("║  Lazy Evaluation Benefits                                     ║");
281    println!("╚════════════════════════════════════════════════════════════════╝\n");
282
283    println!("✅ Deferred Execution:");
284    println!("   • No work until results needed");
285    println!("   • Can build complex queries without performance cost\n");
286
287    println!("✅ Early Termination:");
288    println!("   • .take(n) stops after n items");
289    println!("   • .first() stops after 1 item");
290    println!("   • .any() stops after first match");
291    println!("   • Massive performance win for large datasets\n");
292
293    println!("✅ Iterator Fusion:");
294    println!("   • Multiple filters combined into one pass");
295    println!("   • Rust compiler optimizes chained operations");
296    println!("   • No intermediate allocations\n");
297
298    println!("✅ Composable:");
299    println!("   • Build queries incrementally");
300    println!("   • Reuse query fragments");
301    println!("   • Clean separation of query building vs execution\n");
302
303    println!("✅ Zero Overhead:");
304    println!("   • Compiles to same code as manual loops");
305    println!("   • No runtime cost for abstraction");
306    println!("   • Pay only for what you use\n");
307
308    println!("✓ Lazy evaluation demo complete!\n");
309}
Source§

impl<'a, T: 'static, I> LazyQuery<'a, T, I>
where I: Iterator<Item = &'a T> + 'a,

Source

pub fn where_<F, P>( self, path: KeyPaths<T, F>, predicate: P, ) -> LazyQuery<'a, T, impl Iterator<Item = &'a T> + 'a>
where F: 'static, P: Fn(&F) -> bool + 'a,

Adds a filter predicate (lazy - not executed yet).

§Example
let query = LazyQuery::new(&products)
    .where_(Product::price_r(), |&p| p < 100.0);
Examples found in repository?
examples/lazy_evaluation.rs (lines 66-69)
47fn main() {
48    println!("\n╔════════════════════════════════════════════════════════════════╗");
49    println!("║  Lazy Query Evaluation Demo                                   ║");
50    println!("╚════════════════════════════════════════════════════════════════╝\n");
51
52    let products = create_products();
53    println!("Created {} products\n", products.len());
54
55    // ============================================================================
56    // DEMO 1: Lazy Execution - Nothing Happens Until .collect()
57    // ============================================================================
58    println!("═══════════════════════════════════════════════════════════════");
59    println!("Demo 1: Lazy execution - deferred until needed");
60    println!("═══════════════════════════════════════════════════════════════\n");
61
62    FILTER_EVALUATIONS.store(0, Ordering::SeqCst);
63
64    println!("Building query (should execute nothing)...");
65    let lazy_query = LazyQuery::new(&products)
66        .where_(Product::category_r(), |cat| {
67            FILTER_EVALUATIONS.fetch_add(1, Ordering::SeqCst);
68            cat == "Electronics"
69        });
70
71    let evals_after_build = FILTER_EVALUATIONS.load(Ordering::SeqCst);
72    println!("  Filter evaluations after building query: {}", evals_after_build);
73    
74    if evals_after_build == 0 {
75        println!("  ✅ Confirmed: Query is lazy! Nothing executed yet.\n");
76    }
77
78    println!("Collecting results (now it executes)...");
79    let results: Vec<_> = lazy_query.collect();
80
81    let evals_after_collect = FILTER_EVALUATIONS.load(Ordering::SeqCst);
82    println!("  Filter evaluations after collecting: {}", evals_after_collect);
83    println!("  Results found: {}", results.len());
84    println!("  ✅ Query executed exactly once, when needed!\n");
85
86    // ============================================================================
87    // DEMO 2: Early Termination - Stops as Soon as Enough Items Found
88    // ============================================================================
89    println!("═══════════════════════════════════════════════════════════════");
90    println!("Demo 2: Early termination with .take()");
91    println!("═══════════════════════════════════════════════════════════════\n");
92
93    EXPENSIVE_OPERATIONS.store(0, Ordering::SeqCst);
94
95    println!("Finding first 5 expensive items from 1000 products...");
96    let first_5: Vec<_> = LazyQuery::new(&products)
97        .where_(Product::price_r(), |p| expensive_check(p))
98        .take_lazy(5)
99        .collect();
100
101    let ops = EXPENSIVE_OPERATIONS.load(Ordering::SeqCst);
102    println!("  Found: {} items", first_5.len());
103    println!("  Expensive operations performed: {}", ops);
104    println!("  Items NOT checked: {} (stopped early!)", 1000 - ops);
105    
106    if ops < 1000 {
107        println!("  ✅ Early termination worked! Didn't check all 1000 items.\n");
108    }
109
110    // ============================================================================
111    // DEMO 3: Iterator Fusion - Rust Optimizes Chained Operations
112    // ============================================================================
113    println!("═══════════════════════════════════════════════════════════════");
114    println!("Demo 3: Iterator fusion - chained operations optimized");
115    println!("═══════════════════════════════════════════════════════════════\n");
116
117    println!("Chaining multiple operations...");
118    let chained_query = LazyQuery::new(&products)
119        .where_(Product::category_r(), |cat| cat == "Electronics")
120        .where_(Product::price_r(), |&price| price > 200.0)
121        .where_(Product::stock_r(), |&stock| stock > 10)
122        .take_lazy(10);
123
124    println!("  Built query with 3 filters + take(10)");
125    println!("  ✅ No execution yet - all operations fused into one iterator\n");
126
127    let results: Vec<_> = chained_query.collect();
128    println!("  Executed: Found {} items", results.len());
129    println!("  ✅ All filters applied in single pass!\n");
130
131    // ============================================================================
132    // DEMO 4: Lazy Projection - Only Extract What You Need
133    // ============================================================================
134    println!("═══════════════════════════════════════════════════════════════");
135    println!("Demo 4: Lazy projection");
136    println!("═══════════════════════════════════════════════════════════════\n");
137
138    println!("Selecting names (lazy)...");
139    let names: Vec<String> = LazyQuery::new(&products)
140        .where_(Product::category_r(), |cat| cat == "Electronics")
141        .select_lazy(Product::name_r())
142        .take(5)  // Only process until we have 5
143        .collect();
144
145    println!("  Selected {} names", names.len());
146    println!("  ✅ Only evaluated until 5 names found!\n");
147
148    // ============================================================================
149    // DEMO 5: Lazy Aggregation - Short-Circuit When Possible
150    // ============================================================================
151    println!("═══════════════════════════════════════════════════════════════");
152    println!("Demo 5: Short-circuit with .any()");
153    println!("═══════════════════════════════════════════════════════════════\n");
154
155    FILTER_EVALUATIONS.store(0, Ordering::SeqCst);
156
157    println!("Checking if ANY electronics exist (1000 items to search)...");
158    let exists = LazyQuery::new(&products)
159        .where_(Product::category_r(), |cat| {
160            FILTER_EVALUATIONS.fetch_add(1, Ordering::SeqCst);
161            cat == "Electronics"
162        })
163        .any();
164
165    let checks = FILTER_EVALUATIONS.load(Ordering::SeqCst);
166    println!("  Result: {}", exists);
167    println!("  Items checked: {} out of 1000", checks);
168    println!("  Items skipped: {} (short-circuited!)", 1000 - checks);
169    
170    if checks < 1000 {
171        println!("  ✅ Short-circuit worked! Stopped as soon as first match found.\n");
172    }
173
174    // ============================================================================
175    // DEMO 6: Lazy Find - Stops at First Match
176    // ============================================================================
177    println!("═══════════════════════════════════════════════════════════════");
178    println!("Demo 6: .find() stops at first match");
179    println!("═══════════════════════════════════════════════════════════════\n");
180
181    FILTER_EVALUATIONS.store(0, Ordering::SeqCst);
182
183    println!("Finding first product with price > 500...");
184    let found = LazyQuery::new(&products)
185        .where_(Product::price_r(), |&price| {
186            FILTER_EVALUATIONS.fetch_add(1, Ordering::SeqCst);
187            price > 500.0
188        })
189        .first();
190
191    let checks = FILTER_EVALUATIONS.load(Ordering::SeqCst);
192    if let Some(product) = found {
193        println!("  Found: {} (${:.2})", product.name, product.price);
194    }
195    println!("  Items checked: {} out of 1000", checks);
196    println!("  ✅ Stopped immediately after finding first match!\n");
197
198    // ============================================================================
199    // DEMO 7: Composition - Build Queries Incrementally
200    // ============================================================================
201    println!("═══════════════════════════════════════════════════════════════");
202    println!("Demo 7: Composable queries");
203    println!("═══════════════════════════════════════════════════════════════\n");
204
205    println!("Building base query...");
206    let base_query = LazyQuery::new(&products)
207        .where_(Product::category_r(), |cat| cat == "Electronics");
208
209    println!("  Created base query (not executed)\n");
210
211    println!("  Adding price filter...");
212    let refined_query = base_query
213        .where_(Product::price_r(), |&price| price > 100.0);
214
215    println!("  Still not executed...\n");
216
217    println!("  Adding stock filter and limiting...");
218    let final_query = refined_query
219        .where_(Product::stock_r(), |&stock| stock > 5)
220        .take_lazy(10);
221
222    println!("  Still not executed...\n");
223
224    println!("  Executing...");
225    let results: Vec<_> = final_query.collect();
226    println!("  ✅ Executed once with all filters: Found {} items\n", results.len());
227
228    // ============================================================================
229    // DEMO 8: For Loop - Natural Iteration
230    // ============================================================================
231    println!("═══════════════════════════════════════════════════════════════");
232    println!("Demo 8: Use in for loops");
233    println!("═══════════════════════════════════════════════════════════════\n");
234
235    println!("Iterating over filtered products...");
236    let mut count = 0;
237    for product in LazyQuery::new(&products)
238        .where_(Product::category_r(), |cat| cat == "Electronics")
239        .take_lazy(3)
240    {
241        println!("  • {}: ${:.2}", product.name, product.price);
242        count += 1;
243    }
244    println!("  ✅ Processed {} items lazily\n", count);
245
246    // ============================================================================
247    // DEMO 9: Performance Comparison
248    // ============================================================================
249    println!("═══════════════════════════════════════════════════════════════");
250    println!("Demo 9: Performance benefit demonstration");
251    println!("═══════════════════════════════════════════════════════════════\n");
252
253    println!("Scenario: Find first expensive item from 1000 products\n");
254
255    EXPENSIVE_OPERATIONS.store(0, Ordering::SeqCst);
256    
257    println!("Without lazy (hypothetical - check all, then take first):");
258    println!("  Would check: 1000 items");
259    println!("  Would find: ~300 matching items");
260    println!("  Would return: 1 item");
261    println!("  Wasted work: 299 items processed unnecessarily\n");
262
263    EXPENSIVE_OPERATIONS.store(0, Ordering::SeqCst);
264    
265    println!("With lazy evaluation:");
266    let _first = LazyQuery::new(&products)
267        .where_(Product::price_r(), |p| expensive_check(p))
268        .first();
269
270    let ops = EXPENSIVE_OPERATIONS.load(Ordering::SeqCst);
271    println!("  Checked: {} items", ops);
272    println!("  Found: 1 item");
273    println!("  Wasted work: 0 items");
274    println!("  ✅ Efficiency gain: {}x faster!", 1000 / ops.max(1));
275
276    // ============================================================================
277    // Summary
278    // ============================================================================
279    println!("\n╔════════════════════════════════════════════════════════════════╗");
280    println!("║  Lazy Evaluation Benefits                                     ║");
281    println!("╚════════════════════════════════════════════════════════════════╝\n");
282
283    println!("✅ Deferred Execution:");
284    println!("   • No work until results needed");
285    println!("   • Can build complex queries without performance cost\n");
286
287    println!("✅ Early Termination:");
288    println!("   • .take(n) stops after n items");
289    println!("   • .first() stops after 1 item");
290    println!("   • .any() stops after first match");
291    println!("   • Massive performance win for large datasets\n");
292
293    println!("✅ Iterator Fusion:");
294    println!("   • Multiple filters combined into one pass");
295    println!("   • Rust compiler optimizes chained operations");
296    println!("   • No intermediate allocations\n");
297
298    println!("✅ Composable:");
299    println!("   • Build queries incrementally");
300    println!("   • Reuse query fragments");
301    println!("   • Clean separation of query building vs execution\n");
302
303    println!("✅ Zero Overhead:");
304    println!("   • Compiles to same code as manual loops");
305    println!("   • No runtime cost for abstraction");
306    println!("   • Pay only for what you use\n");
307
308    println!("✓ Lazy evaluation demo complete!\n");
309}
Source

pub fn map_items<F, O>(self, f: F) -> impl Iterator<Item = O> + 'a
where F: Fn(&'a T) -> O + 'a, I: 'a,

Maps each item through a transformation (lazy).

§Example
let prices = LazyQuery::new(&products)
    .map_items(|p| p.price)
    .collect::<Vec<_>>();
Source

pub fn select_lazy<F>( self, path: KeyPaths<T, F>, ) -> impl Iterator<Item = F> + 'a
where F: Clone + 'static, I: 'a,

Selects/projects a field value (lazy).

Returns iterator over cloned field values.

§Example
let names: Vec<String> = LazyQuery::new(&products)
    .select_lazy(Product::name_r())
    .collect();
Examples found in repository?
examples/lazy_evaluation.rs (line 141)
47fn main() {
48    println!("\n╔════════════════════════════════════════════════════════════════╗");
49    println!("║  Lazy Query Evaluation Demo                                   ║");
50    println!("╚════════════════════════════════════════════════════════════════╝\n");
51
52    let products = create_products();
53    println!("Created {} products\n", products.len());
54
55    // ============================================================================
56    // DEMO 1: Lazy Execution - Nothing Happens Until .collect()
57    // ============================================================================
58    println!("═══════════════════════════════════════════════════════════════");
59    println!("Demo 1: Lazy execution - deferred until needed");
60    println!("═══════════════════════════════════════════════════════════════\n");
61
62    FILTER_EVALUATIONS.store(0, Ordering::SeqCst);
63
64    println!("Building query (should execute nothing)...");
65    let lazy_query = LazyQuery::new(&products)
66        .where_(Product::category_r(), |cat| {
67            FILTER_EVALUATIONS.fetch_add(1, Ordering::SeqCst);
68            cat == "Electronics"
69        });
70
71    let evals_after_build = FILTER_EVALUATIONS.load(Ordering::SeqCst);
72    println!("  Filter evaluations after building query: {}", evals_after_build);
73    
74    if evals_after_build == 0 {
75        println!("  ✅ Confirmed: Query is lazy! Nothing executed yet.\n");
76    }
77
78    println!("Collecting results (now it executes)...");
79    let results: Vec<_> = lazy_query.collect();
80
81    let evals_after_collect = FILTER_EVALUATIONS.load(Ordering::SeqCst);
82    println!("  Filter evaluations after collecting: {}", evals_after_collect);
83    println!("  Results found: {}", results.len());
84    println!("  ✅ Query executed exactly once, when needed!\n");
85
86    // ============================================================================
87    // DEMO 2: Early Termination - Stops as Soon as Enough Items Found
88    // ============================================================================
89    println!("═══════════════════════════════════════════════════════════════");
90    println!("Demo 2: Early termination with .take()");
91    println!("═══════════════════════════════════════════════════════════════\n");
92
93    EXPENSIVE_OPERATIONS.store(0, Ordering::SeqCst);
94
95    println!("Finding first 5 expensive items from 1000 products...");
96    let first_5: Vec<_> = LazyQuery::new(&products)
97        .where_(Product::price_r(), |p| expensive_check(p))
98        .take_lazy(5)
99        .collect();
100
101    let ops = EXPENSIVE_OPERATIONS.load(Ordering::SeqCst);
102    println!("  Found: {} items", first_5.len());
103    println!("  Expensive operations performed: {}", ops);
104    println!("  Items NOT checked: {} (stopped early!)", 1000 - ops);
105    
106    if ops < 1000 {
107        println!("  ✅ Early termination worked! Didn't check all 1000 items.\n");
108    }
109
110    // ============================================================================
111    // DEMO 3: Iterator Fusion - Rust Optimizes Chained Operations
112    // ============================================================================
113    println!("═══════════════════════════════════════════════════════════════");
114    println!("Demo 3: Iterator fusion - chained operations optimized");
115    println!("═══════════════════════════════════════════════════════════════\n");
116
117    println!("Chaining multiple operations...");
118    let chained_query = LazyQuery::new(&products)
119        .where_(Product::category_r(), |cat| cat == "Electronics")
120        .where_(Product::price_r(), |&price| price > 200.0)
121        .where_(Product::stock_r(), |&stock| stock > 10)
122        .take_lazy(10);
123
124    println!("  Built query with 3 filters + take(10)");
125    println!("  ✅ No execution yet - all operations fused into one iterator\n");
126
127    let results: Vec<_> = chained_query.collect();
128    println!("  Executed: Found {} items", results.len());
129    println!("  ✅ All filters applied in single pass!\n");
130
131    // ============================================================================
132    // DEMO 4: Lazy Projection - Only Extract What You Need
133    // ============================================================================
134    println!("═══════════════════════════════════════════════════════════════");
135    println!("Demo 4: Lazy projection");
136    println!("═══════════════════════════════════════════════════════════════\n");
137
138    println!("Selecting names (lazy)...");
139    let names: Vec<String> = LazyQuery::new(&products)
140        .where_(Product::category_r(), |cat| cat == "Electronics")
141        .select_lazy(Product::name_r())
142        .take(5)  // Only process until we have 5
143        .collect();
144
145    println!("  Selected {} names", names.len());
146    println!("  ✅ Only evaluated until 5 names found!\n");
147
148    // ============================================================================
149    // DEMO 5: Lazy Aggregation - Short-Circuit When Possible
150    // ============================================================================
151    println!("═══════════════════════════════════════════════════════════════");
152    println!("Demo 5: Short-circuit with .any()");
153    println!("═══════════════════════════════════════════════════════════════\n");
154
155    FILTER_EVALUATIONS.store(0, Ordering::SeqCst);
156
157    println!("Checking if ANY electronics exist (1000 items to search)...");
158    let exists = LazyQuery::new(&products)
159        .where_(Product::category_r(), |cat| {
160            FILTER_EVALUATIONS.fetch_add(1, Ordering::SeqCst);
161            cat == "Electronics"
162        })
163        .any();
164
165    let checks = FILTER_EVALUATIONS.load(Ordering::SeqCst);
166    println!("  Result: {}", exists);
167    println!("  Items checked: {} out of 1000", checks);
168    println!("  Items skipped: {} (short-circuited!)", 1000 - checks);
169    
170    if checks < 1000 {
171        println!("  ✅ Short-circuit worked! Stopped as soon as first match found.\n");
172    }
173
174    // ============================================================================
175    // DEMO 6: Lazy Find - Stops at First Match
176    // ============================================================================
177    println!("═══════════════════════════════════════════════════════════════");
178    println!("Demo 6: .find() stops at first match");
179    println!("═══════════════════════════════════════════════════════════════\n");
180
181    FILTER_EVALUATIONS.store(0, Ordering::SeqCst);
182
183    println!("Finding first product with price > 500...");
184    let found = LazyQuery::new(&products)
185        .where_(Product::price_r(), |&price| {
186            FILTER_EVALUATIONS.fetch_add(1, Ordering::SeqCst);
187            price > 500.0
188        })
189        .first();
190
191    let checks = FILTER_EVALUATIONS.load(Ordering::SeqCst);
192    if let Some(product) = found {
193        println!("  Found: {} (${:.2})", product.name, product.price);
194    }
195    println!("  Items checked: {} out of 1000", checks);
196    println!("  ✅ Stopped immediately after finding first match!\n");
197
198    // ============================================================================
199    // DEMO 7: Composition - Build Queries Incrementally
200    // ============================================================================
201    println!("═══════════════════════════════════════════════════════════════");
202    println!("Demo 7: Composable queries");
203    println!("═══════════════════════════════════════════════════════════════\n");
204
205    println!("Building base query...");
206    let base_query = LazyQuery::new(&products)
207        .where_(Product::category_r(), |cat| cat == "Electronics");
208
209    println!("  Created base query (not executed)\n");
210
211    println!("  Adding price filter...");
212    let refined_query = base_query
213        .where_(Product::price_r(), |&price| price > 100.0);
214
215    println!("  Still not executed...\n");
216
217    println!("  Adding stock filter and limiting...");
218    let final_query = refined_query
219        .where_(Product::stock_r(), |&stock| stock > 5)
220        .take_lazy(10);
221
222    println!("  Still not executed...\n");
223
224    println!("  Executing...");
225    let results: Vec<_> = final_query.collect();
226    println!("  ✅ Executed once with all filters: Found {} items\n", results.len());
227
228    // ============================================================================
229    // DEMO 8: For Loop - Natural Iteration
230    // ============================================================================
231    println!("═══════════════════════════════════════════════════════════════");
232    println!("Demo 8: Use in for loops");
233    println!("═══════════════════════════════════════════════════════════════\n");
234
235    println!("Iterating over filtered products...");
236    let mut count = 0;
237    for product in LazyQuery::new(&products)
238        .where_(Product::category_r(), |cat| cat == "Electronics")
239        .take_lazy(3)
240    {
241        println!("  • {}: ${:.2}", product.name, product.price);
242        count += 1;
243    }
244    println!("  ✅ Processed {} items lazily\n", count);
245
246    // ============================================================================
247    // DEMO 9: Performance Comparison
248    // ============================================================================
249    println!("═══════════════════════════════════════════════════════════════");
250    println!("Demo 9: Performance benefit demonstration");
251    println!("═══════════════════════════════════════════════════════════════\n");
252
253    println!("Scenario: Find first expensive item from 1000 products\n");
254
255    EXPENSIVE_OPERATIONS.store(0, Ordering::SeqCst);
256    
257    println!("Without lazy (hypothetical - check all, then take first):");
258    println!("  Would check: 1000 items");
259    println!("  Would find: ~300 matching items");
260    println!("  Would return: 1 item");
261    println!("  Wasted work: 299 items processed unnecessarily\n");
262
263    EXPENSIVE_OPERATIONS.store(0, Ordering::SeqCst);
264    
265    println!("With lazy evaluation:");
266    let _first = LazyQuery::new(&products)
267        .where_(Product::price_r(), |p| expensive_check(p))
268        .first();
269
270    let ops = EXPENSIVE_OPERATIONS.load(Ordering::SeqCst);
271    println!("  Checked: {} items", ops);
272    println!("  Found: 1 item");
273    println!("  Wasted work: 0 items");
274    println!("  ✅ Efficiency gain: {}x faster!", 1000 / ops.max(1));
275
276    // ============================================================================
277    // Summary
278    // ============================================================================
279    println!("\n╔════════════════════════════════════════════════════════════════╗");
280    println!("║  Lazy Evaluation Benefits                                     ║");
281    println!("╚════════════════════════════════════════════════════════════════╝\n");
282
283    println!("✅ Deferred Execution:");
284    println!("   • No work until results needed");
285    println!("   • Can build complex queries without performance cost\n");
286
287    println!("✅ Early Termination:");
288    println!("   • .take(n) stops after n items");
289    println!("   • .first() stops after 1 item");
290    println!("   • .any() stops after first match");
291    println!("   • Massive performance win for large datasets\n");
292
293    println!("✅ Iterator Fusion:");
294    println!("   • Multiple filters combined into one pass");
295    println!("   • Rust compiler optimizes chained operations");
296    println!("   • No intermediate allocations\n");
297
298    println!("✅ Composable:");
299    println!("   • Build queries incrementally");
300    println!("   • Reuse query fragments");
301    println!("   • Clean separation of query building vs execution\n");
302
303    println!("✅ Zero Overhead:");
304    println!("   • Compiles to same code as manual loops");
305    println!("   • No runtime cost for abstraction");
306    println!("   • Pay only for what you use\n");
307
308    println!("✓ Lazy evaluation demo complete!\n");
309}
Source

pub fn take_lazy( self, n: usize, ) -> LazyQuery<'a, T, impl Iterator<Item = &'a T> + 'a>
where I: 'a,

Takes at most n items (lazy).

§Example
let first_10: Vec<_> = LazyQuery::new(&products)
    .take_lazy(10)
    .collect();
Examples found in repository?
examples/lazy_evaluation.rs (line 98)
47fn main() {
48    println!("\n╔════════════════════════════════════════════════════════════════╗");
49    println!("║  Lazy Query Evaluation Demo                                   ║");
50    println!("╚════════════════════════════════════════════════════════════════╝\n");
51
52    let products = create_products();
53    println!("Created {} products\n", products.len());
54
55    // ============================================================================
56    // DEMO 1: Lazy Execution - Nothing Happens Until .collect()
57    // ============================================================================
58    println!("═══════════════════════════════════════════════════════════════");
59    println!("Demo 1: Lazy execution - deferred until needed");
60    println!("═══════════════════════════════════════════════════════════════\n");
61
62    FILTER_EVALUATIONS.store(0, Ordering::SeqCst);
63
64    println!("Building query (should execute nothing)...");
65    let lazy_query = LazyQuery::new(&products)
66        .where_(Product::category_r(), |cat| {
67            FILTER_EVALUATIONS.fetch_add(1, Ordering::SeqCst);
68            cat == "Electronics"
69        });
70
71    let evals_after_build = FILTER_EVALUATIONS.load(Ordering::SeqCst);
72    println!("  Filter evaluations after building query: {}", evals_after_build);
73    
74    if evals_after_build == 0 {
75        println!("  ✅ Confirmed: Query is lazy! Nothing executed yet.\n");
76    }
77
78    println!("Collecting results (now it executes)...");
79    let results: Vec<_> = lazy_query.collect();
80
81    let evals_after_collect = FILTER_EVALUATIONS.load(Ordering::SeqCst);
82    println!("  Filter evaluations after collecting: {}", evals_after_collect);
83    println!("  Results found: {}", results.len());
84    println!("  ✅ Query executed exactly once, when needed!\n");
85
86    // ============================================================================
87    // DEMO 2: Early Termination - Stops as Soon as Enough Items Found
88    // ============================================================================
89    println!("═══════════════════════════════════════════════════════════════");
90    println!("Demo 2: Early termination with .take()");
91    println!("═══════════════════════════════════════════════════════════════\n");
92
93    EXPENSIVE_OPERATIONS.store(0, Ordering::SeqCst);
94
95    println!("Finding first 5 expensive items from 1000 products...");
96    let first_5: Vec<_> = LazyQuery::new(&products)
97        .where_(Product::price_r(), |p| expensive_check(p))
98        .take_lazy(5)
99        .collect();
100
101    let ops = EXPENSIVE_OPERATIONS.load(Ordering::SeqCst);
102    println!("  Found: {} items", first_5.len());
103    println!("  Expensive operations performed: {}", ops);
104    println!("  Items NOT checked: {} (stopped early!)", 1000 - ops);
105    
106    if ops < 1000 {
107        println!("  ✅ Early termination worked! Didn't check all 1000 items.\n");
108    }
109
110    // ============================================================================
111    // DEMO 3: Iterator Fusion - Rust Optimizes Chained Operations
112    // ============================================================================
113    println!("═══════════════════════════════════════════════════════════════");
114    println!("Demo 3: Iterator fusion - chained operations optimized");
115    println!("═══════════════════════════════════════════════════════════════\n");
116
117    println!("Chaining multiple operations...");
118    let chained_query = LazyQuery::new(&products)
119        .where_(Product::category_r(), |cat| cat == "Electronics")
120        .where_(Product::price_r(), |&price| price > 200.0)
121        .where_(Product::stock_r(), |&stock| stock > 10)
122        .take_lazy(10);
123
124    println!("  Built query with 3 filters + take(10)");
125    println!("  ✅ No execution yet - all operations fused into one iterator\n");
126
127    let results: Vec<_> = chained_query.collect();
128    println!("  Executed: Found {} items", results.len());
129    println!("  ✅ All filters applied in single pass!\n");
130
131    // ============================================================================
132    // DEMO 4: Lazy Projection - Only Extract What You Need
133    // ============================================================================
134    println!("═══════════════════════════════════════════════════════════════");
135    println!("Demo 4: Lazy projection");
136    println!("═══════════════════════════════════════════════════════════════\n");
137
138    println!("Selecting names (lazy)...");
139    let names: Vec<String> = LazyQuery::new(&products)
140        .where_(Product::category_r(), |cat| cat == "Electronics")
141        .select_lazy(Product::name_r())
142        .take(5)  // Only process until we have 5
143        .collect();
144
145    println!("  Selected {} names", names.len());
146    println!("  ✅ Only evaluated until 5 names found!\n");
147
148    // ============================================================================
149    // DEMO 5: Lazy Aggregation - Short-Circuit When Possible
150    // ============================================================================
151    println!("═══════════════════════════════════════════════════════════════");
152    println!("Demo 5: Short-circuit with .any()");
153    println!("═══════════════════════════════════════════════════════════════\n");
154
155    FILTER_EVALUATIONS.store(0, Ordering::SeqCst);
156
157    println!("Checking if ANY electronics exist (1000 items to search)...");
158    let exists = LazyQuery::new(&products)
159        .where_(Product::category_r(), |cat| {
160            FILTER_EVALUATIONS.fetch_add(1, Ordering::SeqCst);
161            cat == "Electronics"
162        })
163        .any();
164
165    let checks = FILTER_EVALUATIONS.load(Ordering::SeqCst);
166    println!("  Result: {}", exists);
167    println!("  Items checked: {} out of 1000", checks);
168    println!("  Items skipped: {} (short-circuited!)", 1000 - checks);
169    
170    if checks < 1000 {
171        println!("  ✅ Short-circuit worked! Stopped as soon as first match found.\n");
172    }
173
174    // ============================================================================
175    // DEMO 6: Lazy Find - Stops at First Match
176    // ============================================================================
177    println!("═══════════════════════════════════════════════════════════════");
178    println!("Demo 6: .find() stops at first match");
179    println!("═══════════════════════════════════════════════════════════════\n");
180
181    FILTER_EVALUATIONS.store(0, Ordering::SeqCst);
182
183    println!("Finding first product with price > 500...");
184    let found = LazyQuery::new(&products)
185        .where_(Product::price_r(), |&price| {
186            FILTER_EVALUATIONS.fetch_add(1, Ordering::SeqCst);
187            price > 500.0
188        })
189        .first();
190
191    let checks = FILTER_EVALUATIONS.load(Ordering::SeqCst);
192    if let Some(product) = found {
193        println!("  Found: {} (${:.2})", product.name, product.price);
194    }
195    println!("  Items checked: {} out of 1000", checks);
196    println!("  ✅ Stopped immediately after finding first match!\n");
197
198    // ============================================================================
199    // DEMO 7: Composition - Build Queries Incrementally
200    // ============================================================================
201    println!("═══════════════════════════════════════════════════════════════");
202    println!("Demo 7: Composable queries");
203    println!("═══════════════════════════════════════════════════════════════\n");
204
205    println!("Building base query...");
206    let base_query = LazyQuery::new(&products)
207        .where_(Product::category_r(), |cat| cat == "Electronics");
208
209    println!("  Created base query (not executed)\n");
210
211    println!("  Adding price filter...");
212    let refined_query = base_query
213        .where_(Product::price_r(), |&price| price > 100.0);
214
215    println!("  Still not executed...\n");
216
217    println!("  Adding stock filter and limiting...");
218    let final_query = refined_query
219        .where_(Product::stock_r(), |&stock| stock > 5)
220        .take_lazy(10);
221
222    println!("  Still not executed...\n");
223
224    println!("  Executing...");
225    let results: Vec<_> = final_query.collect();
226    println!("  ✅ Executed once with all filters: Found {} items\n", results.len());
227
228    // ============================================================================
229    // DEMO 8: For Loop - Natural Iteration
230    // ============================================================================
231    println!("═══════════════════════════════════════════════════════════════");
232    println!("Demo 8: Use in for loops");
233    println!("═══════════════════════════════════════════════════════════════\n");
234
235    println!("Iterating over filtered products...");
236    let mut count = 0;
237    for product in LazyQuery::new(&products)
238        .where_(Product::category_r(), |cat| cat == "Electronics")
239        .take_lazy(3)
240    {
241        println!("  • {}: ${:.2}", product.name, product.price);
242        count += 1;
243    }
244    println!("  ✅ Processed {} items lazily\n", count);
245
246    // ============================================================================
247    // DEMO 9: Performance Comparison
248    // ============================================================================
249    println!("═══════════════════════════════════════════════════════════════");
250    println!("Demo 9: Performance benefit demonstration");
251    println!("═══════════════════════════════════════════════════════════════\n");
252
253    println!("Scenario: Find first expensive item from 1000 products\n");
254
255    EXPENSIVE_OPERATIONS.store(0, Ordering::SeqCst);
256    
257    println!("Without lazy (hypothetical - check all, then take first):");
258    println!("  Would check: 1000 items");
259    println!("  Would find: ~300 matching items");
260    println!("  Would return: 1 item");
261    println!("  Wasted work: 299 items processed unnecessarily\n");
262
263    EXPENSIVE_OPERATIONS.store(0, Ordering::SeqCst);
264    
265    println!("With lazy evaluation:");
266    let _first = LazyQuery::new(&products)
267        .where_(Product::price_r(), |p| expensive_check(p))
268        .first();
269
270    let ops = EXPENSIVE_OPERATIONS.load(Ordering::SeqCst);
271    println!("  Checked: {} items", ops);
272    println!("  Found: 1 item");
273    println!("  Wasted work: 0 items");
274    println!("  ✅ Efficiency gain: {}x faster!", 1000 / ops.max(1));
275
276    // ============================================================================
277    // Summary
278    // ============================================================================
279    println!("\n╔════════════════════════════════════════════════════════════════╗");
280    println!("║  Lazy Evaluation Benefits                                     ║");
281    println!("╚════════════════════════════════════════════════════════════════╝\n");
282
283    println!("✅ Deferred Execution:");
284    println!("   • No work until results needed");
285    println!("   • Can build complex queries without performance cost\n");
286
287    println!("✅ Early Termination:");
288    println!("   • .take(n) stops after n items");
289    println!("   • .first() stops after 1 item");
290    println!("   • .any() stops after first match");
291    println!("   • Massive performance win for large datasets\n");
292
293    println!("✅ Iterator Fusion:");
294    println!("   • Multiple filters combined into one pass");
295    println!("   • Rust compiler optimizes chained operations");
296    println!("   • No intermediate allocations\n");
297
298    println!("✅ Composable:");
299    println!("   • Build queries incrementally");
300    println!("   • Reuse query fragments");
301    println!("   • Clean separation of query building vs execution\n");
302
303    println!("✅ Zero Overhead:");
304    println!("   • Compiles to same code as manual loops");
305    println!("   • No runtime cost for abstraction");
306    println!("   • Pay only for what you use\n");
307
308    println!("✓ Lazy evaluation demo complete!\n");
309}
Source

pub fn skip_lazy( self, n: usize, ) -> LazyQuery<'a, T, impl Iterator<Item = &'a T> + 'a>
where I: 'a,

Skips n items (lazy).

§Example
let page_2: Vec<_> = LazyQuery::new(&products)
    .skip_lazy(10)
    .take_lazy(10)
    .collect();
Source

pub fn collect(self) -> Vec<&'a T>

Collects all items into a vector (terminal operation - executes query).

§Example
let results: Vec<&Product> = query.collect();
Examples found in repository?
examples/lazy_evaluation.rs (line 79)
47fn main() {
48    println!("\n╔════════════════════════════════════════════════════════════════╗");
49    println!("║  Lazy Query Evaluation Demo                                   ║");
50    println!("╚════════════════════════════════════════════════════════════════╝\n");
51
52    let products = create_products();
53    println!("Created {} products\n", products.len());
54
55    // ============================================================================
56    // DEMO 1: Lazy Execution - Nothing Happens Until .collect()
57    // ============================================================================
58    println!("═══════════════════════════════════════════════════════════════");
59    println!("Demo 1: Lazy execution - deferred until needed");
60    println!("═══════════════════════════════════════════════════════════════\n");
61
62    FILTER_EVALUATIONS.store(0, Ordering::SeqCst);
63
64    println!("Building query (should execute nothing)...");
65    let lazy_query = LazyQuery::new(&products)
66        .where_(Product::category_r(), |cat| {
67            FILTER_EVALUATIONS.fetch_add(1, Ordering::SeqCst);
68            cat == "Electronics"
69        });
70
71    let evals_after_build = FILTER_EVALUATIONS.load(Ordering::SeqCst);
72    println!("  Filter evaluations after building query: {}", evals_after_build);
73    
74    if evals_after_build == 0 {
75        println!("  ✅ Confirmed: Query is lazy! Nothing executed yet.\n");
76    }
77
78    println!("Collecting results (now it executes)...");
79    let results: Vec<_> = lazy_query.collect();
80
81    let evals_after_collect = FILTER_EVALUATIONS.load(Ordering::SeqCst);
82    println!("  Filter evaluations after collecting: {}", evals_after_collect);
83    println!("  Results found: {}", results.len());
84    println!("  ✅ Query executed exactly once, when needed!\n");
85
86    // ============================================================================
87    // DEMO 2: Early Termination - Stops as Soon as Enough Items Found
88    // ============================================================================
89    println!("═══════════════════════════════════════════════════════════════");
90    println!("Demo 2: Early termination with .take()");
91    println!("═══════════════════════════════════════════════════════════════\n");
92
93    EXPENSIVE_OPERATIONS.store(0, Ordering::SeqCst);
94
95    println!("Finding first 5 expensive items from 1000 products...");
96    let first_5: Vec<_> = LazyQuery::new(&products)
97        .where_(Product::price_r(), |p| expensive_check(p))
98        .take_lazy(5)
99        .collect();
100
101    let ops = EXPENSIVE_OPERATIONS.load(Ordering::SeqCst);
102    println!("  Found: {} items", first_5.len());
103    println!("  Expensive operations performed: {}", ops);
104    println!("  Items NOT checked: {} (stopped early!)", 1000 - ops);
105    
106    if ops < 1000 {
107        println!("  ✅ Early termination worked! Didn't check all 1000 items.\n");
108    }
109
110    // ============================================================================
111    // DEMO 3: Iterator Fusion - Rust Optimizes Chained Operations
112    // ============================================================================
113    println!("═══════════════════════════════════════════════════════════════");
114    println!("Demo 3: Iterator fusion - chained operations optimized");
115    println!("═══════════════════════════════════════════════════════════════\n");
116
117    println!("Chaining multiple operations...");
118    let chained_query = LazyQuery::new(&products)
119        .where_(Product::category_r(), |cat| cat == "Electronics")
120        .where_(Product::price_r(), |&price| price > 200.0)
121        .where_(Product::stock_r(), |&stock| stock > 10)
122        .take_lazy(10);
123
124    println!("  Built query with 3 filters + take(10)");
125    println!("  ✅ No execution yet - all operations fused into one iterator\n");
126
127    let results: Vec<_> = chained_query.collect();
128    println!("  Executed: Found {} items", results.len());
129    println!("  ✅ All filters applied in single pass!\n");
130
131    // ============================================================================
132    // DEMO 4: Lazy Projection - Only Extract What You Need
133    // ============================================================================
134    println!("═══════════════════════════════════════════════════════════════");
135    println!("Demo 4: Lazy projection");
136    println!("═══════════════════════════════════════════════════════════════\n");
137
138    println!("Selecting names (lazy)...");
139    let names: Vec<String> = LazyQuery::new(&products)
140        .where_(Product::category_r(), |cat| cat == "Electronics")
141        .select_lazy(Product::name_r())
142        .take(5)  // Only process until we have 5
143        .collect();
144
145    println!("  Selected {} names", names.len());
146    println!("  ✅ Only evaluated until 5 names found!\n");
147
148    // ============================================================================
149    // DEMO 5: Lazy Aggregation - Short-Circuit When Possible
150    // ============================================================================
151    println!("═══════════════════════════════════════════════════════════════");
152    println!("Demo 5: Short-circuit with .any()");
153    println!("═══════════════════════════════════════════════════════════════\n");
154
155    FILTER_EVALUATIONS.store(0, Ordering::SeqCst);
156
157    println!("Checking if ANY electronics exist (1000 items to search)...");
158    let exists = LazyQuery::new(&products)
159        .where_(Product::category_r(), |cat| {
160            FILTER_EVALUATIONS.fetch_add(1, Ordering::SeqCst);
161            cat == "Electronics"
162        })
163        .any();
164
165    let checks = FILTER_EVALUATIONS.load(Ordering::SeqCst);
166    println!("  Result: {}", exists);
167    println!("  Items checked: {} out of 1000", checks);
168    println!("  Items skipped: {} (short-circuited!)", 1000 - checks);
169    
170    if checks < 1000 {
171        println!("  ✅ Short-circuit worked! Stopped as soon as first match found.\n");
172    }
173
174    // ============================================================================
175    // DEMO 6: Lazy Find - Stops at First Match
176    // ============================================================================
177    println!("═══════════════════════════════════════════════════════════════");
178    println!("Demo 6: .find() stops at first match");
179    println!("═══════════════════════════════════════════════════════════════\n");
180
181    FILTER_EVALUATIONS.store(0, Ordering::SeqCst);
182
183    println!("Finding first product with price > 500...");
184    let found = LazyQuery::new(&products)
185        .where_(Product::price_r(), |&price| {
186            FILTER_EVALUATIONS.fetch_add(1, Ordering::SeqCst);
187            price > 500.0
188        })
189        .first();
190
191    let checks = FILTER_EVALUATIONS.load(Ordering::SeqCst);
192    if let Some(product) = found {
193        println!("  Found: {} (${:.2})", product.name, product.price);
194    }
195    println!("  Items checked: {} out of 1000", checks);
196    println!("  ✅ Stopped immediately after finding first match!\n");
197
198    // ============================================================================
199    // DEMO 7: Composition - Build Queries Incrementally
200    // ============================================================================
201    println!("═══════════════════════════════════════════════════════════════");
202    println!("Demo 7: Composable queries");
203    println!("═══════════════════════════════════════════════════════════════\n");
204
205    println!("Building base query...");
206    let base_query = LazyQuery::new(&products)
207        .where_(Product::category_r(), |cat| cat == "Electronics");
208
209    println!("  Created base query (not executed)\n");
210
211    println!("  Adding price filter...");
212    let refined_query = base_query
213        .where_(Product::price_r(), |&price| price > 100.0);
214
215    println!("  Still not executed...\n");
216
217    println!("  Adding stock filter and limiting...");
218    let final_query = refined_query
219        .where_(Product::stock_r(), |&stock| stock > 5)
220        .take_lazy(10);
221
222    println!("  Still not executed...\n");
223
224    println!("  Executing...");
225    let results: Vec<_> = final_query.collect();
226    println!("  ✅ Executed once with all filters: Found {} items\n", results.len());
227
228    // ============================================================================
229    // DEMO 8: For Loop - Natural Iteration
230    // ============================================================================
231    println!("═══════════════════════════════════════════════════════════════");
232    println!("Demo 8: Use in for loops");
233    println!("═══════════════════════════════════════════════════════════════\n");
234
235    println!("Iterating over filtered products...");
236    let mut count = 0;
237    for product in LazyQuery::new(&products)
238        .where_(Product::category_r(), |cat| cat == "Electronics")
239        .take_lazy(3)
240    {
241        println!("  • {}: ${:.2}", product.name, product.price);
242        count += 1;
243    }
244    println!("  ✅ Processed {} items lazily\n", count);
245
246    // ============================================================================
247    // DEMO 9: Performance Comparison
248    // ============================================================================
249    println!("═══════════════════════════════════════════════════════════════");
250    println!("Demo 9: Performance benefit demonstration");
251    println!("═══════════════════════════════════════════════════════════════\n");
252
253    println!("Scenario: Find first expensive item from 1000 products\n");
254
255    EXPENSIVE_OPERATIONS.store(0, Ordering::SeqCst);
256    
257    println!("Without lazy (hypothetical - check all, then take first):");
258    println!("  Would check: 1000 items");
259    println!("  Would find: ~300 matching items");
260    println!("  Would return: 1 item");
261    println!("  Wasted work: 299 items processed unnecessarily\n");
262
263    EXPENSIVE_OPERATIONS.store(0, Ordering::SeqCst);
264    
265    println!("With lazy evaluation:");
266    let _first = LazyQuery::new(&products)
267        .where_(Product::price_r(), |p| expensive_check(p))
268        .first();
269
270    let ops = EXPENSIVE_OPERATIONS.load(Ordering::SeqCst);
271    println!("  Checked: {} items", ops);
272    println!("  Found: 1 item");
273    println!("  Wasted work: 0 items");
274    println!("  ✅ Efficiency gain: {}x faster!", 1000 / ops.max(1));
275
276    // ============================================================================
277    // Summary
278    // ============================================================================
279    println!("\n╔════════════════════════════════════════════════════════════════╗");
280    println!("║  Lazy Evaluation Benefits                                     ║");
281    println!("╚════════════════════════════════════════════════════════════════╝\n");
282
283    println!("✅ Deferred Execution:");
284    println!("   • No work until results needed");
285    println!("   • Can build complex queries without performance cost\n");
286
287    println!("✅ Early Termination:");
288    println!("   • .take(n) stops after n items");
289    println!("   • .first() stops after 1 item");
290    println!("   • .any() stops after first match");
291    println!("   • Massive performance win for large datasets\n");
292
293    println!("✅ Iterator Fusion:");
294    println!("   • Multiple filters combined into one pass");
295    println!("   • Rust compiler optimizes chained operations");
296    println!("   • No intermediate allocations\n");
297
298    println!("✅ Composable:");
299    println!("   • Build queries incrementally");
300    println!("   • Reuse query fragments");
301    println!("   • Clean separation of query building vs execution\n");
302
303    println!("✅ Zero Overhead:");
304    println!("   • Compiles to same code as manual loops");
305    println!("   • No runtime cost for abstraction");
306    println!("   • Pay only for what you use\n");
307
308    println!("✓ Lazy evaluation demo complete!\n");
309}
Source

pub fn first(self) -> Option<&'a T>

Gets the first item (terminal operation - executes until first match).

§Example
let first = query.first();
Examples found in repository?
examples/lazy_evaluation.rs (line 189)
47fn main() {
48    println!("\n╔════════════════════════════════════════════════════════════════╗");
49    println!("║  Lazy Query Evaluation Demo                                   ║");
50    println!("╚════════════════════════════════════════════════════════════════╝\n");
51
52    let products = create_products();
53    println!("Created {} products\n", products.len());
54
55    // ============================================================================
56    // DEMO 1: Lazy Execution - Nothing Happens Until .collect()
57    // ============================================================================
58    println!("═══════════════════════════════════════════════════════════════");
59    println!("Demo 1: Lazy execution - deferred until needed");
60    println!("═══════════════════════════════════════════════════════════════\n");
61
62    FILTER_EVALUATIONS.store(0, Ordering::SeqCst);
63
64    println!("Building query (should execute nothing)...");
65    let lazy_query = LazyQuery::new(&products)
66        .where_(Product::category_r(), |cat| {
67            FILTER_EVALUATIONS.fetch_add(1, Ordering::SeqCst);
68            cat == "Electronics"
69        });
70
71    let evals_after_build = FILTER_EVALUATIONS.load(Ordering::SeqCst);
72    println!("  Filter evaluations after building query: {}", evals_after_build);
73    
74    if evals_after_build == 0 {
75        println!("  ✅ Confirmed: Query is lazy! Nothing executed yet.\n");
76    }
77
78    println!("Collecting results (now it executes)...");
79    let results: Vec<_> = lazy_query.collect();
80
81    let evals_after_collect = FILTER_EVALUATIONS.load(Ordering::SeqCst);
82    println!("  Filter evaluations after collecting: {}", evals_after_collect);
83    println!("  Results found: {}", results.len());
84    println!("  ✅ Query executed exactly once, when needed!\n");
85
86    // ============================================================================
87    // DEMO 2: Early Termination - Stops as Soon as Enough Items Found
88    // ============================================================================
89    println!("═══════════════════════════════════════════════════════════════");
90    println!("Demo 2: Early termination with .take()");
91    println!("═══════════════════════════════════════════════════════════════\n");
92
93    EXPENSIVE_OPERATIONS.store(0, Ordering::SeqCst);
94
95    println!("Finding first 5 expensive items from 1000 products...");
96    let first_5: Vec<_> = LazyQuery::new(&products)
97        .where_(Product::price_r(), |p| expensive_check(p))
98        .take_lazy(5)
99        .collect();
100
101    let ops = EXPENSIVE_OPERATIONS.load(Ordering::SeqCst);
102    println!("  Found: {} items", first_5.len());
103    println!("  Expensive operations performed: {}", ops);
104    println!("  Items NOT checked: {} (stopped early!)", 1000 - ops);
105    
106    if ops < 1000 {
107        println!("  ✅ Early termination worked! Didn't check all 1000 items.\n");
108    }
109
110    // ============================================================================
111    // DEMO 3: Iterator Fusion - Rust Optimizes Chained Operations
112    // ============================================================================
113    println!("═══════════════════════════════════════════════════════════════");
114    println!("Demo 3: Iterator fusion - chained operations optimized");
115    println!("═══════════════════════════════════════════════════════════════\n");
116
117    println!("Chaining multiple operations...");
118    let chained_query = LazyQuery::new(&products)
119        .where_(Product::category_r(), |cat| cat == "Electronics")
120        .where_(Product::price_r(), |&price| price > 200.0)
121        .where_(Product::stock_r(), |&stock| stock > 10)
122        .take_lazy(10);
123
124    println!("  Built query with 3 filters + take(10)");
125    println!("  ✅ No execution yet - all operations fused into one iterator\n");
126
127    let results: Vec<_> = chained_query.collect();
128    println!("  Executed: Found {} items", results.len());
129    println!("  ✅ All filters applied in single pass!\n");
130
131    // ============================================================================
132    // DEMO 4: Lazy Projection - Only Extract What You Need
133    // ============================================================================
134    println!("═══════════════════════════════════════════════════════════════");
135    println!("Demo 4: Lazy projection");
136    println!("═══════════════════════════════════════════════════════════════\n");
137
138    println!("Selecting names (lazy)...");
139    let names: Vec<String> = LazyQuery::new(&products)
140        .where_(Product::category_r(), |cat| cat == "Electronics")
141        .select_lazy(Product::name_r())
142        .take(5)  // Only process until we have 5
143        .collect();
144
145    println!("  Selected {} names", names.len());
146    println!("  ✅ Only evaluated until 5 names found!\n");
147
148    // ============================================================================
149    // DEMO 5: Lazy Aggregation - Short-Circuit When Possible
150    // ============================================================================
151    println!("═══════════════════════════════════════════════════════════════");
152    println!("Demo 5: Short-circuit with .any()");
153    println!("═══════════════════════════════════════════════════════════════\n");
154
155    FILTER_EVALUATIONS.store(0, Ordering::SeqCst);
156
157    println!("Checking if ANY electronics exist (1000 items to search)...");
158    let exists = LazyQuery::new(&products)
159        .where_(Product::category_r(), |cat| {
160            FILTER_EVALUATIONS.fetch_add(1, Ordering::SeqCst);
161            cat == "Electronics"
162        })
163        .any();
164
165    let checks = FILTER_EVALUATIONS.load(Ordering::SeqCst);
166    println!("  Result: {}", exists);
167    println!("  Items checked: {} out of 1000", checks);
168    println!("  Items skipped: {} (short-circuited!)", 1000 - checks);
169    
170    if checks < 1000 {
171        println!("  ✅ Short-circuit worked! Stopped as soon as first match found.\n");
172    }
173
174    // ============================================================================
175    // DEMO 6: Lazy Find - Stops at First Match
176    // ============================================================================
177    println!("═══════════════════════════════════════════════════════════════");
178    println!("Demo 6: .find() stops at first match");
179    println!("═══════════════════════════════════════════════════════════════\n");
180
181    FILTER_EVALUATIONS.store(0, Ordering::SeqCst);
182
183    println!("Finding first product with price > 500...");
184    let found = LazyQuery::new(&products)
185        .where_(Product::price_r(), |&price| {
186            FILTER_EVALUATIONS.fetch_add(1, Ordering::SeqCst);
187            price > 500.0
188        })
189        .first();
190
191    let checks = FILTER_EVALUATIONS.load(Ordering::SeqCst);
192    if let Some(product) = found {
193        println!("  Found: {} (${:.2})", product.name, product.price);
194    }
195    println!("  Items checked: {} out of 1000", checks);
196    println!("  ✅ Stopped immediately after finding first match!\n");
197
198    // ============================================================================
199    // DEMO 7: Composition - Build Queries Incrementally
200    // ============================================================================
201    println!("═══════════════════════════════════════════════════════════════");
202    println!("Demo 7: Composable queries");
203    println!("═══════════════════════════════════════════════════════════════\n");
204
205    println!("Building base query...");
206    let base_query = LazyQuery::new(&products)
207        .where_(Product::category_r(), |cat| cat == "Electronics");
208
209    println!("  Created base query (not executed)\n");
210
211    println!("  Adding price filter...");
212    let refined_query = base_query
213        .where_(Product::price_r(), |&price| price > 100.0);
214
215    println!("  Still not executed...\n");
216
217    println!("  Adding stock filter and limiting...");
218    let final_query = refined_query
219        .where_(Product::stock_r(), |&stock| stock > 5)
220        .take_lazy(10);
221
222    println!("  Still not executed...\n");
223
224    println!("  Executing...");
225    let results: Vec<_> = final_query.collect();
226    println!("  ✅ Executed once with all filters: Found {} items\n", results.len());
227
228    // ============================================================================
229    // DEMO 8: For Loop - Natural Iteration
230    // ============================================================================
231    println!("═══════════════════════════════════════════════════════════════");
232    println!("Demo 8: Use in for loops");
233    println!("═══════════════════════════════════════════════════════════════\n");
234
235    println!("Iterating over filtered products...");
236    let mut count = 0;
237    for product in LazyQuery::new(&products)
238        .where_(Product::category_r(), |cat| cat == "Electronics")
239        .take_lazy(3)
240    {
241        println!("  • {}: ${:.2}", product.name, product.price);
242        count += 1;
243    }
244    println!("  ✅ Processed {} items lazily\n", count);
245
246    // ============================================================================
247    // DEMO 9: Performance Comparison
248    // ============================================================================
249    println!("═══════════════════════════════════════════════════════════════");
250    println!("Demo 9: Performance benefit demonstration");
251    println!("═══════════════════════════════════════════════════════════════\n");
252
253    println!("Scenario: Find first expensive item from 1000 products\n");
254
255    EXPENSIVE_OPERATIONS.store(0, Ordering::SeqCst);
256    
257    println!("Without lazy (hypothetical - check all, then take first):");
258    println!("  Would check: 1000 items");
259    println!("  Would find: ~300 matching items");
260    println!("  Would return: 1 item");
261    println!("  Wasted work: 299 items processed unnecessarily\n");
262
263    EXPENSIVE_OPERATIONS.store(0, Ordering::SeqCst);
264    
265    println!("With lazy evaluation:");
266    let _first = LazyQuery::new(&products)
267        .where_(Product::price_r(), |p| expensive_check(p))
268        .first();
269
270    let ops = EXPENSIVE_OPERATIONS.load(Ordering::SeqCst);
271    println!("  Checked: {} items", ops);
272    println!("  Found: 1 item");
273    println!("  Wasted work: 0 items");
274    println!("  ✅ Efficiency gain: {}x faster!", 1000 / ops.max(1));
275
276    // ============================================================================
277    // Summary
278    // ============================================================================
279    println!("\n╔════════════════════════════════════════════════════════════════╗");
280    println!("║  Lazy Evaluation Benefits                                     ║");
281    println!("╚════════════════════════════════════════════════════════════════╝\n");
282
283    println!("✅ Deferred Execution:");
284    println!("   • No work until results needed");
285    println!("   • Can build complex queries without performance cost\n");
286
287    println!("✅ Early Termination:");
288    println!("   • .take(n) stops after n items");
289    println!("   • .first() stops after 1 item");
290    println!("   • .any() stops after first match");
291    println!("   • Massive performance win for large datasets\n");
292
293    println!("✅ Iterator Fusion:");
294    println!("   • Multiple filters combined into one pass");
295    println!("   • Rust compiler optimizes chained operations");
296    println!("   • No intermediate allocations\n");
297
298    println!("✅ Composable:");
299    println!("   • Build queries incrementally");
300    println!("   • Reuse query fragments");
301    println!("   • Clean separation of query building vs execution\n");
302
303    println!("✅ Zero Overhead:");
304    println!("   • Compiles to same code as manual loops");
305    println!("   • No runtime cost for abstraction");
306    println!("   • Pay only for what you use\n");
307
308    println!("✓ Lazy evaluation demo complete!\n");
309}
Source

pub fn count(self) -> usize

Counts items (terminal operation - executes query).

§Example
let count = query.count();
Source

pub fn any(self) -> bool

Checks if any items match (terminal operation - short-circuits).

§Example
let exists = query.any();
Examples found in repository?
examples/lazy_evaluation.rs (line 163)
47fn main() {
48    println!("\n╔════════════════════════════════════════════════════════════════╗");
49    println!("║  Lazy Query Evaluation Demo                                   ║");
50    println!("╚════════════════════════════════════════════════════════════════╝\n");
51
52    let products = create_products();
53    println!("Created {} products\n", products.len());
54
55    // ============================================================================
56    // DEMO 1: Lazy Execution - Nothing Happens Until .collect()
57    // ============================================================================
58    println!("═══════════════════════════════════════════════════════════════");
59    println!("Demo 1: Lazy execution - deferred until needed");
60    println!("═══════════════════════════════════════════════════════════════\n");
61
62    FILTER_EVALUATIONS.store(0, Ordering::SeqCst);
63
64    println!("Building query (should execute nothing)...");
65    let lazy_query = LazyQuery::new(&products)
66        .where_(Product::category_r(), |cat| {
67            FILTER_EVALUATIONS.fetch_add(1, Ordering::SeqCst);
68            cat == "Electronics"
69        });
70
71    let evals_after_build = FILTER_EVALUATIONS.load(Ordering::SeqCst);
72    println!("  Filter evaluations after building query: {}", evals_after_build);
73    
74    if evals_after_build == 0 {
75        println!("  ✅ Confirmed: Query is lazy! Nothing executed yet.\n");
76    }
77
78    println!("Collecting results (now it executes)...");
79    let results: Vec<_> = lazy_query.collect();
80
81    let evals_after_collect = FILTER_EVALUATIONS.load(Ordering::SeqCst);
82    println!("  Filter evaluations after collecting: {}", evals_after_collect);
83    println!("  Results found: {}", results.len());
84    println!("  ✅ Query executed exactly once, when needed!\n");
85
86    // ============================================================================
87    // DEMO 2: Early Termination - Stops as Soon as Enough Items Found
88    // ============================================================================
89    println!("═══════════════════════════════════════════════════════════════");
90    println!("Demo 2: Early termination with .take()");
91    println!("═══════════════════════════════════════════════════════════════\n");
92
93    EXPENSIVE_OPERATIONS.store(0, Ordering::SeqCst);
94
95    println!("Finding first 5 expensive items from 1000 products...");
96    let first_5: Vec<_> = LazyQuery::new(&products)
97        .where_(Product::price_r(), |p| expensive_check(p))
98        .take_lazy(5)
99        .collect();
100
101    let ops = EXPENSIVE_OPERATIONS.load(Ordering::SeqCst);
102    println!("  Found: {} items", first_5.len());
103    println!("  Expensive operations performed: {}", ops);
104    println!("  Items NOT checked: {} (stopped early!)", 1000 - ops);
105    
106    if ops < 1000 {
107        println!("  ✅ Early termination worked! Didn't check all 1000 items.\n");
108    }
109
110    // ============================================================================
111    // DEMO 3: Iterator Fusion - Rust Optimizes Chained Operations
112    // ============================================================================
113    println!("═══════════════════════════════════════════════════════════════");
114    println!("Demo 3: Iterator fusion - chained operations optimized");
115    println!("═══════════════════════════════════════════════════════════════\n");
116
117    println!("Chaining multiple operations...");
118    let chained_query = LazyQuery::new(&products)
119        .where_(Product::category_r(), |cat| cat == "Electronics")
120        .where_(Product::price_r(), |&price| price > 200.0)
121        .where_(Product::stock_r(), |&stock| stock > 10)
122        .take_lazy(10);
123
124    println!("  Built query with 3 filters + take(10)");
125    println!("  ✅ No execution yet - all operations fused into one iterator\n");
126
127    let results: Vec<_> = chained_query.collect();
128    println!("  Executed: Found {} items", results.len());
129    println!("  ✅ All filters applied in single pass!\n");
130
131    // ============================================================================
132    // DEMO 4: Lazy Projection - Only Extract What You Need
133    // ============================================================================
134    println!("═══════════════════════════════════════════════════════════════");
135    println!("Demo 4: Lazy projection");
136    println!("═══════════════════════════════════════════════════════════════\n");
137
138    println!("Selecting names (lazy)...");
139    let names: Vec<String> = LazyQuery::new(&products)
140        .where_(Product::category_r(), |cat| cat == "Electronics")
141        .select_lazy(Product::name_r())
142        .take(5)  // Only process until we have 5
143        .collect();
144
145    println!("  Selected {} names", names.len());
146    println!("  ✅ Only evaluated until 5 names found!\n");
147
148    // ============================================================================
149    // DEMO 5: Lazy Aggregation - Short-Circuit When Possible
150    // ============================================================================
151    println!("═══════════════════════════════════════════════════════════════");
152    println!("Demo 5: Short-circuit with .any()");
153    println!("═══════════════════════════════════════════════════════════════\n");
154
155    FILTER_EVALUATIONS.store(0, Ordering::SeqCst);
156
157    println!("Checking if ANY electronics exist (1000 items to search)...");
158    let exists = LazyQuery::new(&products)
159        .where_(Product::category_r(), |cat| {
160            FILTER_EVALUATIONS.fetch_add(1, Ordering::SeqCst);
161            cat == "Electronics"
162        })
163        .any();
164
165    let checks = FILTER_EVALUATIONS.load(Ordering::SeqCst);
166    println!("  Result: {}", exists);
167    println!("  Items checked: {} out of 1000", checks);
168    println!("  Items skipped: {} (short-circuited!)", 1000 - checks);
169    
170    if checks < 1000 {
171        println!("  ✅ Short-circuit worked! Stopped as soon as first match found.\n");
172    }
173
174    // ============================================================================
175    // DEMO 6: Lazy Find - Stops at First Match
176    // ============================================================================
177    println!("═══════════════════════════════════════════════════════════════");
178    println!("Demo 6: .find() stops at first match");
179    println!("═══════════════════════════════════════════════════════════════\n");
180
181    FILTER_EVALUATIONS.store(0, Ordering::SeqCst);
182
183    println!("Finding first product with price > 500...");
184    let found = LazyQuery::new(&products)
185        .where_(Product::price_r(), |&price| {
186            FILTER_EVALUATIONS.fetch_add(1, Ordering::SeqCst);
187            price > 500.0
188        })
189        .first();
190
191    let checks = FILTER_EVALUATIONS.load(Ordering::SeqCst);
192    if let Some(product) = found {
193        println!("  Found: {} (${:.2})", product.name, product.price);
194    }
195    println!("  Items checked: {} out of 1000", checks);
196    println!("  ✅ Stopped immediately after finding first match!\n");
197
198    // ============================================================================
199    // DEMO 7: Composition - Build Queries Incrementally
200    // ============================================================================
201    println!("═══════════════════════════════════════════════════════════════");
202    println!("Demo 7: Composable queries");
203    println!("═══════════════════════════════════════════════════════════════\n");
204
205    println!("Building base query...");
206    let base_query = LazyQuery::new(&products)
207        .where_(Product::category_r(), |cat| cat == "Electronics");
208
209    println!("  Created base query (not executed)\n");
210
211    println!("  Adding price filter...");
212    let refined_query = base_query
213        .where_(Product::price_r(), |&price| price > 100.0);
214
215    println!("  Still not executed...\n");
216
217    println!("  Adding stock filter and limiting...");
218    let final_query = refined_query
219        .where_(Product::stock_r(), |&stock| stock > 5)
220        .take_lazy(10);
221
222    println!("  Still not executed...\n");
223
224    println!("  Executing...");
225    let results: Vec<_> = final_query.collect();
226    println!("  ✅ Executed once with all filters: Found {} items\n", results.len());
227
228    // ============================================================================
229    // DEMO 8: For Loop - Natural Iteration
230    // ============================================================================
231    println!("═══════════════════════════════════════════════════════════════");
232    println!("Demo 8: Use in for loops");
233    println!("═══════════════════════════════════════════════════════════════\n");
234
235    println!("Iterating over filtered products...");
236    let mut count = 0;
237    for product in LazyQuery::new(&products)
238        .where_(Product::category_r(), |cat| cat == "Electronics")
239        .take_lazy(3)
240    {
241        println!("  • {}: ${:.2}", product.name, product.price);
242        count += 1;
243    }
244    println!("  ✅ Processed {} items lazily\n", count);
245
246    // ============================================================================
247    // DEMO 9: Performance Comparison
248    // ============================================================================
249    println!("═══════════════════════════════════════════════════════════════");
250    println!("Demo 9: Performance benefit demonstration");
251    println!("═══════════════════════════════════════════════════════════════\n");
252
253    println!("Scenario: Find first expensive item from 1000 products\n");
254
255    EXPENSIVE_OPERATIONS.store(0, Ordering::SeqCst);
256    
257    println!("Without lazy (hypothetical - check all, then take first):");
258    println!("  Would check: 1000 items");
259    println!("  Would find: ~300 matching items");
260    println!("  Would return: 1 item");
261    println!("  Wasted work: 299 items processed unnecessarily\n");
262
263    EXPENSIVE_OPERATIONS.store(0, Ordering::SeqCst);
264    
265    println!("With lazy evaluation:");
266    let _first = LazyQuery::new(&products)
267        .where_(Product::price_r(), |p| expensive_check(p))
268        .first();
269
270    let ops = EXPENSIVE_OPERATIONS.load(Ordering::SeqCst);
271    println!("  Checked: {} items", ops);
272    println!("  Found: 1 item");
273    println!("  Wasted work: 0 items");
274    println!("  ✅ Efficiency gain: {}x faster!", 1000 / ops.max(1));
275
276    // ============================================================================
277    // Summary
278    // ============================================================================
279    println!("\n╔════════════════════════════════════════════════════════════════╗");
280    println!("║  Lazy Evaluation Benefits                                     ║");
281    println!("╚════════════════════════════════════════════════════════════════╝\n");
282
283    println!("✅ Deferred Execution:");
284    println!("   • No work until results needed");
285    println!("   • Can build complex queries without performance cost\n");
286
287    println!("✅ Early Termination:");
288    println!("   • .take(n) stops after n items");
289    println!("   • .first() stops after 1 item");
290    println!("   • .any() stops after first match");
291    println!("   • Massive performance win for large datasets\n");
292
293    println!("✅ Iterator Fusion:");
294    println!("   • Multiple filters combined into one pass");
295    println!("   • Rust compiler optimizes chained operations");
296    println!("   • No intermediate allocations\n");
297
298    println!("✅ Composable:");
299    println!("   • Build queries incrementally");
300    println!("   • Reuse query fragments");
301    println!("   • Clean separation of query building vs execution\n");
302
303    println!("✅ Zero Overhead:");
304    println!("   • Compiles to same code as manual loops");
305    println!("   • No runtime cost for abstraction");
306    println!("   • Pay only for what you use\n");
307
308    println!("✓ Lazy evaluation demo complete!\n");
309}
Source

pub fn for_each<F>(self, f: F)
where F: FnMut(&'a T),

Executes a function for each item (terminal operation).

§Example
query.for_each(|item| println!("{:?}", item));
Source

pub fn fold<B, F>(self, init: B, f: F) -> B
where F: FnMut(B, &'a T) -> B,

Folds the iterator (terminal operation).

§Example
let sum = query.fold(0.0, |acc, item| acc + item.price);
Source

pub fn find<P>(self, predicate: P) -> Option<&'a T>
where P: FnMut(&&'a T) -> bool,

Finds an item matching a predicate (terminal - short-circuits).

§Example
let found = query.find(|item| item.id == 42);
Source

pub fn all_match<P>(self, predicate: P) -> bool
where P: FnMut(&'a T) -> bool,

Checks if all items match a predicate (terminal - short-circuits).

§Example
let all_positive = query.all_match(|item| item.value > 0);
Source

pub fn into_iter(self) -> I

Converts to a standard iterator for further chaining.

§Example
let custom: Vec<_> = query
    .into_iter()
    .map(|item| item.custom_transform())
    .filter(|x| x.is_valid())
    .collect();
Source§

impl<'a, T: 'static, I> LazyQuery<'a, T, I>
where I: Iterator<Item = &'a T> + 'a,

Source

pub fn sum_by<F>(self, path: KeyPaths<T, F>) -> F
where F: Clone + Add<Output = F> + Default + 'static, I: 'a,

Computes sum of a field (terminal operation).

§Example
let total: f64 = LazyQuery::new(&products)
    .sum_by(Product::price_r());
Source

pub fn avg_by(self, path: KeyPaths<T, f64>) -> Option<f64>
where I: 'a,

Computes average of a float field (terminal operation).

§Example
let avg = LazyQuery::new(&products)
    .avg_by(Product::price_r());
Source

pub fn min_by<F>(self, path: KeyPaths<T, F>) -> Option<F>
where F: Ord + Clone + 'static, I: 'a,

Finds minimum value of a field (terminal operation).

§Example
let min = LazyQuery::new(&products)
    .min_by(Product::price_r());
Source

pub fn max_by<F>(self, path: KeyPaths<T, F>) -> Option<F>
where F: Ord + Clone + 'static, I: 'a,

Finds maximum value of a field (terminal operation).

§Example
let max = LazyQuery::new(&products)
    .max_by(Product::price_r());
Source

pub fn min_by_float(self, path: KeyPaths<T, f64>) -> Option<f64>
where I: 'a,

Finds minimum float value (terminal operation).

Source

pub fn max_by_float(self, path: KeyPaths<T, f64>) -> Option<f64>
where I: 'a,

Finds maximum float value (terminal operation).

Trait Implementations§

Source§

impl<'a, T: 'static, I> IntoIterator for LazyQuery<'a, T, I>
where I: Iterator<Item = &'a T>,

Source§

type Item = &'a T

The type of the elements being iterated over.
Source§

type IntoIter = I

Which kind of iterator are we turning this into?
Source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more

Auto Trait Implementations§

§

impl<'a, T, I> Freeze for LazyQuery<'a, T, I>
where I: Freeze,

§

impl<'a, T, I> RefUnwindSafe for LazyQuery<'a, T, I>

§

impl<'a, T, I> Send for LazyQuery<'a, T, I>
where I: Send, T: Sync,

§

impl<'a, T, I> Sync for LazyQuery<'a, T, I>
where I: Sync, T: Sync,

§

impl<'a, T, I> Unpin for LazyQuery<'a, T, I>
where I: Unpin,

§

impl<'a, T, I> UnwindSafe for LazyQuery<'a, T, I>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.