LazyQuery

Struct LazyQuery 

Source
pub struct LazyQuery<'a, T, I>
where T: 'static, 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> LazyQuery<'a, T, Iter<'a, T>>
where T: 'static,

Source

pub fn new(data: &'a [T]) -> LazyQuery<'a, T, Iter<'a, T>>

Creates a new lazy query from a slice.

§Example
let query = LazyQuery::new(&products);
Examples found in repository?
examples/container_support.rs (line 52)
26fn main() {
27    println!("\n╔════════════════════════════════════════════════════════════════╗");
28    println!("║  Container Support Demo                                       ║");
29    println!("║  Query various collection types                               ║");
30    println!("╚════════════════════════════════════════════════════════════════╝\n");
31
32    // ============================================================================
33    // CONTAINER 1: Vec<T>
34    // ============================================================================
35    println!("═══════════════════════════════════════════════════════════════");
36    println!("Container 1: Vec<T>");
37    println!("═══════════════════════════════════════════════════════════════\n");
38
39    let vec_products = vec![
40        create_sample_product(1, "Laptop", 999, "Electronics"),
41        create_sample_product(2, "Mouse", 29, "Electronics"),
42        create_sample_product(3, "Desk", 299, "Furniture"),
43    ];
44
45    // Query Vec directly
46    let vec_query = Query::new(&vec_products)
47        .where_(Product::category_r(), |cat| cat == "Electronics");
48    let vec_results = vec_query.all();
49    println!("  Vec: Found {} electronics", vec_results.len());
50
51    // Lazy query on Vec
52    let lazy_count = LazyQuery::new(&vec_products)
53        .where_(Product::price_r(), |&p| p < 100)
54        .count();
55    println!("  Vec (lazy): {} items under $100", lazy_count);
56
57    // ============================================================================
58    // CONTAINER 2: VecDeque<T>
59    // ============================================================================
60    println!("\n═══════════════════════════════════════════════════════════════");
61    println!("Container 2: VecDeque<T>");
62    println!("═══════════════════════════════════════════════════════════════\n");
63
64    let mut deque_products = VecDeque::new();
65    deque_products.push_back(create_sample_product(1, "Keyboard", 129, "Electronics"));
66    deque_products.push_back(create_sample_product(2, "Monitor", 349, "Electronics"));
67    deque_products.push_back(create_sample_product(3, "Chair", 199, "Furniture"));
68
69    // Convert to owned Vec for querying
70    let deque_vec: Vec<Product> = deque_products.iter().cloned().collect();
71    let deque_query = Query::new(&deque_vec);
72    let deque_count = deque_query.count();
73    println!("  VecDeque: {} total items", deque_count);
74
75    // More efficient: use make_contiguous for zero-copy slice access
76    let contiguous = deque_products.make_contiguous();
77    let contiguous_query = Query::new(contiguous);
78    println!("  VecDeque (zero-copy): {} items", contiguous_query.count());
79
80    // ============================================================================
81    // CONTAINER 3: HashSet<T>
82    // ============================================================================
83    println!("\n═══════════════════════════════════════════════════════════════");
84    println!("Container 3: HashSet<T>");
85    println!("═══════════════════════════════════════════════════════════════\n");
86
87    let mut set_products = HashSet::new();
88    set_products.insert(create_sample_product(1, "Tablet", 499, "Electronics"));
89    set_products.insert(create_sample_product(2, "Phone", 799, "Electronics"));
90    set_products.insert(create_sample_product(3, "Lamp", 39, "Furniture"));
91
92    // Collect from HashSet to Vec for querying
93    let set_vec: Vec<Product> = set_products.iter().cloned().collect();
94    let set_query = Query::new(&set_vec)
95        .where_(Product::price_r(), |&p| p > 500);
96    let expensive = set_query.all();
97    println!("  HashSet: {} expensive items", expensive.len());
98
99    // Lazy on HashSet (convert to owned Vec first)
100    let set_owned: Vec<Product> = set_products.iter().cloned().collect();
101    let lazy_set: Vec<_> = LazyQuery::new(&set_owned)
102        .where_(Product::category_r(), |cat| cat == "Electronics")
103        .collect();
104    println!("  HashSet (lazy): {} electronics", lazy_set.len());
105
106    // ============================================================================
107    // CONTAINER 4: BTreeSet<T>
108    // ============================================================================
109    println!("\n═══════════════════════════════════════════════════════════════");
110    println!("Container 4: BTreeSet<T>");
111    println!("═══════════════════════════════════════════════════════════════\n");
112
113    let mut btree_set = BTreeSet::new();
114    btree_set.insert(create_sample_product(1, "Webcam", 79, "Electronics"));
115    btree_set.insert(create_sample_product(2, "Microphone", 129, "Electronics"));
116    btree_set.insert(create_sample_product(3, "Bookshelf", 149, "Furniture"));
117
118    let btree_vec: Vec<Product> = btree_set.iter().cloned().collect();
119    let btree_query = Query::new(&btree_vec);
120    println!("  BTreeSet: {} total items (sorted order!)", btree_query.count());
121    
122    // BTreeSet items are in sorted order
123    for (i, item) in btree_vec.iter().take(3).enumerate() {
124        println!("    {}. {} (ID: {})", i + 1, item.name, item.id);
125    }
126
127    // ============================================================================
128    // CONTAINER 5: HashMap<K, V> - Query Values
129    // ============================================================================
130    println!("\n═══════════════════════════════════════════════════════════════");
131    println!("Container 5: HashMap<K, V> - Querying values");
132    println!("═══════════════════════════════════════════════════════════════\n");
133
134    let mut map_products = HashMap::new();
135    map_products.insert("prod1", create_sample_product(1, "Speaker", 199, "Electronics"));
136    map_products.insert("prod2", create_sample_product(2, "Headphones", 149, "Electronics"));
137    map_products.insert("prod3", create_sample_product(3, "Ottoman", 249, "Furniture"));
138
139    // Query HashMap values (convert to owned Vec)
140    let map_vec: Vec<Product> = map_products.values().cloned().collect();
141    let map_query = Query::new(&map_vec)
142        .where_(Product::category_r(), |cat| cat == "Electronics");
143    let electronics = map_query.all();
144    println!("  HashMap: {} electronics", electronics.len());
145
146    // ============================================================================
147    // CONTAINER 6: BTreeMap<K, V> - Query Values
148    // ============================================================================
149    println!("\n═══════════════════════════════════════════════════════════════");
150    println!("Container 6: BTreeMap<K, V> - Querying values");
151    println!("═══════════════════════════════════════════════════════════════\n");
152
153    let mut btree_map = BTreeMap::new();
154    btree_map.insert(1, create_sample_product(1, "Router", 89, "Electronics"));
155    btree_map.insert(2, create_sample_product(2, "Switch", 129, "Electronics"));
156    btree_map.insert(3, create_sample_product(3, "Sofa", 899, "Furniture"));
157
158    let btree_map_vec: Vec<Product> = btree_map.values().cloned().collect();
159    let btree_map_query = Query::new(&btree_map_vec);
160    let avg_price = btree_map_query.sum(Product::price_r()) as f64 / btree_map.len() as f64;
161    println!("  BTreeMap: Average price ${:.2}", avg_price);
162
163    // ============================================================================
164    // CONTAINER 7: Arrays [T; N]
165    // ============================================================================
166    println!("\n═══════════════════════════════════════════════════════════════");
167    println!("Container 7: Arrays [T; N]");
168    println!("═══════════════════════════════════════════════════════════════\n");
169
170    let array_products = [
171        create_sample_product(1, "USB Cable", 15, "Electronics"),
172        create_sample_product(2, "HDMI Cable", 25, "Electronics"),
173        create_sample_product(3, "Power Strip", 35, "Electronics"),
174    ];
175
176    // Query array directly (as slice)
177    let array_query = Query::new(&array_products);
178    let total = array_query.sum(Product::price_r());
179    println!("  Array: Total value ${}", total);
180
181    // Lazy on array
182    let lazy_array: Vec<_> = LazyQuery::new(&array_products)
183        .where_(Product::price_r(), |&p| p > 20)
184        .collect();
185    println!("  Array (lazy): {} items over $20", lazy_array.len());
186
187    // ============================================================================
188    // CONTAINER 8: LinkedList<T>
189    // ============================================================================
190    println!("\n═══════════════════════════════════════════════════════════════");
191    println!("Container 8: LinkedList<T>");
192    println!("═══════════════════════════════════════════════════════════════\n");
193
194    let mut list_products = LinkedList::new();
195    list_products.push_back(create_sample_product(1, "SSD", 159, "Electronics"));
196    list_products.push_back(create_sample_product(2, "HDD", 79, "Electronics"));
197
198    let list_vec: Vec<Product> = list_products.iter().cloned().collect();
199    let list_query = Query::new(&list_vec);
200    println!("  LinkedList: {} items", list_query.count());
201
202    // ============================================================================
203    // CONTAINER 9: Option<T> and Result<T, E>
204    // ============================================================================
205    println!("\n═══════════════════════════════════════════════════════════════");
206    println!("Container 9: Option<T> and Result<T, E>");
207    println!("═══════════════════════════════════════════════════════════════\n");
208
209    let maybe_product = Some(create_sample_product(1, "Mystery Box", 99, "Special"));
210    
211    if let Some(ref product) = maybe_product {
212        let option_query = Query::new(std::slice::from_ref(product));
213        println!("  Option (Some): {} items", option_query.count());
214    }
215
216    let none_product: Option<Product> = None;
217    let none_count = none_product.iter().count();
218    println!("  Option (None): {} items", none_count);
219
220    // ============================================================================
221    // Summary
222    // ============================================================================
223    println!("\n╔════════════════════════════════════════════════════════════════╗");
224    println!("║  Supported Containers Summary                                  ║");
225    println!("╚════════════════════════════════════════════════════════════════╝\n");
226
227    println!("✅ Supported container types:");
228    println!("   • Vec<T>              - Standard vector");
229    println!("   • &[T]                - Slices");
230    println!("   • [T; N]              - Fixed-size arrays");
231    println!("   • VecDeque<T>         - Double-ended queue");
232    println!("   • LinkedList<T>       - Doubly-linked list");
233    println!("   • HashSet<T>          - Unordered set");
234    println!("   • BTreeSet<T>         - Ordered set");
235    println!("   • HashMap<K, V>       - Query values");
236    println!("   • BTreeMap<K, V>      - Query values (sorted)");
237    println!("   • Option<T>           - 0 or 1 item");
238    println!("   • Result<T, E>        - 0 or 1 item\n");
239
240    println!("📝 Usage patterns:");
241    println!("   • Direct: Query::new(&container) for Vec, slices, arrays");
242    println!("   • Convert: Collect to Vec for Sets and Maps");
243    println!("   • Lazy: LazyQuery::new(&slice) for any slice\n");
244
245    println!("💡 Tips:");
246    println!("   • Vec/slice: Direct support, most efficient");
247    println!("   • Sets: Iterate to Vec, then query");
248    println!("   • Maps: Use .values().collect() to query values");
249    println!("   • VecDeque: Use .as_slices() for zero-copy");
250    println!("   • For custom types: Implement Queryable trait\n");
251
252    println!("✓ Container support demo complete!\n");
253}
More examples
Hide additional examples
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}
examples/custom_queryable.rs (line 399)
230fn main() {
231    println!("\n╔════════════════════════════════════════════════════════════════╗");
232    println!("║  Custom Queryable Implementation Demo                         ║");
233    println!("╚════════════════════════════════════════════════════════════════╝\n");
234
235    // ============================================================================
236    // DEMO 1: PaginatedCollection
237    // ============================================================================
238    println!("═══════════════════════════════════════════════════════════════");
239    println!("Demo 1: PaginatedCollection (custom container)");
240    println!("═══════════════════════════════════════════════════════════════\n");
241
242    let mut paginated = PaginatedCollection::new(3); // 3 items per page
243    
244    paginated.add(create_sample_product(1, "Laptop", 999.0, "Electronics", true));
245    paginated.add(create_sample_product(2, "Mouse", 29.0, "Electronics", true));
246    paginated.add(create_sample_product(3, "Keyboard", 129.0, "Electronics", true));
247    paginated.add(create_sample_product(4, "Desk", 299.0, "Furniture", true));
248    paginated.add(create_sample_product(5, "Chair", 199.0, "Furniture", false));
249
250    println!("  Created paginated collection:");
251    println!("    Total items: {}", paginated.total_items());
252    println!("    Pages: {}", paginated.pages.len());
253
254    // Now we can query it using the Queryable trait!
255    // Collect to owned Vec for querying
256    let items: Vec<Product> = paginated.query_iter().cloned().collect();
257    let query = Query::new(&items)
258        .where_(Product::category_r(), |cat| cat == "Electronics");
259    let electronics = query.all();
260    
261    println!("\n  Querying paginated collection:");
262    println!("    Electronics found: {}", electronics.len());
263    for product in electronics {
264        println!("      • {}: ${:.2}", product.name, product.price);
265    }
266
267    // ============================================================================
268    // DEMO 2: CircularBuffer
269    // ============================================================================
270    println!("\n═══════════════════════════════════════════════════════════════");
271    println!("Demo 2: CircularBuffer (fixed capacity)");
272    println!("═══════════════════════════════════════════════════════════════\n");
273
274    let mut circular = CircularBuffer::new(3); // Capacity: 3
275    
276    circular.push(create_sample_product(1, "Product 1", 100.0, "A", true));
277    circular.push(create_sample_product(2, "Product 2", 200.0, "B", true));
278    circular.push(create_sample_product(3, "Product 3", 300.0, "C", true));
279    circular.push(create_sample_product(4, "Product 4", 400.0, "D", true)); // Pushes out Product 1
280
281    println!("  Circular buffer (capacity 3, added 4 items):");
282    println!("    Current size: {}", circular.len());
283
284    // Query the circular buffer
285    let circ_items: Vec<Product> = circular.query_iter().cloned().collect();
286    let circ_query = Query::new(&circ_items);
287    let avg_price = circ_query.avg(Product::price_r()).unwrap_or(0.0);
288    
289    println!("\n  Querying circular buffer:");
290    println!("    Average price: ${:.2}", avg_price);
291    println!("    Items:");
292    for (i, product) in circ_items.iter().enumerate() {
293        println!("      {}. {}: ${:.2}", i + 1, product.name, product.price);
294    }
295
296    // ============================================================================
297    // DEMO 3: FilteredStorage
298    // ============================================================================
299    println!("\n═══════════════════════════════════════════════════════════════");
300    println!("Demo 3: FilteredStorage (auto-filtering container)");
301    println!("═══════════════════════════════════════════════════════════════\n");
302
303    let mut filtered = FilteredStorage::new(|p: &Product| p.price < 200.0);
304    
305    println!("  FilteredStorage (only accepts items < $200):");
306    println!("    Adding Laptop ($999): {}", filtered.add(create_sample_product(1, "Laptop", 999.0, "Electronics", true)));
307    println!("    Adding Mouse ($29): {}", filtered.add(create_sample_product(2, "Mouse", 29.0, "Electronics", true)));
308    println!("    Adding Keyboard ($129): {}", filtered.add(create_sample_product(3, "Keyboard", 129.0, "Electronics", true)));
309    println!("    Total stored: {}", filtered.len());
310
311    // Query the filtered storage
312    let filt_items: Vec<Product> = filtered.query_iter().cloned().collect();
313    let filt_query = Query::new(&filt_items)
314        .where_(Product::in_stock_r(), |&v| v);
315    let in_stock = filt_query.all();
316    
317    println!("\n  Querying filtered storage:");
318    println!("    In stock items: {}", in_stock.len());
319
320    // ============================================================================
321    // DEMO 4: CategoryIndex
322    // ============================================================================
323    println!("\n═══════════════════════════════════════════════════════════════");
324    println!("Demo 4: CategoryIndex (indexed by category)");
325    println!("═══════════════════════════════════════════════════════════════\n");
326
327    let mut category_index = CategoryIndex::new();
328    
329    category_index.add("Electronics".to_string(), create_sample_product(1, "Monitor", 349.0, "Electronics", true));
330    category_index.add("Electronics".to_string(), create_sample_product(2, "Webcam", 79.0, "Electronics", true));
331    category_index.add("Furniture".to_string(), create_sample_product(3, "Desk", 299.0, "Furniture", true));
332    category_index.add("Furniture".to_string(), create_sample_product(4, "Lamp", 39.0, "Furniture", true));
333
334    println!("  CategoryIndex:");
335    println!("    Categories: {:?}", category_index.categories());
336    println!("    Total items: {}", category_index.total_items());
337
338    // Query across all categories
339    let idx_items: Vec<Product> = category_index.query_iter().cloned().collect();
340    let idx_query = Query::new(&idx_items);
341    let expensive = idx_query
342        .where_(Product::price_r(), |&p| p > 100.0);
343    let expensive_items = expensive.all();
344    
345    println!("\n  Querying category index:");
346    println!("    Expensive items (>$100): {}", expensive_items.len());
347    for product in expensive_items {
348        println!("      • {}: ${:.2} ({})", product.name, product.price, product.category);
349    }
350
351    // ============================================================================
352    // DEMO 5: LazyLoader
353    // ============================================================================
354    println!("\n═══════════════════════════════════════════════════════════════");
355    println!("Demo 5: LazyLoader (simulated lazy loading)");
356    println!("═══════════════════════════════════════════════════════════════\n");
357
358    let loader = LazyLoader::new(vec![
359        create_sample_product(1, "Item 1", 50.0, "A", true),
360        create_sample_product(2, "Item 2", 150.0, "B", true),
361        create_sample_product(3, "Item 3", 250.0, "C", true),
362    ]);
363
364    println!("  LazyLoader:");
365    println!("    Total available: {}", loader.total_count());
366    println!("    Currently loaded: {}", loader.loaded_count());
367
368    // Query loaded items
369    let loader_items: Vec<Product> = loader.query_iter().cloned().collect();
370    let loader_query = Query::new(&loader_items);
371    let total_value = loader_query.sum(Product::price_r());
372    
373    println!("\n  Querying lazy loader:");
374    println!("    Total value: ${:.2}", total_value);
375
376    // ============================================================================
377    // DEMO 6: Custom Container with LazyQuery
378    // ============================================================================
379    println!("\n═══════════════════════════════════════════════════════════════");
380    println!("Demo 6: Using LazyQuery with custom containers");
381    println!("═══════════════════════════════════════════════════════════════\n");
382
383    let mut circular = CircularBuffer::new(5);
384    for i in 1..=10 {
385        circular.push(create_sample_product(
386            i,
387            &format!("Product {}", i),
388            i as f64 * 50.0,
389            if i % 2 == 0 { "Even" } else { "Odd" },
390            true,
391        ));
392    }
393
394    println!("  Circular buffer (capacity 5, added 10 items):");
395    println!("    Current size: {}", circular.len());
396
397    // Use LazyQuery for early termination!
398    let circ_vec: Vec<Product> = circular.query_iter().cloned().collect();
399    let first_expensive = LazyQuery::new(&circ_vec)
400        .where_(Product::price_r(), |&p| p > 300.0)
401        .first();
402
403    if let Some(product) = first_expensive {
404        println!("\n  First expensive item (lazy query):");
405        println!("    {}: ${:.2}", product.name, product.price);
406    }
407
408    // ============================================================================
409    // DEMO 7: Implementing Queryable for Wrapper Types
410    // ============================================================================
411    println!("\n═══════════════════════════════════════════════════════════════");
412    println!("Demo 7: Queryable for wrapper types");
413    println!("═══════════════════════════════════════════════════════════════\n");
414
415    /// A simple wrapper around Vec with metadata
416    struct VersionedCollection<T> {
417        items: Vec<T>,
418        version: u32,
419        last_modified: String,
420    }
421
422    impl<T> Queryable<T> for VersionedCollection<T> {
423        fn query_iter(&self) -> Box<dyn Iterator<Item = &T> + '_> {
424            Box::new(self.items.iter())
425        }
426    }
427
428    let versioned = VersionedCollection {
429        items: vec![
430            create_sample_product(1, "V1 Product", 99.0, "Test", true),
431            create_sample_product(2, "V2 Product", 199.0, "Test", true),
432        ],
433        version: 2,
434        last_modified: "2025-10-11".to_string(),
435    };
436
437    println!("  VersionedCollection:");
438    println!("    Version: {}", versioned.version);
439    println!("    Last modified: {}", versioned.last_modified);
440
441    let versioned_items: Vec<Product> = versioned.query_iter().cloned().collect();
442    let query = Query::new(&versioned_items);
443    println!("    Items: {}", query.count());
444
445    // ============================================================================
446    // DEMO 8: Real-World Example - Cache with TTL
447    // ============================================================================
448    println!("\n═══════════════════════════════════════════════════════════════");
449    println!("Demo 8: Cache container (real-world example)");
450    println!("═══════════════════════════════════════════════════════════════\n");
451
452    use std::time::{Duration, SystemTime};
453
454    struct CachedItem<T> {
455        item: T,
456        inserted_at: SystemTime,
457        ttl: Duration,
458    }
459
460    struct Cache<T> {
461        items: Vec<CachedItem<T>>,
462    }
463
464    impl<T> Cache<T> {
465        fn new() -> Self {
466            Self { items: Vec::new() }
467        }
468
469        fn insert(&mut self, item: T, ttl: Duration) {
470            self.items.push(CachedItem {
471                item,
472                inserted_at: SystemTime::now(),
473                ttl,
474            });
475        }
476
477        fn valid_items(&self) -> Vec<&T> {
478            let now = SystemTime::now();
479            self.items
480                .iter()
481                .filter(|cached| {
482                    now.duration_since(cached.inserted_at)
483                        .map_or(false, |elapsed| elapsed < cached.ttl)
484                })
485                .map(|cached| &cached.item)
486                .collect()
487        }
488    }
489
490    // Implement Queryable to query only valid (non-expired) items
491    impl<T> Queryable<T> for Cache<T> {
492        fn query_iter(&self) -> Box<dyn Iterator<Item = &T> + '_> {
493            let now = SystemTime::now();
494            Box::new(
495                self.items
496                    .iter()
497                    .filter(move |cached| {
498                        now.duration_since(cached.inserted_at)
499                            .map_or(false, |elapsed| elapsed < cached.ttl)
500                    })
501                    .map(|cached| &cached.item),
502            )
503        }
504    }
505
506    let mut cache = Cache::new();
507    cache.insert(create_sample_product(1, "Cached Item 1", 100.0, "A", true), Duration::from_secs(60));
508    cache.insert(create_sample_product(2, "Cached Item 2", 200.0, "B", true), Duration::from_secs(60));
509
510    let valid = cache.valid_items();
511    println!("  Cache:");
512    println!("    Total items: {}", cache.items.len());
513    println!("    Valid items: {}", valid.len());
514
515    // Query the cache
516    let cache_items: Vec<Product> = cache.query_iter().cloned().collect();
517    let cache_query = Query::new(&cache_items);
518    println!("    Queryable items: {}", cache_query.count());
519
520    // ============================================================================
521    // Summary
522    // ============================================================================
523    println!("\n╔════════════════════════════════════════════════════════════════╗");
524    println!("║  Summary: Implementing Queryable                              ║");
525    println!("╚════════════════════════════════════════════════════════════════╝\n");
526
527    println!("✅ How to make any container queryable:\n");
528    println!("  1. Implement the Queryable<T> trait:");
529    println!("     ```rust");
530    println!("     impl<T> Queryable<T> for MyContainer<T> {{");
531    println!("         fn query_iter(&self) -> Box<dyn Iterator<Item = &T> + '_> {{");
532    println!("             Box::new(self.items.iter())");
533    println!("         }}");
534    println!("     }}");
535    println!("     ```\n");
536
537    println!("  2. Convert to Vec or slice for querying:");
538    println!("     ```rust");
539    println!("     let items: Vec<&Product> = container.query_iter().collect();");
540    println!("     let query = Query::new(&items);");
541    println!("     ```\n");
542
543    println!("  3. Now use all query operations:");
544    println!("     ```rust");
545    println!("     let results = query.where_(...).all();");
546    println!("     let count = query.count();");
547    println!("     let total = query.sum(field);");
548    println!("     ```\n");
549
550    println!("📝 Custom containers demonstrated:");
551    println!("   • PaginatedCollection - Items stored in pages");
552    println!("   • CircularBuffer - Fixed-capacity FIFO buffer");
553    println!("   • FilteredStorage - Auto-filtering container");
554    println!("   • CategoryIndex - Indexed by category");
555    println!("   • LazyLoader - Simulated lazy loading");
556    println!("   • VersionedCollection - Wrapper with metadata");
557    println!("   • Cache - TTL-based cache\n");
558
559    println!("💡 Use cases:");
560    println!("   • Database result wrappers");
561    println!("   • Custom data structures");
562    println!("   • Specialized collections");
563    println!("   • Caches and buffers");
564    println!("   • Event streams");
565    println!("   • Any container that holds items!\n");
566
567    println!("✓ Custom Queryable demo complete!\n");
568}
examples/macro_helpers.rs (line 325)
36fn main() {
37    println!("\n╔════════════════════════════════════════════════════════════════╗");
38    println!("║  Macro Helpers Demo - Reducing Boilerplate                    ║");
39    println!("╚════════════════════════════════════════════════════════════════╝\n");
40
41    let products = create_products();
42
43    // ============================================================================
44    // EXAMPLE 1: Simple Collection
45    // ============================================================================
46    println!("═══════════════════════════════════════════════════════════════");
47    println!("Example 1: collect_lazy! - Simple collection");
48    println!("═══════════════════════════════════════════════════════════════\n");
49
50    println!("❌ Without macro (verbose):");
51    println!("```rust");
52    println!("let results: Vec<_> = LazyQuery::new(&products).collect();");
53    println!("```\n");
54
55    println!("✅ With macro (concise):");
56    println!("```rust");
57    println!("let results = collect_lazy!(&products);");
58    println!("```\n");
59
60    let results = collect_lazy!(&products);
61    println!("Result: {} products collected\n", results.len());
62
63    // ============================================================================
64    // EXAMPLE 2: Filter and Collect
65    // ============================================================================
66    println!("═══════════════════════════════════════════════════════════════");
67    println!("Example 2: filter_collect! - Filter and collect");
68    println!("═══════════════════════════════════════════════════════════════\n");
69
70    println!("❌ Without macro (verbose):");
71    println!("```rust");
72    println!("let electronics: Vec<_> = LazyQuery::new(&products)");
73    println!("    .where_(Product::category_r(), |cat| cat == \"Electronics\")");
74    println!("    .collect();");
75    println!("```\n");
76
77    println!("✅ With macro (concise):");
78    println!("```rust");
79    println!("let electronics = filter_collect!(");
80    println!("    &products,");
81    println!("    Product::category_r(),");
82    println!("    |cat| cat == \"Electronics\"");
83    println!(");");
84    println!("```\n");
85
86    let electronics = filter_collect!(
87        &products,
88        Product::category_r(),
89        |cat| cat == "Electronics"
90    );
91    println!("Result: {} electronics\n", electronics.len());
92
93    // ============================================================================
94    // EXAMPLE 3: Count with Filter
95    // ============================================================================
96    println!("═══════════════════════════════════════════════════════════════");
97    println!("Example 3: count_where! - Count with filter");
98    println!("═══════════════════════════════════════════════════════════════\n");
99
100    println!("❌ Without macro (verbose):");
101    println!("```rust");
102    println!("let count = LazyQuery::new(&products)");
103    println!("    .where_(Product::stock_r(), |&s| s > 0)");
104    println!("    .count();");
105    println!("```\n");
106
107    println!("✅ With macro (concise):");
108    println!("```rust");
109    println!("let count = count_where!(&products, Product::stock_r(), |&s| s > 0);");
110    println!("```\n");
111
112    let count = count_where!(&products, Product::stock_r(), |&s| s > 0);
113    println!("Result: {} products in stock\n", count);
114
115    // ============================================================================
116    // EXAMPLE 4: Find First
117    // ============================================================================
118    println!("═══════════════════════════════════════════════════════════════");
119    println!("Example 4: find_first! - Find first matching item");
120    println!("═══════════════════════════════════════════════════════════════\n");
121
122    println!("❌ Without macro (verbose):");
123    println!("```rust");
124    println!("let found = LazyQuery::new(&products)");
125    println!("    .where_(Product::price_r(), |&p| p > 500.0)");
126    println!("    .first();");
127    println!("```\n");
128
129    println!("✅ With macro (concise):");
130    println!("```rust");
131    println!("let found = find_first!(&products, Product::price_r(), |&p| p > 500.0);");
132    println!("```\n");
133
134    let found = find_first!(&products, Product::price_r(), |&p| p > 500.0);
135    if let Some(p) = found {
136        println!("Result: Found {} at ${:.2}\n", p.name, p.price);
137    }
138
139    // ============================================================================
140    // EXAMPLE 5: Existence Check
141    // ============================================================================
142    println!("═══════════════════════════════════════════════════════════════");
143    println!("Example 5: exists_where! - Check if any item matches");
144    println!("═══════════════════════════════════════════════════════════════\n");
145
146    println!("❌ Without macro (verbose):");
147    println!("```rust");
148    println!("let has_furniture = LazyQuery::new(&products)");
149    println!("    .where_(Product::category_r(), |cat| cat == \"Furniture\")");
150    println!("    .any();");
151    println!("```\n");
152
153    println!("✅ With macro (concise):");
154    println!("```rust");
155    println!("let has_furniture = exists_where!(");
156    println!("    &products,");
157    println!("    Product::category_r(),");
158    println!("    |cat| cat == \"Furniture\"");
159    println!(");");
160    println!("```\n");
161
162    let has_furniture = exists_where!(
163        &products,
164        Product::category_r(),
165        |cat| cat == "Furniture"
166    );
167    println!("Result: Has furniture = {}\n", has_furniture);
168
169    // ============================================================================
170    // EXAMPLE 6: Pagination
171    // ============================================================================
172    println!("═══════════════════════════════════════════════════════════════");
173    println!("Example 6: paginate! - Quick pagination");
174    println!("═══════════════════════════════════════════════════════════════\n");
175
176    println!("❌ Without macro (verbose):");
177    println!("```rust");
178    println!("let page_2: Vec<_> = LazyQuery::new(&products)");
179    println!("    .skip_lazy(1 * 2)  // page * size");
180    println!("    .take_lazy(2)");
181    println!("    .collect();");
182    println!("```\n");
183
184    println!("✅ With macro (concise):");
185    println!("```rust");
186    println!("let page_2 = paginate!(&products, page: 1, size: 2);");
187    println!("```\n");
188
189    let page_2 = paginate!(&products, page: 1, size: 2);
190    println!("Result: Page 2 has {} items\n", page_2.len());
191
192    // ============================================================================
193    // EXAMPLE 7: Sum with Filter
194    // ============================================================================
195    println!("═══════════════════════════════════════════════════════════════");
196    println!("Example 7: sum_where! - Sum with filter");
197    println!("═══════════════════════════════════════════════════════════════\n");
198
199    println!("❌ Without macro (verbose):");
200    println!("```rust");
201    println!("let total: f64 = LazyQuery::new(&products)");
202    println!("    .where_(Product::active_r(), |&a| a)");
203    println!("    .sum_by(Product::price_r());");
204    println!("```\n");
205
206    println!("✅ With macro (concise):");
207    println!("```rust");
208    println!("let total = sum_where!(&products, Product::price_r(), Product::active_r(), |&a| a);");
209    println!("```\n");
210
211    let total = sum_where!(&products, Product::price_r(), Product::active_r(), |&a| a);
212    println!("Result: Total active products value = ${:.2}\n", total);
213
214    // ============================================================================
215    // EXAMPLE 8: Average with Filter
216    // ============================================================================
217    println!("═══════════════════════════════════════════════════════════════");
218    println!("Example 8: avg_where! - Average with filter");
219    println!("═══════════════════════════════════════════════════════════════\n");
220
221    println!("❌ Without macro (verbose):");
222    println!("```rust");
223    println!("let avg = LazyQuery::new(&products)");
224    println!("    .where_(Product::category_r(), |cat| cat == \"Electronics\")");
225    println!("    .avg_by(Product::price_r())");
226    println!("    .unwrap_or(0.0);");
227    println!("```\n");
228
229    println!("✅ With macro (concise):");
230    println!("```rust");
231    println!("let avg = avg_where!(");
232    println!("    &products,");
233    println!("    Product::price_r(),");
234    println!("    Product::category_r(),");
235    println!("    |cat| cat == \"Electronics\"");
236    println!(").unwrap_or(0.0);");
237    println!("```\n");
238
239    let avg = avg_where!(
240        &products,
241        Product::price_r(),
242        Product::category_r(),
243        |cat| cat == "Electronics"
244    ).unwrap_or(0.0);
245    println!("Result: Average electronics price = ${:.2}\n", avg);
246
247    // ============================================================================
248    // EXAMPLE 9: Select All
249    // ============================================================================
250    println!("═══════════════════════════════════════════════════════════════");
251    println!("Example 9: select_all! - Select field from all items");
252    println!("═══════════════════════════════════════════════════════════════\n");
253
254    println!("❌ Without macro (verbose):");
255    println!("```rust");
256    println!("let names: Vec<String> = LazyQuery::new(&products)");
257    println!("    .select_lazy(Product::name_r())");
258    println!("    .collect();");
259    println!("```\n");
260
261    println!("✅ With macro (concise):");
262    println!("```rust");
263    println!("let names = select_all!(&products, Product::name_r());");
264    println!("```\n");
265
266    let names: Vec<String> = select_all!(&products, Product::name_r());
267    println!("Result: {} product names\n", names.len());
268
269    // ============================================================================
270    // EXAMPLE 10: Select with Filter
271    // ============================================================================
272    println!("═══════════════════════════════════════════════════════════════");
273    println!("Example 10: select_where! - Select field with filter");
274    println!("═══════════════════════════════════════════════════════════════\n");
275
276    println!("❌ Without macro (verbose):");
277    println!("```rust");
278    println!("let furniture_names: Vec<String> = LazyQuery::new(&products)");
279    println!("    .where_(Product::category_r(), |cat| cat == \"Furniture\")");
280    println!("    .select_lazy(Product::name_r())");
281    println!("    .collect();");
282    println!("```\n");
283
284    println!("✅ With macro (concise):");
285    println!("```rust");
286    println!("let furniture_names = select_where!(");
287    println!("    &products,");
288    println!("    Product::name_r(),");
289    println!("    Product::category_r(),");
290    println!("    |cat| cat == \"Furniture\"");
291    println!(");");
292    println!("```\n");
293
294    let furniture_names: Vec<String> = select_where!(
295        &products,
296        Product::name_r(),
297        Product::category_r(),
298        |cat| cat == "Furniture"
299    );
300    println!("Result: {} furniture items\n", furniture_names.len());
301
302    // ============================================================================
303    // COMPARISON: Complex Query
304    // ============================================================================
305    println!("═══════════════════════════════════════════════════════════════");
306    println!("Complex Example: Before & After");
307    println!("═══════════════════════════════════════════════════════════════\n");
308
309    println!("Scenario: Filter electronics, under $500, in stock, get first 5\n");
310
311    println!("❌ WITHOUT MACROS (13 lines):");
312    println!("```rust");
313    println!("let results: Vec<_> = LazyQuery::new(&products)");
314    println!("    .where_(");
315    println!("        Product::category_r(),");
316    println!("        |cat| cat == \"Electronics\"");
317    println!("    )");
318    println!("    .where_(Product::price_r(), |&p| p < 500.0)");
319    println!("    .where_(Product::stock_r(), |&s| s > 0)");
320    println!("    .take_lazy(5)");
321    println!("    .collect();");
322    println!("```\n");
323
324    // Actual verbose version
325    let verbose_results: Vec<_> = LazyQuery::new(&products)
326        .where_(Product::category_r(), |cat| cat == "Electronics")
327        .where_(Product::price_r(), |&p| p < 500.0)
328        .where_(Product::stock_r(), |&s| s > 0)
329        .take_lazy(5)
330        .collect();
331
332    println!("✅ WITH MACROS (Shorter, but still need multiple filters):");
333    println!("```rust");
334    println!("let results = lazy_query!(&products)");
335    println!("    .where_(Product::category_r(), |cat| cat == \"Electronics\")");
336    println!("    .where_(Product::price_r(), |&p| p < 500.0)");
337    println!("    .where_(Product::stock_r(), |&s| s > 0)");
338    println!("    .take_lazy(5)");
339    println!("    .collect();");
340    println!("```\n");
341
342    let macro_results = lazy_query!(&products)
343        .where_(Product::category_r(), |cat| cat == "Electronics")
344        .where_(Product::price_r(), |&p| p < 500.0)
345        .where_(Product::stock_r(), |&s| s > 0)
346        .take_lazy(5)
347        .collect();
348
349    println!("Both approaches found {} items ✅\n", verbose_results.len());
350    assert_eq!(verbose_results.len(), macro_results.len());
351
352    // ============================================================================
353    // CODE REDUCTION METRICS
354    // ============================================================================
355    println!("═══════════════════════════════════════════════════════════════");
356    println!("Code Reduction Metrics");
357    println!("═══════════════════════════════════════════════════════════════\n");
358
359    println!("Pattern Comparisons:\n");
360
361    println!("  1. Simple collect:");
362    println!("     Before: LazyQuery::new(&data).collect()");
363    println!("     After:  collect_lazy!(&data)");
364    println!("     Saved:  ~20 characters\n");
365
366    println!("  2. Filter + collect:");
367    println!("     Before: LazyQuery::new(&data).where_(...).collect()");
368    println!("     After:  filter_collect!(&data, field, pred)");
369    println!("     Saved:  ~35 characters\n");
370
371    println!("  3. Count with filter:");
372    println!("     Before: LazyQuery::new(&data).where_(...).count()");
373    println!("     After:  count_where!(&data, field, pred)");
374    println!("     Saved:  ~30 characters\n");
375
376    println!("  4. Pagination:");
377    println!("     Before: LazyQuery::new(&data).skip_lazy(p*s).take_lazy(s).collect()");
378    println!("     After:  paginate!(&data, page: p, size: s)");
379    println!("     Saved:  ~45 characters\n");
380
381    println!("  5. Sum with filter:");
382    println!("     Before: LazyQuery::new(&data).where_(...).sum_by(...)");
383    println!("     After:  sum_where!(&data, sum_field, filter_field, pred)");
384    println!("     Saved:  ~25 characters\n");
385
386    // ============================================================================
387    // ALL MACRO DEMONSTRATIONS
388    // ============================================================================
389    println!("═══════════════════════════════════════════════════════════════");
390    println!("All Available Macros - Quick Reference");
391    println!("═══════════════════════════════════════════════════════════════\n");
392
393    println!("1. lazy_query!(&data)");
394    let _q1 = lazy_query!(&products);
395    println!("   → LazyQuery::new(&data)\n");
396
397    println!("2. query!(&data)");
398    let _q2 = query!(&products);
399    println!("   → Query::new(&data)\n");
400
401    println!("3. collect_lazy!(&data)");
402    let _r3 = collect_lazy!(&products);
403    println!("   → LazyQuery::new(&data).collect()\n");
404
405    println!("4. filter_collect!(&data, field, pred)");
406    let _r4 = filter_collect!(&products, Product::active_r(), |&a| a);
407    println!("   → LazyQuery::new(&data).where_(field, pred).collect()\n");
408
409    println!("5. count_where!(&data, field, pred)");
410    let _r5 = count_where!(&products, Product::active_r(), |&a| a);
411    println!("   → LazyQuery::new(&data).where_(field, pred).count()\n");
412
413    println!("6. find_first!(&data, field, pred)");
414    let _r6 = find_first!(&products, Product::id_r(), |&id| id == 1);
415    println!("   → LazyQuery::new(&data).where_(field, pred).first()\n");
416
417    println!("7. exists_where!(&data, field, pred)");
418    let _r7 = exists_where!(&products, Product::active_r(), |&a| a);
419    println!("   → LazyQuery::new(&data).where_(field, pred).any()\n");
420
421    println!("8. paginate!(&data, page: p, size: s)");
422    let _r8 = paginate!(&products, page: 0, size: 3);
423    println!("   → LazyQuery::new(&data).skip_lazy(p*s).take_lazy(s).collect()\n");
424
425    println!("9. sum_where!(&data, sum_field, filter_field, pred)");
426    let _r9 = sum_where!(&products, Product::price_r(), Product::active_r(), |&a| a);
427    println!("   → LazyQuery::new(&data).where_(filter_field, pred).sum_by(sum_field)\n");
428
429    println!("10. avg_where!(&data, avg_field, filter_field, pred)");
430    let _r10 = avg_where!(&products, Product::price_r(), Product::active_r(), |&a| a);
431    println!("    → LazyQuery::new(&data).where_(filter_field, pred).avg_by(avg_field)\n");
432
433    println!("11. select_all!(&data, field)");
434    let _r11: Vec<String> = select_all!(&products, Product::name_r());
435    println!("    → LazyQuery::new(&data).select_lazy(field).collect()\n");
436
437    println!("12. select_where!(&data, select_field, filter_field, pred)");
438    let _r12: Vec<String> = select_where!(&products, Product::name_r(), Product::active_r(), |&a| a);
439    println!("    → LazyQuery::new(&data).where_(filter, pred).select_lazy(field).collect()\n");
440
441    // ============================================================================
442    // Summary
443    // ============================================================================
444    println!("╔════════════════════════════════════════════════════════════════╗");
445    println!("║  Summary                                                       ║");
446    println!("╚════════════════════════════════════════════════════════════════╝\n");
447
448    println!("✅ 12 helper macros provided:");
449    println!("   • lazy_query! - Create LazyQuery");
450    println!("   • query! - Create Query");
451    println!("   • collect_lazy! - Quick collect");
452    println!("   • filter_collect! - Filter and collect");
453    println!("   • count_where! - Count with filter");
454    println!("   • find_first! - Find first match");
455    println!("   • exists_where! - Existence check");
456    println!("   • paginate! - Easy pagination");
457    println!("   • sum_where! - Sum with filter");
458    println!("   • avg_where! - Average with filter");
459    println!("   • select_all! - Select all");
460    println!("   • select_where! - Select with filter\n");
461
462    println!("📊 Benefits:");
463    println!("   • Less typing (20-45 characters saved per operation)");
464    println!("   • More readable code");
465    println!("   • Common patterns encapsulated");
466    println!("   • Same performance (zero-cost abstraction)");
467    println!("   • Type-safe (compile-time checked)\n");
468
469    println!("💡 When to use:");
470    println!("   • Use macros for simple, common patterns");
471    println!("   • Use full API for complex queries");
472    println!("   • Mix and match as needed\n");
473
474    println!("✓ Macro helpers demo complete!\n");
475}
examples/arc_rwlock_hashmap.rs (line 82)
59fn main() {
60    println!("\n╔══════════════════════════════════════════════════════════════════╗");
61    println!("║  Arc<RwLock<T>> HashMap Lazy Query Demo                         ║");
62    println!("║  Thread-safe shared data with lazy evaluation                   ║");
63    println!("╚══════════════════════════════════════════════════════════════════╝\n");
64
65    let product_map = create_sample_data();
66    println!("Created product catalog:");
67    println!("  Total products: {}", product_map.len());
68    println!("  Keys: {:?}\n", product_map.keys().take(3).collect::<Vec<_>>());
69
70    // Extract products for querying
71    let products = extract_products(&product_map);
72    println!("Extracted {} products from Arc<RwLock<Product>>\n", products.len());
73
74    // ============================================================================
75    // LAZY OPERATION 1: where_ - Lazy Filtering
76    // ============================================================================
77    println!("═══════════════════════════════════════════════════════════════");
78    println!("Lazy Operation 1: where_ (filtering)");
79    println!("═══════════════════════════════════════════════════════════════\n");
80
81    println!("Building filtered query (nothing executes yet)...");
82    let electronics_query = LazyQuery::new(&products)
83        .where_(Product::category_r(), |cat| cat == "Electronics")
84        .where_(Product::active_r(), |&active| active)
85        .where_(Product::stock_r(), |&stock| stock > 20);
86
87    println!("  ✅ Query built (deferred execution)\n");
88
89    println!("Collecting results (executes now)...");
90    let electronics: Vec<_> = electronics_query.collect();
91    println!("  Found {} electronics in stock", electronics.len());
92    for p in &electronics {
93        println!("    • {}: {} in stock", p.name, p.stock);
94    }
95
96    // ============================================================================
97    // LAZY OPERATION 2: select_lazy - Lazy Projection
98    // ============================================================================
99    println!("\n═══════════════════════════════════════════════════════════════");
100    println!("Lazy Operation 2: select_lazy (projection)");
101    println!("═══════════════════════════════════════════════════════════════\n");
102
103    println!("Selecting product names (lazy)...");
104    let names: Vec<String> = LazyQuery::new(&products)
105        .where_(Product::category_r(), |cat| cat == "Furniture")
106        .select_lazy(Product::name_r())
107        .collect();
108
109    println!("  Furniture names ({}):", names.len());
110    for name in &names {
111        println!("    • {}", name);
112    }
113
114    // ============================================================================
115    // LAZY OPERATION 3: take_lazy - Early Termination
116    // ============================================================================
117    println!("\n═══════════════════════════════════════════════════════════════");
118    println!("Lazy Operation 3: take_lazy (early termination)");
119    println!("═══════════════════════════════════════════════════════════════\n");
120
121    println!("Getting first 3 electronics...");
122    let first_3: Vec<_> = LazyQuery::new(&products)
123        .where_(Product::category_r(), |cat| cat == "Electronics")
124        .take_lazy(3)
125        .collect();
126
127    println!("  First 3 electronics:");
128    for (i, p) in first_3.iter().enumerate() {
129        println!("    {}. {} - ${:.2}", i + 1, p.name, p.price);
130    }
131    println!("  ✅ Stopped after finding 3 items!");
132
133    // ============================================================================
134    // LAZY OPERATION 4: skip_lazy - Pagination
135    // ============================================================================
136    println!("\n═══════════════════════════════════════════════════════════════");
137    println!("Lazy Operation 4: skip_lazy (pagination)");
138    println!("═══════════════════════════════════════════════════════════════\n");
139
140    println!("Getting page 2 (skip 3, take 3)...");
141    let page_2: Vec<_> = LazyQuery::new(&products)
142        .where_(Product::active_r(), |&active| active)
143        .skip_lazy(3)
144        .take_lazy(3)
145        .collect();
146
147    println!("  Page 2 items:");
148    for (i, p) in page_2.iter().enumerate() {
149        println!("    {}. {}", i + 4, p.name);
150    }
151
152    // ============================================================================
153    // LAZY OPERATION 5: first - Short-Circuit Search
154    // ============================================================================
155    println!("\n═══════════════════════════════════════════════════════════════");
156    println!("Lazy Operation 5: first (short-circuit)");
157    println!("═══════════════════════════════════════════════════════════════\n");
158
159    println!("Finding first expensive item (>$1000)...");
160    let expensive = LazyQuery::new(&products)
161        .where_(Product::price_r(), |&price| price > 1000.0)
162        .first();
163
164    match expensive {
165        Some(p) => println!("  Found: {} - ${:.2}", p.name, p.price),
166        None => println!("  Not found"),
167    }
168    println!("  ✅ Stopped at first match!");
169
170    // ============================================================================
171    // LAZY OPERATION 6: any - Existence Check
172    // ============================================================================
173    println!("\n═══════════════════════════════════════════════════════════════");
174    println!("Lazy Operation 6: any (existence check)");
175    println!("═══════════════════════════════════════════════════════════════\n");
176
177    println!("Checking if any furniture exists...");
178    let has_furniture = LazyQuery::new(&products)
179        .where_(Product::category_r(), |cat| cat == "Furniture")
180        .any();
181
182    println!("  Has furniture: {}", has_furniture);
183    println!("  ✅ Stopped immediately after finding first match!");
184
185    // ============================================================================
186    // LAZY OPERATION 7: count - Count Matching Items
187    // ============================================================================
188    println!("\n═══════════════════════════════════════════════════════════════");
189    println!("Lazy Operation 7: count");
190    println!("═══════════════════════════════════════════════════════════════\n");
191
192    let electronics_count = LazyQuery::new(&products)
193        .where_(Product::category_r(), |cat| cat == "Electronics")
194        .count();
195
196    println!("  Electronics count: {}", electronics_count);
197
198    // ============================================================================
199    // LAZY OPERATION 8: sum_by - Aggregation
200    // ============================================================================
201    println!("\n═══════════════════════════════════════════════════════════════");
202    println!("Lazy Operation 8: sum_by (aggregation)");
203    println!("═══════════════════════════════════════════════════════════════\n");
204
205    let total_value: f64 = LazyQuery::new(&products)
206        .where_(Product::category_r(), |cat| cat == "Electronics")
207        .sum_by(Product::price_r());
208
209    println!("  Total electronics value: ${:.2}", total_value);
210
211    // ============================================================================
212    // LAZY OPERATION 9: avg_by - Average
213    // ============================================================================
214    println!("\n═══════════════════════════════════════════════════════════════");
215    println!("Lazy Operation 9: avg_by");
216    println!("═══════════════════════════════════════════════════════════════\n");
217
218    let avg_price = LazyQuery::new(&products)
219        .where_(Product::category_r(), |cat| cat == "Furniture")
220        .avg_by(Product::price_r())
221        .unwrap_or(0.0);
222
223    println!("  Average furniture price: ${:.2}", avg_price);
224
225    // ============================================================================
226    // LAZY OPERATION 10: min_by_float / max_by_float
227    // ============================================================================
228    println!("\n═══════════════════════════════════════════════════════════════");
229    println!("Lazy Operation 10: min_by_float / max_by_float");
230    println!("═══════════════════════════════════════════════════════════════\n");
231
232    let min_price = LazyQuery::new(&products)
233        .where_(Product::active_r(), |&active| active)
234        .min_by_float(Product::price_r())
235        .unwrap_or(0.0);
236
237    let max_price = LazyQuery::new(&products)
238        .where_(Product::active_r(), |&active| active)
239        .max_by_float(Product::price_r())
240        .unwrap_or(0.0);
241
242    println!("  Price range for active products:");
243    println!("    Min: ${:.2}", min_price);
244    println!("    Max: ${:.2}", max_price);
245
246    // ============================================================================
247    // LAZY OPERATION 11: find - Find with Predicate
248    // ============================================================================
249    println!("\n═══════════════════════════════════════════════════════════════");
250    println!("Lazy Operation 11: find (with predicate)");
251    println!("═══════════════════════════════════════════════════════════════\n");
252
253    let high_rated = LazyQuery::new(&products)
254        .where_(Product::category_r(), |cat| cat == "Electronics")
255        .find(|item| item.rating > 4.7);
256
257    if let Some(product) = high_rated {
258        println!("  First highly-rated electronic:");
259        println!("    {}: Rating {:.1}", product.name, product.rating);
260    }
261
262    // ============================================================================
263    // LAZY OPERATION 12: for_each - Iteration
264    // ============================================================================
265    println!("\n═══════════════════════════════════════════════════════════════");
266    println!("Lazy Operation 12: for_each (iteration)");
267    println!("═══════════════════════════════════════════════════════════════\n");
268
269    println!("  Low stock alerts:");
270    LazyQuery::new(&products)
271        .where_(Product::stock_r(), |&stock| stock < 20)
272        .for_each(|product| {
273            println!("    ⚠️  {}: Only {} in stock", product.name, product.stock);
274        });
275
276    // ============================================================================
277    // LAZY OPERATION 13: fold - Custom Aggregation
278    // ============================================================================
279    println!("\n═══════════════════════════════════════════════════════════════");
280    println!("Lazy Operation 14: fold (custom aggregation)");
281    println!("═══════════════════════════════════════════════════════════════\n");
282
283    let total_inventory_value = LazyQuery::new(&products)
284        .where_(Product::active_r(), |&active| active)
285        .fold(0.0, |acc, product| {
286            acc + (product.price * product.stock as f64)
287        });
288
289    println!("  Total inventory value: ${:.2}", total_inventory_value);
290
291    // ============================================================================
292    // LAZY OPERATION 14: all_match - Validation
293    // ============================================================================
294    println!("\n═══════════════════════════════════════════════════════════════");
295    println!("Lazy Operation 15: all_match (validation)");
296    println!("═══════════════════════════════════════════════════════════════\n");
297
298    let all_priced = LazyQuery::new(&products)
299        .all_match(|item| item.price > 0.0);
300
301    println!("  All products have valid prices: {}", all_priced);
302
303    // ============================================================================
304    // LAZY OPERATION 15: into_iter - For Loop
305    // ============================================================================
306    println!("\n═══════════════════════════════════════════════════════════════");
307    println!("Lazy Operation 16: into_iter (for loop)");
308    println!("═══════════════════════════════════════════════════════════════\n");
309
310    println!("  High-value products (>$300):");
311    for product in LazyQuery::new(&products)
312        .where_(Product::price_r(), |&p| p > 300.0)
313        .take_lazy(5)
314    {
315        println!("    • {}: ${:.2}", product.name, product.price);
316    }
317
318    // ============================================================================
319    // LAZY OPERATION 16: map_items - Transform
320    // ============================================================================
321    println!("\n═══════════════════════════════════════════════════════════════");
322    println!("Lazy Operation 17: map_items (transformation)");
323    println!("═══════════════════════════════════════════════════════════════\n");
324
325    let price_tags: Vec<String> = LazyQuery::new(&products)
326        .where_(Product::category_r(), |cat| cat == "Electronics")
327        .map_items(|p| format!("{}: ${:.2}", p.name, p.price))
328        .take(5)
329        .collect();
330
331    println!("  Electronics price tags:");
332    for tag in &price_tags {
333        println!("    • {}", tag);
334    }
335
336    // ============================================================================
337    // COMPLEX EXAMPLE: Multi-Stage Lazy Pipeline
338    // ============================================================================
339    println!("\n═══════════════════════════════════════════════════════════════");
340    println!("Complex Example: Multi-stage lazy pipeline");
341    println!("═══════════════════════════════════════════════════════════════\n");
342
343    println!("Building complex query:");
344    println!("  1. Filter by category (Electronics)");
345    println!("  2. Filter by price range ($50-$500)");
346    println!("  3. Filter by rating (>4.5)");
347    println!("  4. Select names");
348    println!("  5. Take first 3");
349    println!();
350
351    let results: Vec<String> = LazyQuery::new(&products)
352        .where_(Product::category_r(), |cat| cat == "Electronics")
353        .where_(Product::price_r(), |&p| p >= 50.0 && p <= 500.0)
354        .where_(Product::rating_r(), |&r| r > 4.5)
355        .select_lazy(Product::name_r())
356        .take(3)
357        .collect();
358
359    println!("  Results:");
360    for (i, name) in results.iter().enumerate() {
361        println!("    {}. {}", i + 1, name);
362    }
363    println!("  ✅ All operations fused and executed lazily!");
364
365    // ============================================================================
366    // THREAD-SAFE UPDATES WITH RWLOCK
367    // ============================================================================
368    println!("\n═══════════════════════════════════════════════════════════════");
369    println!("Bonus: Thread-safe updates with RwLock");
370    println!("═══════════════════════════════════════════════════════════════\n");
371
372    // Update a product through the Arc<RwLock>
373    if let Some(product_arc) = product_map.get("PROD-002") {
374        println!("Updating PROD-002 stock...");
375        
376        // Write lock for mutation
377        if let Ok(mut product) = product_arc.write() {
378            let old_stock = product.stock;
379            product.stock = 25;
380            println!("  Stock updated: {} → {}", old_stock, product.stock);
381        }
382    }
383
384    // Query again to see the update
385    let updated_products = extract_products(&product_map);
386    let mouse = LazyQuery::new(&updated_products)
387        .find(|p| p.id == 2);
388
389    if let Some(product) = mouse {
390        println!("  Verified update: {} now has {} in stock", product.name, product.stock);
391    }
392
393    // ============================================================================
394    // PRACTICAL EXAMPLE: Price Analysis by Category
395    // ============================================================================
396    println!("\n═══════════════════════════════════════════════════════════════");
397    println!("Practical Example: Price analysis by category");
398    println!("═══════════════════════════════════════════════════════════════\n");
399
400    let categories = vec!["Electronics", "Furniture"];
401
402    for category in categories {
403        println!("  {} Statistics:", category);
404        
405        // Filter products by category first
406        let cat_products: Vec<Product> = products.iter()
407            .filter(|p| p.category == category)
408            .cloned()
409            .collect();
410
411        let count = LazyQuery::new(&cat_products).count();
412        let total = LazyQuery::new(&cat_products).sum_by(Product::price_r());
413        let avg = LazyQuery::new(&cat_products).avg_by(Product::price_r()).unwrap_or(0.0);
414        let min = LazyQuery::new(&cat_products).min_by_float(Product::price_r()).unwrap_or(0.0);
415        let max = LazyQuery::new(&cat_products).max_by_float(Product::price_r()).unwrap_or(0.0);
416
417        println!("    Count: {}", count);
418        println!("    Total: ${:.2}", total);
419        println!("    Average: ${:.2}", avg);
420        println!("    Range: ${:.2} - ${:.2}\n", min, max);
421    }
422
423    // ============================================================================
424    // COMBINING WITH HASHMAP OPERATIONS
425    // ============================================================================
426    println!("═══════════════════════════════════════════════════════════════");
427    println!("HashMap Integration: Query by key patterns");
428    println!("═══════════════════════════════════════════════════════════════\n");
429
430    // Filter HashMap by key pattern
431    let electronics_keys: Vec<String> = product_map
432        .iter()
433        .filter(|(_key, value)| {
434            // Read the value to check category
435            if let Ok(guard) = value.read() {
436                guard.category == "Electronics"
437            } else {
438                false
439            }
440        })
441        .map(|(key, _value)| key.clone())
442        .collect();
443
444    println!("  Electronics product IDs:");
445    for key in electronics_keys.iter().take(5) {
446        println!("    • {}", key);
447    }
448
449    // ============================================================================
450    // PERFORMANCE DEMONSTRATION
451    // ============================================================================
452    println!("\n═══════════════════════════════════════════════════════════════");
453    println!("Performance: Lazy vs Eager comparison");
454    println!("═══════════════════════════════════════════════════════════════\n");
455
456    println!("Scenario: Find first product with rating > 4.7 from {} products\n", products.len());
457
458    println!("  Eager approach (hypothetical):");
459    println!("    - Filter all {} products", products.len());
460    println!("    - Collect filtered results");
461    println!("    - Take first item");
462    println!("    - Wasted work: Check all items\n");
463
464    println!("  Lazy approach (actual):");
465    let _first_rated = LazyQuery::new(&products)
466        .where_(Product::rating_r(), |&r| r > 4.7)
467        .first();
468    println!("    - Starts checking products");
469    println!("    - Stops at first match");
470    println!("    - ✅ Early termination - checks ~3-5 items only!");
471
472    // ============================================================================
473    // Summary
474    // ============================================================================
475    println!("\n╔══════════════════════════════════════════════════════════════════╗");
476    println!("║  Summary: All Lazy Operations Demonstrated                      ║");
477    println!("╚══════════════════════════════════════════════════════════════════╝\n");
478
479    println!("✅ Lazy Query Operations:");
480    println!("   1. ✅ where_ - Lazy filtering");
481    println!("   2. ✅ select_lazy - Lazy projection");
482    println!("   3. ✅ take_lazy - Early termination");
483    println!("   4. ✅ skip_lazy - Pagination");
484    println!("   5. ✅ first - Short-circuit search");
485    println!("   6. ✅ any - Existence check (short-circuit)");
486    println!("   7. ✅ count - Count items");
487    println!("   8. ✅ sum_by - Sum aggregation");
488    println!("   9. ✅ avg_by - Average aggregation");
489    println!("   10. ✅ min_by_float - Minimum value");
490    println!("   11. ✅ max_by_float - Maximum value");
491    println!("   12. ✅ find - Find with predicate (short-circuit)");
492    println!("   13. ✅ for_each - Iteration");
493    println!("   14. ✅ fold - Custom aggregation");
494    println!("   15. ✅ all_match - Validation (short-circuit)");
495    println!("   16. ✅ into_iter - For loop support");
496    println!("   17. ✅ map_items - Transformation\n");
497
498    println!("✅ Arc<RwLock<T>> Benefits:");
499    println!("   • Thread-safe shared access");
500    println!("   • Interior mutability");
501    println!("   • Multiple readers, single writer");
502    println!("   • Reference counting (Arc)");
503    println!("   • Can be queried after extracting data\n");
504
505    println!("✅ HashMap<K, Arc<RwLock<V>>> Benefits:");
506    println!("   • Fast key-based lookup");
507    println!("   • Thread-safe value access");
508    println!("   • Can query all values");
509    println!("   • Can filter by key patterns");
510    println!("   • Perfect for shared state/caches\n");
511
512    println!("🎯 Use Cases:");
513    println!("   • Shared product catalogs");
514    println!("   • User session stores");
515    println!("   • Configuration caches");
516    println!("   • Real-time inventory systems");
517    println!("   • Multi-threaded data processing");
518    println!("   • Web server state management\n");
519
520    println!("✓ Arc<RwLock<T>> HashMap with all lazy operations demo complete!\n");
521}
Source§

impl<'a, T, I> LazyQuery<'a, T, I>
where T: 'static, 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/individual_crates.rs (line 102)
27fn main() {
28    println!("Individual Crates Example");
29    println!("=========================\n");
30    println!("Using rust-queries-core + rust-queries-derive directly\n");
31
32    let products = vec![
33        Product {
34            id: 1,
35            name: "Laptop".to_string(),
36            price: 999.99,
37            category: "Electronics".to_string(),
38            stock: 5,
39        },
40        Product {
41            id: 2,
42            name: "Mouse".to_string(),
43            price: 29.99,
44            category: "Electronics".to_string(),
45            stock: 50,
46        },
47        Product {
48            id: 3,
49            name: "Keyboard".to_string(),
50            price: 79.99,
51            category: "Electronics".to_string(),
52            stock: 30,
53        },
54        Product {
55            id: 4,
56            name: "Monitor".to_string(),
57            price: 299.99,
58            category: "Electronics".to_string(),
59            stock: 12,
60        },
61        Product {
62            id: 5,
63            name: "Desk Chair".to_string(),
64            price: 199.99,
65            category: "Furniture".to_string(),
66            stock: 8,
67        },
68    ];
69
70    println!("1. QueryExt from rust_queries_core");
71    println!("   products.query().where_(price > 100).all()");
72    
73    let query = products
74        .query()  // From QueryExt trait
75        .where_(Product::price_r(), |&p| p > 100.0);
76    let expensive = query.all();
77    
78    println!("   Found {} expensive products:", expensive.len());
79    for product in expensive {
80        println!("   - {} (${:.2})", product.name, product.price);
81    }
82    println!();
83
84    println!("2. QueryBuilder from rust_queries_derive");
85    println!("   Product::query(&products).where_(stock < 10).all()");
86    
87    let query2 = Product::query(&products)  // From QueryBuilder derive
88        .where_(Product::stock_r(), |&s| s < 10);
89    let low_stock = query2.all();
90    
91    println!("   Found {} low stock products:", low_stock.len());
92    for product in low_stock {
93        println!("   - {} (stock: {})", product.name, product.stock);
94    }
95    println!();
96
97    println!("3. LazyQuery from rust_queries_core");
98    println!("   products.lazy_query().where_(...).collect()");
99    
100    let electronics: Vec<_> = products
101        .lazy_query()  // From QueryExt trait
102        .where_(Product::category_r(), |cat| cat == "Electronics")
103        .collect();
104    
105    println!("   Found {} electronics:", electronics.len());
106    for product in electronics {
107        println!("   - {}", product.name);
108    }
109    println!();
110
111    println!("4. Aggregations with LazyQuery");
112    println!("   products.lazy_query().sum_by(Product::price_r())");
113    
114    let total_value: f64 = products
115        .lazy_query()
116        .sum_by(Product::price_r());
117    
118    println!("   Total inventory value: ${:.2}", total_value);
119    println!();
120
121    println!("5. Early termination with lazy queries");
122    println!("   products.lazy_query().where_(...).first()");
123    
124    if let Some(first_cheap) = products
125        .lazy_query()
126        .where_(Product::price_r(), |&p| p < 50.0)
127        .first()
128    {
129        println!("   First cheap product: {} (${:.2})", first_cheap.name, first_cheap.price);
130    }
131    println!();
132
133    println!("6. Using Query (eager) from rust_queries_core");
134    println!("   Query::new(&products).where_(...).count()");
135    
136    let query3 = Query::new(&products)  // Traditional approach
137        .where_(Product::price_r(), |&p| p > 50.0);
138    let count = query3.count();
139    
140    println!("   Products over $50: {}", count);
141    println!();
142
143    println!("Summary:");
144    println!("--------");
145    println!("✓ rust_queries_core provides: Query, LazyQuery, QueryExt");
146    println!("✓ rust_queries_derive provides: #[derive(QueryBuilder)]");
147    println!("✓ key_paths_derive provides: #[derive(Keypaths)]");
148    println!("✓ All features work with individual crates!");
149}
More examples
Hide additional examples
examples/derive_and_ext.rs (line 74)
13fn main() {
14    println!("Derive Macros and Extension Traits Example");
15    println!("===========================================\n");
16
17    let products = vec![
18        Product {
19            id: 1,
20            name: "Laptop".to_string(),
21            price: 999.99,
22            category: "Electronics".to_string(),
23            stock: 5,
24        },
25        Product {
26            id: 2,
27            name: "Mouse".to_string(),
28            price: 29.99,
29            category: "Electronics".to_string(),
30            stock: 50,
31        },
32        Product {
33            id: 3,
34            name: "Keyboard".to_string(),
35            price: 79.99,
36            category: "Electronics".to_string(),
37            stock: 30,
38        },
39        Product {
40            id: 4,
41            name: "Monitor".to_string(),
42            price: 299.99,
43            category: "Electronics".to_string(),
44            stock: 12,
45        },
46        Product {
47            id: 5,
48            name: "Desk Chair".to_string(),
49            price: 199.99,
50            category: "Furniture".to_string(),
51            stock: 8,
52        },
53    ];
54
55    println!("1. Using Extension Trait - Direct .query() on Vec");
56    println!("   Query: products.query().where_(price > 100).all()");
57    
58    let query = products
59        .query()
60        .where_(Product::price_r(), |&p| p > 100.0);
61    let expensive = query.all();
62    
63    println!("   Found {} expensive products:", expensive.len());
64    for product in &expensive {
65        println!("   - {} (${:.2})", product.name, product.price);
66    }
67    println!();
68
69    println!("2. Using Extension Trait - Direct .lazy_query() on Vec");
70    println!("   Query: products.lazy_query().where_(stock < 10).collect()");
71    
72    let low_stock: Vec<_> = products
73        .lazy_query()
74        .where_(Product::stock_r(), |&s| s < 10)
75        .collect();
76    
77    println!("   Found {} low stock products:", low_stock.len());
78    for product in &low_stock {
79        println!("   - {} (stock: {})", product.name, product.stock);
80    }
81    println!();
82
83    println!("3. Using Extension Trait - Chained Operations");
84    println!("   Query: products.lazy_query().where_(category == Electronics).take(2).select(name).collect()");
85    
86    let names: Vec<String> = products
87        .lazy_query()
88        .where_(Product::category_r(), |cat| cat == "Electronics")
89        .take_lazy(2)
90        .select_lazy(Product::name_r())
91        .collect();
92    
93    println!("   First 2 electronics:");
94    for name in &names {
95        println!("   - {}", name);
96    }
97    println!();
98
99    println!("4. Using QueryBuilder Derive - Static Methods");
100    println!("   Query: Product::query(&products).where_(price > 50).count()");
101    
102    let query4 = Product::query(&products)
103        .where_(Product::price_r(), |&p| p > 50.0);
104    let count = query4.count();
105    
106    println!("   Products over $50: {}", count);
107    println!();
108
109    println!("5. Using QueryBuilder Derive - Lazy Static Methods");
110    println!("   Query: Product::lazy_query(&products).first()");
111    
112    if let Some(first) = Product::lazy_query(&products).first() {
113        println!("   First product: {} (${:.2})", first.name, first.price);
114    }
115    println!();
116
117    println!("6. Complex Chain with Extension Trait");
118    println!("   Query: products.lazy_query()");
119    println!("          .where_(category == Electronics)");
120    println!("          .where_(price < 500)");
121    println!("          .map(|p| format!(\"{{}} - ${{:.2}}\", p.name, p.price))");
122    println!("          .collect()");
123    
124    let formatted: Vec<String> = products
125        .lazy_query()
126        .where_(Product::category_r(), |cat| cat == "Electronics")
127        .where_(Product::price_r(), |&p| p < 500.0)
128        .map_items(|p| format!("{} - ${:.2}", p.name, p.price))
129        .collect();
130    
131    println!("   Affordable electronics:");
132    for item in &formatted {
133        println!("   - {}", item);
134    }
135    println!();
136
137    println!("7. Aggregation with Extension Trait");
138    println!("   Query: products.lazy_query().sum_by(Product::stock())");
139    
140    let total_stock = products
141        .lazy_query()
142        .sum_by(Product::stock_r());
143    
144    println!("   Total stock across all products: {}", total_stock);
145    println!();
146
147    println!("8. Find with Extension Trait");
148    println!("   Query: products.lazy_query().find(|p| p.name.contains(\"Chair\"))");
149    
150    if let Some(chair) = products.lazy_query().find(|p| p.name.contains("Chair")) {
151        println!("   Found: {} in {}", chair.name, chair.category);
152    }
153    println!();
154
155    println!("9. Early Termination with Extension Trait");
156    println!("   Query: products.lazy_query().where_(price > 1000).any()");
157    
158    let has_luxury = products
159        .lazy_query()
160        .where_(Product::price_r(), |&p| p > 1000.0)
161        .any();
162    
163    println!("   Has products over $1000: {}", has_luxury);
164    println!();
165
166    println!("10. Slice Extension Trait");
167    println!("    Query: (&products[..]).lazy_query().count()");
168    
169    let slice_count = (&products[..])
170        .lazy_query()
171        .count();
172    
173    println!("    Count from slice: {}", slice_count);
174    println!();
175
176    println!("Summary:");
177    println!("--------");
178    println!("✓ Extension trait QueryExt adds .query() and .lazy_query() to containers");
179    println!("✓ Derive macro QueryBuilder adds static methods Product::query() and Product::lazy_query()");
180    println!("✓ Both approaches provide the same query functionality");
181    println!("✓ Extension trait is more ergonomic: products.query() vs Query::new(&products)");
182    println!("✓ All iterator optimizations (fusion, early termination) still apply");
183}
examples/container_support.rs (line 53)
26fn main() {
27    println!("\n╔════════════════════════════════════════════════════════════════╗");
28    println!("║  Container Support Demo                                       ║");
29    println!("║  Query various collection types                               ║");
30    println!("╚════════════════════════════════════════════════════════════════╝\n");
31
32    // ============================================================================
33    // CONTAINER 1: Vec<T>
34    // ============================================================================
35    println!("═══════════════════════════════════════════════════════════════");
36    println!("Container 1: Vec<T>");
37    println!("═══════════════════════════════════════════════════════════════\n");
38
39    let vec_products = vec![
40        create_sample_product(1, "Laptop", 999, "Electronics"),
41        create_sample_product(2, "Mouse", 29, "Electronics"),
42        create_sample_product(3, "Desk", 299, "Furniture"),
43    ];
44
45    // Query Vec directly
46    let vec_query = Query::new(&vec_products)
47        .where_(Product::category_r(), |cat| cat == "Electronics");
48    let vec_results = vec_query.all();
49    println!("  Vec: Found {} electronics", vec_results.len());
50
51    // Lazy query on Vec
52    let lazy_count = LazyQuery::new(&vec_products)
53        .where_(Product::price_r(), |&p| p < 100)
54        .count();
55    println!("  Vec (lazy): {} items under $100", lazy_count);
56
57    // ============================================================================
58    // CONTAINER 2: VecDeque<T>
59    // ============================================================================
60    println!("\n═══════════════════════════════════════════════════════════════");
61    println!("Container 2: VecDeque<T>");
62    println!("═══════════════════════════════════════════════════════════════\n");
63
64    let mut deque_products = VecDeque::new();
65    deque_products.push_back(create_sample_product(1, "Keyboard", 129, "Electronics"));
66    deque_products.push_back(create_sample_product(2, "Monitor", 349, "Electronics"));
67    deque_products.push_back(create_sample_product(3, "Chair", 199, "Furniture"));
68
69    // Convert to owned Vec for querying
70    let deque_vec: Vec<Product> = deque_products.iter().cloned().collect();
71    let deque_query = Query::new(&deque_vec);
72    let deque_count = deque_query.count();
73    println!("  VecDeque: {} total items", deque_count);
74
75    // More efficient: use make_contiguous for zero-copy slice access
76    let contiguous = deque_products.make_contiguous();
77    let contiguous_query = Query::new(contiguous);
78    println!("  VecDeque (zero-copy): {} items", contiguous_query.count());
79
80    // ============================================================================
81    // CONTAINER 3: HashSet<T>
82    // ============================================================================
83    println!("\n═══════════════════════════════════════════════════════════════");
84    println!("Container 3: HashSet<T>");
85    println!("═══════════════════════════════════════════════════════════════\n");
86
87    let mut set_products = HashSet::new();
88    set_products.insert(create_sample_product(1, "Tablet", 499, "Electronics"));
89    set_products.insert(create_sample_product(2, "Phone", 799, "Electronics"));
90    set_products.insert(create_sample_product(3, "Lamp", 39, "Furniture"));
91
92    // Collect from HashSet to Vec for querying
93    let set_vec: Vec<Product> = set_products.iter().cloned().collect();
94    let set_query = Query::new(&set_vec)
95        .where_(Product::price_r(), |&p| p > 500);
96    let expensive = set_query.all();
97    println!("  HashSet: {} expensive items", expensive.len());
98
99    // Lazy on HashSet (convert to owned Vec first)
100    let set_owned: Vec<Product> = set_products.iter().cloned().collect();
101    let lazy_set: Vec<_> = LazyQuery::new(&set_owned)
102        .where_(Product::category_r(), |cat| cat == "Electronics")
103        .collect();
104    println!("  HashSet (lazy): {} electronics", lazy_set.len());
105
106    // ============================================================================
107    // CONTAINER 4: BTreeSet<T>
108    // ============================================================================
109    println!("\n═══════════════════════════════════════════════════════════════");
110    println!("Container 4: BTreeSet<T>");
111    println!("═══════════════════════════════════════════════════════════════\n");
112
113    let mut btree_set = BTreeSet::new();
114    btree_set.insert(create_sample_product(1, "Webcam", 79, "Electronics"));
115    btree_set.insert(create_sample_product(2, "Microphone", 129, "Electronics"));
116    btree_set.insert(create_sample_product(3, "Bookshelf", 149, "Furniture"));
117
118    let btree_vec: Vec<Product> = btree_set.iter().cloned().collect();
119    let btree_query = Query::new(&btree_vec);
120    println!("  BTreeSet: {} total items (sorted order!)", btree_query.count());
121    
122    // BTreeSet items are in sorted order
123    for (i, item) in btree_vec.iter().take(3).enumerate() {
124        println!("    {}. {} (ID: {})", i + 1, item.name, item.id);
125    }
126
127    // ============================================================================
128    // CONTAINER 5: HashMap<K, V> - Query Values
129    // ============================================================================
130    println!("\n═══════════════════════════════════════════════════════════════");
131    println!("Container 5: HashMap<K, V> - Querying values");
132    println!("═══════════════════════════════════════════════════════════════\n");
133
134    let mut map_products = HashMap::new();
135    map_products.insert("prod1", create_sample_product(1, "Speaker", 199, "Electronics"));
136    map_products.insert("prod2", create_sample_product(2, "Headphones", 149, "Electronics"));
137    map_products.insert("prod3", create_sample_product(3, "Ottoman", 249, "Furniture"));
138
139    // Query HashMap values (convert to owned Vec)
140    let map_vec: Vec<Product> = map_products.values().cloned().collect();
141    let map_query = Query::new(&map_vec)
142        .where_(Product::category_r(), |cat| cat == "Electronics");
143    let electronics = map_query.all();
144    println!("  HashMap: {} electronics", electronics.len());
145
146    // ============================================================================
147    // CONTAINER 6: BTreeMap<K, V> - Query Values
148    // ============================================================================
149    println!("\n═══════════════════════════════════════════════════════════════");
150    println!("Container 6: BTreeMap<K, V> - Querying values");
151    println!("═══════════════════════════════════════════════════════════════\n");
152
153    let mut btree_map = BTreeMap::new();
154    btree_map.insert(1, create_sample_product(1, "Router", 89, "Electronics"));
155    btree_map.insert(2, create_sample_product(2, "Switch", 129, "Electronics"));
156    btree_map.insert(3, create_sample_product(3, "Sofa", 899, "Furniture"));
157
158    let btree_map_vec: Vec<Product> = btree_map.values().cloned().collect();
159    let btree_map_query = Query::new(&btree_map_vec);
160    let avg_price = btree_map_query.sum(Product::price_r()) as f64 / btree_map.len() as f64;
161    println!("  BTreeMap: Average price ${:.2}", avg_price);
162
163    // ============================================================================
164    // CONTAINER 7: Arrays [T; N]
165    // ============================================================================
166    println!("\n═══════════════════════════════════════════════════════════════");
167    println!("Container 7: Arrays [T; N]");
168    println!("═══════════════════════════════════════════════════════════════\n");
169
170    let array_products = [
171        create_sample_product(1, "USB Cable", 15, "Electronics"),
172        create_sample_product(2, "HDMI Cable", 25, "Electronics"),
173        create_sample_product(3, "Power Strip", 35, "Electronics"),
174    ];
175
176    // Query array directly (as slice)
177    let array_query = Query::new(&array_products);
178    let total = array_query.sum(Product::price_r());
179    println!("  Array: Total value ${}", total);
180
181    // Lazy on array
182    let lazy_array: Vec<_> = LazyQuery::new(&array_products)
183        .where_(Product::price_r(), |&p| p > 20)
184        .collect();
185    println!("  Array (lazy): {} items over $20", lazy_array.len());
186
187    // ============================================================================
188    // CONTAINER 8: LinkedList<T>
189    // ============================================================================
190    println!("\n═══════════════════════════════════════════════════════════════");
191    println!("Container 8: LinkedList<T>");
192    println!("═══════════════════════════════════════════════════════════════\n");
193
194    let mut list_products = LinkedList::new();
195    list_products.push_back(create_sample_product(1, "SSD", 159, "Electronics"));
196    list_products.push_back(create_sample_product(2, "HDD", 79, "Electronics"));
197
198    let list_vec: Vec<Product> = list_products.iter().cloned().collect();
199    let list_query = Query::new(&list_vec);
200    println!("  LinkedList: {} items", list_query.count());
201
202    // ============================================================================
203    // CONTAINER 9: Option<T> and Result<T, E>
204    // ============================================================================
205    println!("\n═══════════════════════════════════════════════════════════════");
206    println!("Container 9: Option<T> and Result<T, E>");
207    println!("═══════════════════════════════════════════════════════════════\n");
208
209    let maybe_product = Some(create_sample_product(1, "Mystery Box", 99, "Special"));
210    
211    if let Some(ref product) = maybe_product {
212        let option_query = Query::new(std::slice::from_ref(product));
213        println!("  Option (Some): {} items", option_query.count());
214    }
215
216    let none_product: Option<Product> = None;
217    let none_count = none_product.iter().count();
218    println!("  Option (None): {} items", none_count);
219
220    // ============================================================================
221    // Summary
222    // ============================================================================
223    println!("\n╔════════════════════════════════════════════════════════════════╗");
224    println!("║  Supported Containers Summary                                  ║");
225    println!("╚════════════════════════════════════════════════════════════════╝\n");
226
227    println!("✅ Supported container types:");
228    println!("   • Vec<T>              - Standard vector");
229    println!("   • &[T]                - Slices");
230    println!("   • [T; N]              - Fixed-size arrays");
231    println!("   • VecDeque<T>         - Double-ended queue");
232    println!("   • LinkedList<T>       - Doubly-linked list");
233    println!("   • HashSet<T>          - Unordered set");
234    println!("   • BTreeSet<T>         - Ordered set");
235    println!("   • HashMap<K, V>       - Query values");
236    println!("   • BTreeMap<K, V>      - Query values (sorted)");
237    println!("   • Option<T>           - 0 or 1 item");
238    println!("   • Result<T, E>        - 0 or 1 item\n");
239
240    println!("📝 Usage patterns:");
241    println!("   • Direct: Query::new(&container) for Vec, slices, arrays");
242    println!("   • Convert: Collect to Vec for Sets and Maps");
243    println!("   • Lazy: LazyQuery::new(&slice) for any slice\n");
244
245    println!("💡 Tips:");
246    println!("   • Vec/slice: Direct support, most efficient");
247    println!("   • Sets: Iterate to Vec, then query");
248    println!("   • Maps: Use .values().collect() to query values");
249    println!("   • VecDeque: Use .as_slices() for zero-copy");
250    println!("   • For custom types: Implement Queryable trait\n");
251
252    println!("✓ Container support demo complete!\n");
253}
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}
examples/custom_queryable.rs (line 400)
230fn main() {
231    println!("\n╔════════════════════════════════════════════════════════════════╗");
232    println!("║  Custom Queryable Implementation Demo                         ║");
233    println!("╚════════════════════════════════════════════════════════════════╝\n");
234
235    // ============================================================================
236    // DEMO 1: PaginatedCollection
237    // ============================================================================
238    println!("═══════════════════════════════════════════════════════════════");
239    println!("Demo 1: PaginatedCollection (custom container)");
240    println!("═══════════════════════════════════════════════════════════════\n");
241
242    let mut paginated = PaginatedCollection::new(3); // 3 items per page
243    
244    paginated.add(create_sample_product(1, "Laptop", 999.0, "Electronics", true));
245    paginated.add(create_sample_product(2, "Mouse", 29.0, "Electronics", true));
246    paginated.add(create_sample_product(3, "Keyboard", 129.0, "Electronics", true));
247    paginated.add(create_sample_product(4, "Desk", 299.0, "Furniture", true));
248    paginated.add(create_sample_product(5, "Chair", 199.0, "Furniture", false));
249
250    println!("  Created paginated collection:");
251    println!("    Total items: {}", paginated.total_items());
252    println!("    Pages: {}", paginated.pages.len());
253
254    // Now we can query it using the Queryable trait!
255    // Collect to owned Vec for querying
256    let items: Vec<Product> = paginated.query_iter().cloned().collect();
257    let query = Query::new(&items)
258        .where_(Product::category_r(), |cat| cat == "Electronics");
259    let electronics = query.all();
260    
261    println!("\n  Querying paginated collection:");
262    println!("    Electronics found: {}", electronics.len());
263    for product in electronics {
264        println!("      • {}: ${:.2}", product.name, product.price);
265    }
266
267    // ============================================================================
268    // DEMO 2: CircularBuffer
269    // ============================================================================
270    println!("\n═══════════════════════════════════════════════════════════════");
271    println!("Demo 2: CircularBuffer (fixed capacity)");
272    println!("═══════════════════════════════════════════════════════════════\n");
273
274    let mut circular = CircularBuffer::new(3); // Capacity: 3
275    
276    circular.push(create_sample_product(1, "Product 1", 100.0, "A", true));
277    circular.push(create_sample_product(2, "Product 2", 200.0, "B", true));
278    circular.push(create_sample_product(3, "Product 3", 300.0, "C", true));
279    circular.push(create_sample_product(4, "Product 4", 400.0, "D", true)); // Pushes out Product 1
280
281    println!("  Circular buffer (capacity 3, added 4 items):");
282    println!("    Current size: {}", circular.len());
283
284    // Query the circular buffer
285    let circ_items: Vec<Product> = circular.query_iter().cloned().collect();
286    let circ_query = Query::new(&circ_items);
287    let avg_price = circ_query.avg(Product::price_r()).unwrap_or(0.0);
288    
289    println!("\n  Querying circular buffer:");
290    println!("    Average price: ${:.2}", avg_price);
291    println!("    Items:");
292    for (i, product) in circ_items.iter().enumerate() {
293        println!("      {}. {}: ${:.2}", i + 1, product.name, product.price);
294    }
295
296    // ============================================================================
297    // DEMO 3: FilteredStorage
298    // ============================================================================
299    println!("\n═══════════════════════════════════════════════════════════════");
300    println!("Demo 3: FilteredStorage (auto-filtering container)");
301    println!("═══════════════════════════════════════════════════════════════\n");
302
303    let mut filtered = FilteredStorage::new(|p: &Product| p.price < 200.0);
304    
305    println!("  FilteredStorage (only accepts items < $200):");
306    println!("    Adding Laptop ($999): {}", filtered.add(create_sample_product(1, "Laptop", 999.0, "Electronics", true)));
307    println!("    Adding Mouse ($29): {}", filtered.add(create_sample_product(2, "Mouse", 29.0, "Electronics", true)));
308    println!("    Adding Keyboard ($129): {}", filtered.add(create_sample_product(3, "Keyboard", 129.0, "Electronics", true)));
309    println!("    Total stored: {}", filtered.len());
310
311    // Query the filtered storage
312    let filt_items: Vec<Product> = filtered.query_iter().cloned().collect();
313    let filt_query = Query::new(&filt_items)
314        .where_(Product::in_stock_r(), |&v| v);
315    let in_stock = filt_query.all();
316    
317    println!("\n  Querying filtered storage:");
318    println!("    In stock items: {}", in_stock.len());
319
320    // ============================================================================
321    // DEMO 4: CategoryIndex
322    // ============================================================================
323    println!("\n═══════════════════════════════════════════════════════════════");
324    println!("Demo 4: CategoryIndex (indexed by category)");
325    println!("═══════════════════════════════════════════════════════════════\n");
326
327    let mut category_index = CategoryIndex::new();
328    
329    category_index.add("Electronics".to_string(), create_sample_product(1, "Monitor", 349.0, "Electronics", true));
330    category_index.add("Electronics".to_string(), create_sample_product(2, "Webcam", 79.0, "Electronics", true));
331    category_index.add("Furniture".to_string(), create_sample_product(3, "Desk", 299.0, "Furniture", true));
332    category_index.add("Furniture".to_string(), create_sample_product(4, "Lamp", 39.0, "Furniture", true));
333
334    println!("  CategoryIndex:");
335    println!("    Categories: {:?}", category_index.categories());
336    println!("    Total items: {}", category_index.total_items());
337
338    // Query across all categories
339    let idx_items: Vec<Product> = category_index.query_iter().cloned().collect();
340    let idx_query = Query::new(&idx_items);
341    let expensive = idx_query
342        .where_(Product::price_r(), |&p| p > 100.0);
343    let expensive_items = expensive.all();
344    
345    println!("\n  Querying category index:");
346    println!("    Expensive items (>$100): {}", expensive_items.len());
347    for product in expensive_items {
348        println!("      • {}: ${:.2} ({})", product.name, product.price, product.category);
349    }
350
351    // ============================================================================
352    // DEMO 5: LazyLoader
353    // ============================================================================
354    println!("\n═══════════════════════════════════════════════════════════════");
355    println!("Demo 5: LazyLoader (simulated lazy loading)");
356    println!("═══════════════════════════════════════════════════════════════\n");
357
358    let loader = LazyLoader::new(vec![
359        create_sample_product(1, "Item 1", 50.0, "A", true),
360        create_sample_product(2, "Item 2", 150.0, "B", true),
361        create_sample_product(3, "Item 3", 250.0, "C", true),
362    ]);
363
364    println!("  LazyLoader:");
365    println!("    Total available: {}", loader.total_count());
366    println!("    Currently loaded: {}", loader.loaded_count());
367
368    // Query loaded items
369    let loader_items: Vec<Product> = loader.query_iter().cloned().collect();
370    let loader_query = Query::new(&loader_items);
371    let total_value = loader_query.sum(Product::price_r());
372    
373    println!("\n  Querying lazy loader:");
374    println!("    Total value: ${:.2}", total_value);
375
376    // ============================================================================
377    // DEMO 6: Custom Container with LazyQuery
378    // ============================================================================
379    println!("\n═══════════════════════════════════════════════════════════════");
380    println!("Demo 6: Using LazyQuery with custom containers");
381    println!("═══════════════════════════════════════════════════════════════\n");
382
383    let mut circular = CircularBuffer::new(5);
384    for i in 1..=10 {
385        circular.push(create_sample_product(
386            i,
387            &format!("Product {}", i),
388            i as f64 * 50.0,
389            if i % 2 == 0 { "Even" } else { "Odd" },
390            true,
391        ));
392    }
393
394    println!("  Circular buffer (capacity 5, added 10 items):");
395    println!("    Current size: {}", circular.len());
396
397    // Use LazyQuery for early termination!
398    let circ_vec: Vec<Product> = circular.query_iter().cloned().collect();
399    let first_expensive = LazyQuery::new(&circ_vec)
400        .where_(Product::price_r(), |&p| p > 300.0)
401        .first();
402
403    if let Some(product) = first_expensive {
404        println!("\n  First expensive item (lazy query):");
405        println!("    {}: ${:.2}", product.name, product.price);
406    }
407
408    // ============================================================================
409    // DEMO 7: Implementing Queryable for Wrapper Types
410    // ============================================================================
411    println!("\n═══════════════════════════════════════════════════════════════");
412    println!("Demo 7: Queryable for wrapper types");
413    println!("═══════════════════════════════════════════════════════════════\n");
414
415    /// A simple wrapper around Vec with metadata
416    struct VersionedCollection<T> {
417        items: Vec<T>,
418        version: u32,
419        last_modified: String,
420    }
421
422    impl<T> Queryable<T> for VersionedCollection<T> {
423        fn query_iter(&self) -> Box<dyn Iterator<Item = &T> + '_> {
424            Box::new(self.items.iter())
425        }
426    }
427
428    let versioned = VersionedCollection {
429        items: vec![
430            create_sample_product(1, "V1 Product", 99.0, "Test", true),
431            create_sample_product(2, "V2 Product", 199.0, "Test", true),
432        ],
433        version: 2,
434        last_modified: "2025-10-11".to_string(),
435    };
436
437    println!("  VersionedCollection:");
438    println!("    Version: {}", versioned.version);
439    println!("    Last modified: {}", versioned.last_modified);
440
441    let versioned_items: Vec<Product> = versioned.query_iter().cloned().collect();
442    let query = Query::new(&versioned_items);
443    println!("    Items: {}", query.count());
444
445    // ============================================================================
446    // DEMO 8: Real-World Example - Cache with TTL
447    // ============================================================================
448    println!("\n═══════════════════════════════════════════════════════════════");
449    println!("Demo 8: Cache container (real-world example)");
450    println!("═══════════════════════════════════════════════════════════════\n");
451
452    use std::time::{Duration, SystemTime};
453
454    struct CachedItem<T> {
455        item: T,
456        inserted_at: SystemTime,
457        ttl: Duration,
458    }
459
460    struct Cache<T> {
461        items: Vec<CachedItem<T>>,
462    }
463
464    impl<T> Cache<T> {
465        fn new() -> Self {
466            Self { items: Vec::new() }
467        }
468
469        fn insert(&mut self, item: T, ttl: Duration) {
470            self.items.push(CachedItem {
471                item,
472                inserted_at: SystemTime::now(),
473                ttl,
474            });
475        }
476
477        fn valid_items(&self) -> Vec<&T> {
478            let now = SystemTime::now();
479            self.items
480                .iter()
481                .filter(|cached| {
482                    now.duration_since(cached.inserted_at)
483                        .map_or(false, |elapsed| elapsed < cached.ttl)
484                })
485                .map(|cached| &cached.item)
486                .collect()
487        }
488    }
489
490    // Implement Queryable to query only valid (non-expired) items
491    impl<T> Queryable<T> for Cache<T> {
492        fn query_iter(&self) -> Box<dyn Iterator<Item = &T> + '_> {
493            let now = SystemTime::now();
494            Box::new(
495                self.items
496                    .iter()
497                    .filter(move |cached| {
498                        now.duration_since(cached.inserted_at)
499                            .map_or(false, |elapsed| elapsed < cached.ttl)
500                    })
501                    .map(|cached| &cached.item),
502            )
503        }
504    }
505
506    let mut cache = Cache::new();
507    cache.insert(create_sample_product(1, "Cached Item 1", 100.0, "A", true), Duration::from_secs(60));
508    cache.insert(create_sample_product(2, "Cached Item 2", 200.0, "B", true), Duration::from_secs(60));
509
510    let valid = cache.valid_items();
511    println!("  Cache:");
512    println!("    Total items: {}", cache.items.len());
513    println!("    Valid items: {}", valid.len());
514
515    // Query the cache
516    let cache_items: Vec<Product> = cache.query_iter().cloned().collect();
517    let cache_query = Query::new(&cache_items);
518    println!("    Queryable items: {}", cache_query.count());
519
520    // ============================================================================
521    // Summary
522    // ============================================================================
523    println!("\n╔════════════════════════════════════════════════════════════════╗");
524    println!("║  Summary: Implementing Queryable                              ║");
525    println!("╚════════════════════════════════════════════════════════════════╝\n");
526
527    println!("✅ How to make any container queryable:\n");
528    println!("  1. Implement the Queryable<T> trait:");
529    println!("     ```rust");
530    println!("     impl<T> Queryable<T> for MyContainer<T> {{");
531    println!("         fn query_iter(&self) -> Box<dyn Iterator<Item = &T> + '_> {{");
532    println!("             Box::new(self.items.iter())");
533    println!("         }}");
534    println!("     }}");
535    println!("     ```\n");
536
537    println!("  2. Convert to Vec or slice for querying:");
538    println!("     ```rust");
539    println!("     let items: Vec<&Product> = container.query_iter().collect();");
540    println!("     let query = Query::new(&items);");
541    println!("     ```\n");
542
543    println!("  3. Now use all query operations:");
544    println!("     ```rust");
545    println!("     let results = query.where_(...).all();");
546    println!("     let count = query.count();");
547    println!("     let total = query.sum(field);");
548    println!("     ```\n");
549
550    println!("📝 Custom containers demonstrated:");
551    println!("   • PaginatedCollection - Items stored in pages");
552    println!("   • CircularBuffer - Fixed-capacity FIFO buffer");
553    println!("   • FilteredStorage - Auto-filtering container");
554    println!("   • CategoryIndex - Indexed by category");
555    println!("   • LazyLoader - Simulated lazy loading");
556    println!("   • VersionedCollection - Wrapper with metadata");
557    println!("   • Cache - TTL-based cache\n");
558
559    println!("💡 Use cases:");
560    println!("   • Database result wrappers");
561    println!("   • Custom data structures");
562    println!("   • Specialized collections");
563    println!("   • Caches and buffers");
564    println!("   • Event streams");
565    println!("   • Any container that holds items!\n");
566
567    println!("✓ Custom Queryable demo complete!\n");
568}
examples/macro_helpers.rs (line 326)
36fn main() {
37    println!("\n╔════════════════════════════════════════════════════════════════╗");
38    println!("║  Macro Helpers Demo - Reducing Boilerplate                    ║");
39    println!("╚════════════════════════════════════════════════════════════════╝\n");
40
41    let products = create_products();
42
43    // ============================================================================
44    // EXAMPLE 1: Simple Collection
45    // ============================================================================
46    println!("═══════════════════════════════════════════════════════════════");
47    println!("Example 1: collect_lazy! - Simple collection");
48    println!("═══════════════════════════════════════════════════════════════\n");
49
50    println!("❌ Without macro (verbose):");
51    println!("```rust");
52    println!("let results: Vec<_> = LazyQuery::new(&products).collect();");
53    println!("```\n");
54
55    println!("✅ With macro (concise):");
56    println!("```rust");
57    println!("let results = collect_lazy!(&products);");
58    println!("```\n");
59
60    let results = collect_lazy!(&products);
61    println!("Result: {} products collected\n", results.len());
62
63    // ============================================================================
64    // EXAMPLE 2: Filter and Collect
65    // ============================================================================
66    println!("═══════════════════════════════════════════════════════════════");
67    println!("Example 2: filter_collect! - Filter and collect");
68    println!("═══════════════════════════════════════════════════════════════\n");
69
70    println!("❌ Without macro (verbose):");
71    println!("```rust");
72    println!("let electronics: Vec<_> = LazyQuery::new(&products)");
73    println!("    .where_(Product::category_r(), |cat| cat == \"Electronics\")");
74    println!("    .collect();");
75    println!("```\n");
76
77    println!("✅ With macro (concise):");
78    println!("```rust");
79    println!("let electronics = filter_collect!(");
80    println!("    &products,");
81    println!("    Product::category_r(),");
82    println!("    |cat| cat == \"Electronics\"");
83    println!(");");
84    println!("```\n");
85
86    let electronics = filter_collect!(
87        &products,
88        Product::category_r(),
89        |cat| cat == "Electronics"
90    );
91    println!("Result: {} electronics\n", electronics.len());
92
93    // ============================================================================
94    // EXAMPLE 3: Count with Filter
95    // ============================================================================
96    println!("═══════════════════════════════════════════════════════════════");
97    println!("Example 3: count_where! - Count with filter");
98    println!("═══════════════════════════════════════════════════════════════\n");
99
100    println!("❌ Without macro (verbose):");
101    println!("```rust");
102    println!("let count = LazyQuery::new(&products)");
103    println!("    .where_(Product::stock_r(), |&s| s > 0)");
104    println!("    .count();");
105    println!("```\n");
106
107    println!("✅ With macro (concise):");
108    println!("```rust");
109    println!("let count = count_where!(&products, Product::stock_r(), |&s| s > 0);");
110    println!("```\n");
111
112    let count = count_where!(&products, Product::stock_r(), |&s| s > 0);
113    println!("Result: {} products in stock\n", count);
114
115    // ============================================================================
116    // EXAMPLE 4: Find First
117    // ============================================================================
118    println!("═══════════════════════════════════════════════════════════════");
119    println!("Example 4: find_first! - Find first matching item");
120    println!("═══════════════════════════════════════════════════════════════\n");
121
122    println!("❌ Without macro (verbose):");
123    println!("```rust");
124    println!("let found = LazyQuery::new(&products)");
125    println!("    .where_(Product::price_r(), |&p| p > 500.0)");
126    println!("    .first();");
127    println!("```\n");
128
129    println!("✅ With macro (concise):");
130    println!("```rust");
131    println!("let found = find_first!(&products, Product::price_r(), |&p| p > 500.0);");
132    println!("```\n");
133
134    let found = find_first!(&products, Product::price_r(), |&p| p > 500.0);
135    if let Some(p) = found {
136        println!("Result: Found {} at ${:.2}\n", p.name, p.price);
137    }
138
139    // ============================================================================
140    // EXAMPLE 5: Existence Check
141    // ============================================================================
142    println!("═══════════════════════════════════════════════════════════════");
143    println!("Example 5: exists_where! - Check if any item matches");
144    println!("═══════════════════════════════════════════════════════════════\n");
145
146    println!("❌ Without macro (verbose):");
147    println!("```rust");
148    println!("let has_furniture = LazyQuery::new(&products)");
149    println!("    .where_(Product::category_r(), |cat| cat == \"Furniture\")");
150    println!("    .any();");
151    println!("```\n");
152
153    println!("✅ With macro (concise):");
154    println!("```rust");
155    println!("let has_furniture = exists_where!(");
156    println!("    &products,");
157    println!("    Product::category_r(),");
158    println!("    |cat| cat == \"Furniture\"");
159    println!(");");
160    println!("```\n");
161
162    let has_furniture = exists_where!(
163        &products,
164        Product::category_r(),
165        |cat| cat == "Furniture"
166    );
167    println!("Result: Has furniture = {}\n", has_furniture);
168
169    // ============================================================================
170    // EXAMPLE 6: Pagination
171    // ============================================================================
172    println!("═══════════════════════════════════════════════════════════════");
173    println!("Example 6: paginate! - Quick pagination");
174    println!("═══════════════════════════════════════════════════════════════\n");
175
176    println!("❌ Without macro (verbose):");
177    println!("```rust");
178    println!("let page_2: Vec<_> = LazyQuery::new(&products)");
179    println!("    .skip_lazy(1 * 2)  // page * size");
180    println!("    .take_lazy(2)");
181    println!("    .collect();");
182    println!("```\n");
183
184    println!("✅ With macro (concise):");
185    println!("```rust");
186    println!("let page_2 = paginate!(&products, page: 1, size: 2);");
187    println!("```\n");
188
189    let page_2 = paginate!(&products, page: 1, size: 2);
190    println!("Result: Page 2 has {} items\n", page_2.len());
191
192    // ============================================================================
193    // EXAMPLE 7: Sum with Filter
194    // ============================================================================
195    println!("═══════════════════════════════════════════════════════════════");
196    println!("Example 7: sum_where! - Sum with filter");
197    println!("═══════════════════════════════════════════════════════════════\n");
198
199    println!("❌ Without macro (verbose):");
200    println!("```rust");
201    println!("let total: f64 = LazyQuery::new(&products)");
202    println!("    .where_(Product::active_r(), |&a| a)");
203    println!("    .sum_by(Product::price_r());");
204    println!("```\n");
205
206    println!("✅ With macro (concise):");
207    println!("```rust");
208    println!("let total = sum_where!(&products, Product::price_r(), Product::active_r(), |&a| a);");
209    println!("```\n");
210
211    let total = sum_where!(&products, Product::price_r(), Product::active_r(), |&a| a);
212    println!("Result: Total active products value = ${:.2}\n", total);
213
214    // ============================================================================
215    // EXAMPLE 8: Average with Filter
216    // ============================================================================
217    println!("═══════════════════════════════════════════════════════════════");
218    println!("Example 8: avg_where! - Average with filter");
219    println!("═══════════════════════════════════════════════════════════════\n");
220
221    println!("❌ Without macro (verbose):");
222    println!("```rust");
223    println!("let avg = LazyQuery::new(&products)");
224    println!("    .where_(Product::category_r(), |cat| cat == \"Electronics\")");
225    println!("    .avg_by(Product::price_r())");
226    println!("    .unwrap_or(0.0);");
227    println!("```\n");
228
229    println!("✅ With macro (concise):");
230    println!("```rust");
231    println!("let avg = avg_where!(");
232    println!("    &products,");
233    println!("    Product::price_r(),");
234    println!("    Product::category_r(),");
235    println!("    |cat| cat == \"Electronics\"");
236    println!(").unwrap_or(0.0);");
237    println!("```\n");
238
239    let avg = avg_where!(
240        &products,
241        Product::price_r(),
242        Product::category_r(),
243        |cat| cat == "Electronics"
244    ).unwrap_or(0.0);
245    println!("Result: Average electronics price = ${:.2}\n", avg);
246
247    // ============================================================================
248    // EXAMPLE 9: Select All
249    // ============================================================================
250    println!("═══════════════════════════════════════════════════════════════");
251    println!("Example 9: select_all! - Select field from all items");
252    println!("═══════════════════════════════════════════════════════════════\n");
253
254    println!("❌ Without macro (verbose):");
255    println!("```rust");
256    println!("let names: Vec<String> = LazyQuery::new(&products)");
257    println!("    .select_lazy(Product::name_r())");
258    println!("    .collect();");
259    println!("```\n");
260
261    println!("✅ With macro (concise):");
262    println!("```rust");
263    println!("let names = select_all!(&products, Product::name_r());");
264    println!("```\n");
265
266    let names: Vec<String> = select_all!(&products, Product::name_r());
267    println!("Result: {} product names\n", names.len());
268
269    // ============================================================================
270    // EXAMPLE 10: Select with Filter
271    // ============================================================================
272    println!("═══════════════════════════════════════════════════════════════");
273    println!("Example 10: select_where! - Select field with filter");
274    println!("═══════════════════════════════════════════════════════════════\n");
275
276    println!("❌ Without macro (verbose):");
277    println!("```rust");
278    println!("let furniture_names: Vec<String> = LazyQuery::new(&products)");
279    println!("    .where_(Product::category_r(), |cat| cat == \"Furniture\")");
280    println!("    .select_lazy(Product::name_r())");
281    println!("    .collect();");
282    println!("```\n");
283
284    println!("✅ With macro (concise):");
285    println!("```rust");
286    println!("let furniture_names = select_where!(");
287    println!("    &products,");
288    println!("    Product::name_r(),");
289    println!("    Product::category_r(),");
290    println!("    |cat| cat == \"Furniture\"");
291    println!(");");
292    println!("```\n");
293
294    let furniture_names: Vec<String> = select_where!(
295        &products,
296        Product::name_r(),
297        Product::category_r(),
298        |cat| cat == "Furniture"
299    );
300    println!("Result: {} furniture items\n", furniture_names.len());
301
302    // ============================================================================
303    // COMPARISON: Complex Query
304    // ============================================================================
305    println!("═══════════════════════════════════════════════════════════════");
306    println!("Complex Example: Before & After");
307    println!("═══════════════════════════════════════════════════════════════\n");
308
309    println!("Scenario: Filter electronics, under $500, in stock, get first 5\n");
310
311    println!("❌ WITHOUT MACROS (13 lines):");
312    println!("```rust");
313    println!("let results: Vec<_> = LazyQuery::new(&products)");
314    println!("    .where_(");
315    println!("        Product::category_r(),");
316    println!("        |cat| cat == \"Electronics\"");
317    println!("    )");
318    println!("    .where_(Product::price_r(), |&p| p < 500.0)");
319    println!("    .where_(Product::stock_r(), |&s| s > 0)");
320    println!("    .take_lazy(5)");
321    println!("    .collect();");
322    println!("```\n");
323
324    // Actual verbose version
325    let verbose_results: Vec<_> = LazyQuery::new(&products)
326        .where_(Product::category_r(), |cat| cat == "Electronics")
327        .where_(Product::price_r(), |&p| p < 500.0)
328        .where_(Product::stock_r(), |&s| s > 0)
329        .take_lazy(5)
330        .collect();
331
332    println!("✅ WITH MACROS (Shorter, but still need multiple filters):");
333    println!("```rust");
334    println!("let results = lazy_query!(&products)");
335    println!("    .where_(Product::category_r(), |cat| cat == \"Electronics\")");
336    println!("    .where_(Product::price_r(), |&p| p < 500.0)");
337    println!("    .where_(Product::stock_r(), |&s| s > 0)");
338    println!("    .take_lazy(5)");
339    println!("    .collect();");
340    println!("```\n");
341
342    let macro_results = lazy_query!(&products)
343        .where_(Product::category_r(), |cat| cat == "Electronics")
344        .where_(Product::price_r(), |&p| p < 500.0)
345        .where_(Product::stock_r(), |&s| s > 0)
346        .take_lazy(5)
347        .collect();
348
349    println!("Both approaches found {} items ✅\n", verbose_results.len());
350    assert_eq!(verbose_results.len(), macro_results.len());
351
352    // ============================================================================
353    // CODE REDUCTION METRICS
354    // ============================================================================
355    println!("═══════════════════════════════════════════════════════════════");
356    println!("Code Reduction Metrics");
357    println!("═══════════════════════════════════════════════════════════════\n");
358
359    println!("Pattern Comparisons:\n");
360
361    println!("  1. Simple collect:");
362    println!("     Before: LazyQuery::new(&data).collect()");
363    println!("     After:  collect_lazy!(&data)");
364    println!("     Saved:  ~20 characters\n");
365
366    println!("  2. Filter + collect:");
367    println!("     Before: LazyQuery::new(&data).where_(...).collect()");
368    println!("     After:  filter_collect!(&data, field, pred)");
369    println!("     Saved:  ~35 characters\n");
370
371    println!("  3. Count with filter:");
372    println!("     Before: LazyQuery::new(&data).where_(...).count()");
373    println!("     After:  count_where!(&data, field, pred)");
374    println!("     Saved:  ~30 characters\n");
375
376    println!("  4. Pagination:");
377    println!("     Before: LazyQuery::new(&data).skip_lazy(p*s).take_lazy(s).collect()");
378    println!("     After:  paginate!(&data, page: p, size: s)");
379    println!("     Saved:  ~45 characters\n");
380
381    println!("  5. Sum with filter:");
382    println!("     Before: LazyQuery::new(&data).where_(...).sum_by(...)");
383    println!("     After:  sum_where!(&data, sum_field, filter_field, pred)");
384    println!("     Saved:  ~25 characters\n");
385
386    // ============================================================================
387    // ALL MACRO DEMONSTRATIONS
388    // ============================================================================
389    println!("═══════════════════════════════════════════════════════════════");
390    println!("All Available Macros - Quick Reference");
391    println!("═══════════════════════════════════════════════════════════════\n");
392
393    println!("1. lazy_query!(&data)");
394    let _q1 = lazy_query!(&products);
395    println!("   → LazyQuery::new(&data)\n");
396
397    println!("2. query!(&data)");
398    let _q2 = query!(&products);
399    println!("   → Query::new(&data)\n");
400
401    println!("3. collect_lazy!(&data)");
402    let _r3 = collect_lazy!(&products);
403    println!("   → LazyQuery::new(&data).collect()\n");
404
405    println!("4. filter_collect!(&data, field, pred)");
406    let _r4 = filter_collect!(&products, Product::active_r(), |&a| a);
407    println!("   → LazyQuery::new(&data).where_(field, pred).collect()\n");
408
409    println!("5. count_where!(&data, field, pred)");
410    let _r5 = count_where!(&products, Product::active_r(), |&a| a);
411    println!("   → LazyQuery::new(&data).where_(field, pred).count()\n");
412
413    println!("6. find_first!(&data, field, pred)");
414    let _r6 = find_first!(&products, Product::id_r(), |&id| id == 1);
415    println!("   → LazyQuery::new(&data).where_(field, pred).first()\n");
416
417    println!("7. exists_where!(&data, field, pred)");
418    let _r7 = exists_where!(&products, Product::active_r(), |&a| a);
419    println!("   → LazyQuery::new(&data).where_(field, pred).any()\n");
420
421    println!("8. paginate!(&data, page: p, size: s)");
422    let _r8 = paginate!(&products, page: 0, size: 3);
423    println!("   → LazyQuery::new(&data).skip_lazy(p*s).take_lazy(s).collect()\n");
424
425    println!("9. sum_where!(&data, sum_field, filter_field, pred)");
426    let _r9 = sum_where!(&products, Product::price_r(), Product::active_r(), |&a| a);
427    println!("   → LazyQuery::new(&data).where_(filter_field, pred).sum_by(sum_field)\n");
428
429    println!("10. avg_where!(&data, avg_field, filter_field, pred)");
430    let _r10 = avg_where!(&products, Product::price_r(), Product::active_r(), |&a| a);
431    println!("    → LazyQuery::new(&data).where_(filter_field, pred).avg_by(avg_field)\n");
432
433    println!("11. select_all!(&data, field)");
434    let _r11: Vec<String> = select_all!(&products, Product::name_r());
435    println!("    → LazyQuery::new(&data).select_lazy(field).collect()\n");
436
437    println!("12. select_where!(&data, select_field, filter_field, pred)");
438    let _r12: Vec<String> = select_where!(&products, Product::name_r(), Product::active_r(), |&a| a);
439    println!("    → LazyQuery::new(&data).where_(filter, pred).select_lazy(field).collect()\n");
440
441    // ============================================================================
442    // Summary
443    // ============================================================================
444    println!("╔════════════════════════════════════════════════════════════════╗");
445    println!("║  Summary                                                       ║");
446    println!("╚════════════════════════════════════════════════════════════════╝\n");
447
448    println!("✅ 12 helper macros provided:");
449    println!("   • lazy_query! - Create LazyQuery");
450    println!("   • query! - Create Query");
451    println!("   • collect_lazy! - Quick collect");
452    println!("   • filter_collect! - Filter and collect");
453    println!("   • count_where! - Count with filter");
454    println!("   • find_first! - Find first match");
455    println!("   • exists_where! - Existence check");
456    println!("   • paginate! - Easy pagination");
457    println!("   • sum_where! - Sum with filter");
458    println!("   • avg_where! - Average with filter");
459    println!("   • select_all! - Select all");
460    println!("   • select_where! - Select with filter\n");
461
462    println!("📊 Benefits:");
463    println!("   • Less typing (20-45 characters saved per operation)");
464    println!("   • More readable code");
465    println!("   • Common patterns encapsulated");
466    println!("   • Same performance (zero-cost abstraction)");
467    println!("   • Type-safe (compile-time checked)\n");
468
469    println!("💡 When to use:");
470    println!("   • Use macros for simple, common patterns");
471    println!("   • Use full API for complex queries");
472    println!("   • Mix and match as needed\n");
473
474    println!("✓ Macro helpers demo complete!\n");
475}
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<_>>();
Examples found in repository?
examples/derive_and_ext.rs (line 128)
13fn main() {
14    println!("Derive Macros and Extension Traits Example");
15    println!("===========================================\n");
16
17    let products = vec![
18        Product {
19            id: 1,
20            name: "Laptop".to_string(),
21            price: 999.99,
22            category: "Electronics".to_string(),
23            stock: 5,
24        },
25        Product {
26            id: 2,
27            name: "Mouse".to_string(),
28            price: 29.99,
29            category: "Electronics".to_string(),
30            stock: 50,
31        },
32        Product {
33            id: 3,
34            name: "Keyboard".to_string(),
35            price: 79.99,
36            category: "Electronics".to_string(),
37            stock: 30,
38        },
39        Product {
40            id: 4,
41            name: "Monitor".to_string(),
42            price: 299.99,
43            category: "Electronics".to_string(),
44            stock: 12,
45        },
46        Product {
47            id: 5,
48            name: "Desk Chair".to_string(),
49            price: 199.99,
50            category: "Furniture".to_string(),
51            stock: 8,
52        },
53    ];
54
55    println!("1. Using Extension Trait - Direct .query() on Vec");
56    println!("   Query: products.query().where_(price > 100).all()");
57    
58    let query = products
59        .query()
60        .where_(Product::price_r(), |&p| p > 100.0);
61    let expensive = query.all();
62    
63    println!("   Found {} expensive products:", expensive.len());
64    for product in &expensive {
65        println!("   - {} (${:.2})", product.name, product.price);
66    }
67    println!();
68
69    println!("2. Using Extension Trait - Direct .lazy_query() on Vec");
70    println!("   Query: products.lazy_query().where_(stock < 10).collect()");
71    
72    let low_stock: Vec<_> = products
73        .lazy_query()
74        .where_(Product::stock_r(), |&s| s < 10)
75        .collect();
76    
77    println!("   Found {} low stock products:", low_stock.len());
78    for product in &low_stock {
79        println!("   - {} (stock: {})", product.name, product.stock);
80    }
81    println!();
82
83    println!("3. Using Extension Trait - Chained Operations");
84    println!("   Query: products.lazy_query().where_(category == Electronics).take(2).select(name).collect()");
85    
86    let names: Vec<String> = products
87        .lazy_query()
88        .where_(Product::category_r(), |cat| cat == "Electronics")
89        .take_lazy(2)
90        .select_lazy(Product::name_r())
91        .collect();
92    
93    println!("   First 2 electronics:");
94    for name in &names {
95        println!("   - {}", name);
96    }
97    println!();
98
99    println!("4. Using QueryBuilder Derive - Static Methods");
100    println!("   Query: Product::query(&products).where_(price > 50).count()");
101    
102    let query4 = Product::query(&products)
103        .where_(Product::price_r(), |&p| p > 50.0);
104    let count = query4.count();
105    
106    println!("   Products over $50: {}", count);
107    println!();
108
109    println!("5. Using QueryBuilder Derive - Lazy Static Methods");
110    println!("   Query: Product::lazy_query(&products).first()");
111    
112    if let Some(first) = Product::lazy_query(&products).first() {
113        println!("   First product: {} (${:.2})", first.name, first.price);
114    }
115    println!();
116
117    println!("6. Complex Chain with Extension Trait");
118    println!("   Query: products.lazy_query()");
119    println!("          .where_(category == Electronics)");
120    println!("          .where_(price < 500)");
121    println!("          .map(|p| format!(\"{{}} - ${{:.2}}\", p.name, p.price))");
122    println!("          .collect()");
123    
124    let formatted: Vec<String> = products
125        .lazy_query()
126        .where_(Product::category_r(), |cat| cat == "Electronics")
127        .where_(Product::price_r(), |&p| p < 500.0)
128        .map_items(|p| format!("{} - ${:.2}", p.name, p.price))
129        .collect();
130    
131    println!("   Affordable electronics:");
132    for item in &formatted {
133        println!("   - {}", item);
134    }
135    println!();
136
137    println!("7. Aggregation with Extension Trait");
138    println!("   Query: products.lazy_query().sum_by(Product::stock())");
139    
140    let total_stock = products
141        .lazy_query()
142        .sum_by(Product::stock_r());
143    
144    println!("   Total stock across all products: {}", total_stock);
145    println!();
146
147    println!("8. Find with Extension Trait");
148    println!("   Query: products.lazy_query().find(|p| p.name.contains(\"Chair\"))");
149    
150    if let Some(chair) = products.lazy_query().find(|p| p.name.contains("Chair")) {
151        println!("   Found: {} in {}", chair.name, chair.category);
152    }
153    println!();
154
155    println!("9. Early Termination with Extension Trait");
156    println!("   Query: products.lazy_query().where_(price > 1000).any()");
157    
158    let has_luxury = products
159        .lazy_query()
160        .where_(Product::price_r(), |&p| p > 1000.0)
161        .any();
162    
163    println!("   Has products over $1000: {}", has_luxury);
164    println!();
165
166    println!("10. Slice Extension Trait");
167    println!("    Query: (&products[..]).lazy_query().count()");
168    
169    let slice_count = (&products[..])
170        .lazy_query()
171        .count();
172    
173    println!("    Count from slice: {}", slice_count);
174    println!();
175
176    println!("Summary:");
177    println!("--------");
178    println!("✓ Extension trait QueryExt adds .query() and .lazy_query() to containers");
179    println!("✓ Derive macro QueryBuilder adds static methods Product::query() and Product::lazy_query()");
180    println!("✓ Both approaches provide the same query functionality");
181    println!("✓ Extension trait is more ergonomic: products.query() vs Query::new(&products)");
182    println!("✓ All iterator optimizations (fusion, early termination) still apply");
183}
More examples
Hide additional examples
examples/arc_rwlock_hashmap.rs (line 327)
59fn main() {
60    println!("\n╔══════════════════════════════════════════════════════════════════╗");
61    println!("║  Arc<RwLock<T>> HashMap Lazy Query Demo                         ║");
62    println!("║  Thread-safe shared data with lazy evaluation                   ║");
63    println!("╚══════════════════════════════════════════════════════════════════╝\n");
64
65    let product_map = create_sample_data();
66    println!("Created product catalog:");
67    println!("  Total products: {}", product_map.len());
68    println!("  Keys: {:?}\n", product_map.keys().take(3).collect::<Vec<_>>());
69
70    // Extract products for querying
71    let products = extract_products(&product_map);
72    println!("Extracted {} products from Arc<RwLock<Product>>\n", products.len());
73
74    // ============================================================================
75    // LAZY OPERATION 1: where_ - Lazy Filtering
76    // ============================================================================
77    println!("═══════════════════════════════════════════════════════════════");
78    println!("Lazy Operation 1: where_ (filtering)");
79    println!("═══════════════════════════════════════════════════════════════\n");
80
81    println!("Building filtered query (nothing executes yet)...");
82    let electronics_query = LazyQuery::new(&products)
83        .where_(Product::category_r(), |cat| cat == "Electronics")
84        .where_(Product::active_r(), |&active| active)
85        .where_(Product::stock_r(), |&stock| stock > 20);
86
87    println!("  ✅ Query built (deferred execution)\n");
88
89    println!("Collecting results (executes now)...");
90    let electronics: Vec<_> = electronics_query.collect();
91    println!("  Found {} electronics in stock", electronics.len());
92    for p in &electronics {
93        println!("    • {}: {} in stock", p.name, p.stock);
94    }
95
96    // ============================================================================
97    // LAZY OPERATION 2: select_lazy - Lazy Projection
98    // ============================================================================
99    println!("\n═══════════════════════════════════════════════════════════════");
100    println!("Lazy Operation 2: select_lazy (projection)");
101    println!("═══════════════════════════════════════════════════════════════\n");
102
103    println!("Selecting product names (lazy)...");
104    let names: Vec<String> = LazyQuery::new(&products)
105        .where_(Product::category_r(), |cat| cat == "Furniture")
106        .select_lazy(Product::name_r())
107        .collect();
108
109    println!("  Furniture names ({}):", names.len());
110    for name in &names {
111        println!("    • {}", name);
112    }
113
114    // ============================================================================
115    // LAZY OPERATION 3: take_lazy - Early Termination
116    // ============================================================================
117    println!("\n═══════════════════════════════════════════════════════════════");
118    println!("Lazy Operation 3: take_lazy (early termination)");
119    println!("═══════════════════════════════════════════════════════════════\n");
120
121    println!("Getting first 3 electronics...");
122    let first_3: Vec<_> = LazyQuery::new(&products)
123        .where_(Product::category_r(), |cat| cat == "Electronics")
124        .take_lazy(3)
125        .collect();
126
127    println!("  First 3 electronics:");
128    for (i, p) in first_3.iter().enumerate() {
129        println!("    {}. {} - ${:.2}", i + 1, p.name, p.price);
130    }
131    println!("  ✅ Stopped after finding 3 items!");
132
133    // ============================================================================
134    // LAZY OPERATION 4: skip_lazy - Pagination
135    // ============================================================================
136    println!("\n═══════════════════════════════════════════════════════════════");
137    println!("Lazy Operation 4: skip_lazy (pagination)");
138    println!("═══════════════════════════════════════════════════════════════\n");
139
140    println!("Getting page 2 (skip 3, take 3)...");
141    let page_2: Vec<_> = LazyQuery::new(&products)
142        .where_(Product::active_r(), |&active| active)
143        .skip_lazy(3)
144        .take_lazy(3)
145        .collect();
146
147    println!("  Page 2 items:");
148    for (i, p) in page_2.iter().enumerate() {
149        println!("    {}. {}", i + 4, p.name);
150    }
151
152    // ============================================================================
153    // LAZY OPERATION 5: first - Short-Circuit Search
154    // ============================================================================
155    println!("\n═══════════════════════════════════════════════════════════════");
156    println!("Lazy Operation 5: first (short-circuit)");
157    println!("═══════════════════════════════════════════════════════════════\n");
158
159    println!("Finding first expensive item (>$1000)...");
160    let expensive = LazyQuery::new(&products)
161        .where_(Product::price_r(), |&price| price > 1000.0)
162        .first();
163
164    match expensive {
165        Some(p) => println!("  Found: {} - ${:.2}", p.name, p.price),
166        None => println!("  Not found"),
167    }
168    println!("  ✅ Stopped at first match!");
169
170    // ============================================================================
171    // LAZY OPERATION 6: any - Existence Check
172    // ============================================================================
173    println!("\n═══════════════════════════════════════════════════════════════");
174    println!("Lazy Operation 6: any (existence check)");
175    println!("═══════════════════════════════════════════════════════════════\n");
176
177    println!("Checking if any furniture exists...");
178    let has_furniture = LazyQuery::new(&products)
179        .where_(Product::category_r(), |cat| cat == "Furniture")
180        .any();
181
182    println!("  Has furniture: {}", has_furniture);
183    println!("  ✅ Stopped immediately after finding first match!");
184
185    // ============================================================================
186    // LAZY OPERATION 7: count - Count Matching Items
187    // ============================================================================
188    println!("\n═══════════════════════════════════════════════════════════════");
189    println!("Lazy Operation 7: count");
190    println!("═══════════════════════════════════════════════════════════════\n");
191
192    let electronics_count = LazyQuery::new(&products)
193        .where_(Product::category_r(), |cat| cat == "Electronics")
194        .count();
195
196    println!("  Electronics count: {}", electronics_count);
197
198    // ============================================================================
199    // LAZY OPERATION 8: sum_by - Aggregation
200    // ============================================================================
201    println!("\n═══════════════════════════════════════════════════════════════");
202    println!("Lazy Operation 8: sum_by (aggregation)");
203    println!("═══════════════════════════════════════════════════════════════\n");
204
205    let total_value: f64 = LazyQuery::new(&products)
206        .where_(Product::category_r(), |cat| cat == "Electronics")
207        .sum_by(Product::price_r());
208
209    println!("  Total electronics value: ${:.2}", total_value);
210
211    // ============================================================================
212    // LAZY OPERATION 9: avg_by - Average
213    // ============================================================================
214    println!("\n═══════════════════════════════════════════════════════════════");
215    println!("Lazy Operation 9: avg_by");
216    println!("═══════════════════════════════════════════════════════════════\n");
217
218    let avg_price = LazyQuery::new(&products)
219        .where_(Product::category_r(), |cat| cat == "Furniture")
220        .avg_by(Product::price_r())
221        .unwrap_or(0.0);
222
223    println!("  Average furniture price: ${:.2}", avg_price);
224
225    // ============================================================================
226    // LAZY OPERATION 10: min_by_float / max_by_float
227    // ============================================================================
228    println!("\n═══════════════════════════════════════════════════════════════");
229    println!("Lazy Operation 10: min_by_float / max_by_float");
230    println!("═══════════════════════════════════════════════════════════════\n");
231
232    let min_price = LazyQuery::new(&products)
233        .where_(Product::active_r(), |&active| active)
234        .min_by_float(Product::price_r())
235        .unwrap_or(0.0);
236
237    let max_price = LazyQuery::new(&products)
238        .where_(Product::active_r(), |&active| active)
239        .max_by_float(Product::price_r())
240        .unwrap_or(0.0);
241
242    println!("  Price range for active products:");
243    println!("    Min: ${:.2}", min_price);
244    println!("    Max: ${:.2}", max_price);
245
246    // ============================================================================
247    // LAZY OPERATION 11: find - Find with Predicate
248    // ============================================================================
249    println!("\n═══════════════════════════════════════════════════════════════");
250    println!("Lazy Operation 11: find (with predicate)");
251    println!("═══════════════════════════════════════════════════════════════\n");
252
253    let high_rated = LazyQuery::new(&products)
254        .where_(Product::category_r(), |cat| cat == "Electronics")
255        .find(|item| item.rating > 4.7);
256
257    if let Some(product) = high_rated {
258        println!("  First highly-rated electronic:");
259        println!("    {}: Rating {:.1}", product.name, product.rating);
260    }
261
262    // ============================================================================
263    // LAZY OPERATION 12: for_each - Iteration
264    // ============================================================================
265    println!("\n═══════════════════════════════════════════════════════════════");
266    println!("Lazy Operation 12: for_each (iteration)");
267    println!("═══════════════════════════════════════════════════════════════\n");
268
269    println!("  Low stock alerts:");
270    LazyQuery::new(&products)
271        .where_(Product::stock_r(), |&stock| stock < 20)
272        .for_each(|product| {
273            println!("    ⚠️  {}: Only {} in stock", product.name, product.stock);
274        });
275
276    // ============================================================================
277    // LAZY OPERATION 13: fold - Custom Aggregation
278    // ============================================================================
279    println!("\n═══════════════════════════════════════════════════════════════");
280    println!("Lazy Operation 14: fold (custom aggregation)");
281    println!("═══════════════════════════════════════════════════════════════\n");
282
283    let total_inventory_value = LazyQuery::new(&products)
284        .where_(Product::active_r(), |&active| active)
285        .fold(0.0, |acc, product| {
286            acc + (product.price * product.stock as f64)
287        });
288
289    println!("  Total inventory value: ${:.2}", total_inventory_value);
290
291    // ============================================================================
292    // LAZY OPERATION 14: all_match - Validation
293    // ============================================================================
294    println!("\n═══════════════════════════════════════════════════════════════");
295    println!("Lazy Operation 15: all_match (validation)");
296    println!("═══════════════════════════════════════════════════════════════\n");
297
298    let all_priced = LazyQuery::new(&products)
299        .all_match(|item| item.price > 0.0);
300
301    println!("  All products have valid prices: {}", all_priced);
302
303    // ============================================================================
304    // LAZY OPERATION 15: into_iter - For Loop
305    // ============================================================================
306    println!("\n═══════════════════════════════════════════════════════════════");
307    println!("Lazy Operation 16: into_iter (for loop)");
308    println!("═══════════════════════════════════════════════════════════════\n");
309
310    println!("  High-value products (>$300):");
311    for product in LazyQuery::new(&products)
312        .where_(Product::price_r(), |&p| p > 300.0)
313        .take_lazy(5)
314    {
315        println!("    • {}: ${:.2}", product.name, product.price);
316    }
317
318    // ============================================================================
319    // LAZY OPERATION 16: map_items - Transform
320    // ============================================================================
321    println!("\n═══════════════════════════════════════════════════════════════");
322    println!("Lazy Operation 17: map_items (transformation)");
323    println!("═══════════════════════════════════════════════════════════════\n");
324
325    let price_tags: Vec<String> = LazyQuery::new(&products)
326        .where_(Product::category_r(), |cat| cat == "Electronics")
327        .map_items(|p| format!("{}: ${:.2}", p.name, p.price))
328        .take(5)
329        .collect();
330
331    println!("  Electronics price tags:");
332    for tag in &price_tags {
333        println!("    • {}", tag);
334    }
335
336    // ============================================================================
337    // COMPLEX EXAMPLE: Multi-Stage Lazy Pipeline
338    // ============================================================================
339    println!("\n═══════════════════════════════════════════════════════════════");
340    println!("Complex Example: Multi-stage lazy pipeline");
341    println!("═══════════════════════════════════════════════════════════════\n");
342
343    println!("Building complex query:");
344    println!("  1. Filter by category (Electronics)");
345    println!("  2. Filter by price range ($50-$500)");
346    println!("  3. Filter by rating (>4.5)");
347    println!("  4. Select names");
348    println!("  5. Take first 3");
349    println!();
350
351    let results: Vec<String> = LazyQuery::new(&products)
352        .where_(Product::category_r(), |cat| cat == "Electronics")
353        .where_(Product::price_r(), |&p| p >= 50.0 && p <= 500.0)
354        .where_(Product::rating_r(), |&r| r > 4.5)
355        .select_lazy(Product::name_r())
356        .take(3)
357        .collect();
358
359    println!("  Results:");
360    for (i, name) in results.iter().enumerate() {
361        println!("    {}. {}", i + 1, name);
362    }
363    println!("  ✅ All operations fused and executed lazily!");
364
365    // ============================================================================
366    // THREAD-SAFE UPDATES WITH RWLOCK
367    // ============================================================================
368    println!("\n═══════════════════════════════════════════════════════════════");
369    println!("Bonus: Thread-safe updates with RwLock");
370    println!("═══════════════════════════════════════════════════════════════\n");
371
372    // Update a product through the Arc<RwLock>
373    if let Some(product_arc) = product_map.get("PROD-002") {
374        println!("Updating PROD-002 stock...");
375        
376        // Write lock for mutation
377        if let Ok(mut product) = product_arc.write() {
378            let old_stock = product.stock;
379            product.stock = 25;
380            println!("  Stock updated: {} → {}", old_stock, product.stock);
381        }
382    }
383
384    // Query again to see the update
385    let updated_products = extract_products(&product_map);
386    let mouse = LazyQuery::new(&updated_products)
387        .find(|p| p.id == 2);
388
389    if let Some(product) = mouse {
390        println!("  Verified update: {} now has {} in stock", product.name, product.stock);
391    }
392
393    // ============================================================================
394    // PRACTICAL EXAMPLE: Price Analysis by Category
395    // ============================================================================
396    println!("\n═══════════════════════════════════════════════════════════════");
397    println!("Practical Example: Price analysis by category");
398    println!("═══════════════════════════════════════════════════════════════\n");
399
400    let categories = vec!["Electronics", "Furniture"];
401
402    for category in categories {
403        println!("  {} Statistics:", category);
404        
405        // Filter products by category first
406        let cat_products: Vec<Product> = products.iter()
407            .filter(|p| p.category == category)
408            .cloned()
409            .collect();
410
411        let count = LazyQuery::new(&cat_products).count();
412        let total = LazyQuery::new(&cat_products).sum_by(Product::price_r());
413        let avg = LazyQuery::new(&cat_products).avg_by(Product::price_r()).unwrap_or(0.0);
414        let min = LazyQuery::new(&cat_products).min_by_float(Product::price_r()).unwrap_or(0.0);
415        let max = LazyQuery::new(&cat_products).max_by_float(Product::price_r()).unwrap_or(0.0);
416
417        println!("    Count: {}", count);
418        println!("    Total: ${:.2}", total);
419        println!("    Average: ${:.2}", avg);
420        println!("    Range: ${:.2} - ${:.2}\n", min, max);
421    }
422
423    // ============================================================================
424    // COMBINING WITH HASHMAP OPERATIONS
425    // ============================================================================
426    println!("═══════════════════════════════════════════════════════════════");
427    println!("HashMap Integration: Query by key patterns");
428    println!("═══════════════════════════════════════════════════════════════\n");
429
430    // Filter HashMap by key pattern
431    let electronics_keys: Vec<String> = product_map
432        .iter()
433        .filter(|(_key, value)| {
434            // Read the value to check category
435            if let Ok(guard) = value.read() {
436                guard.category == "Electronics"
437            } else {
438                false
439            }
440        })
441        .map(|(key, _value)| key.clone())
442        .collect();
443
444    println!("  Electronics product IDs:");
445    for key in electronics_keys.iter().take(5) {
446        println!("    • {}", key);
447    }
448
449    // ============================================================================
450    // PERFORMANCE DEMONSTRATION
451    // ============================================================================
452    println!("\n═══════════════════════════════════════════════════════════════");
453    println!("Performance: Lazy vs Eager comparison");
454    println!("═══════════════════════════════════════════════════════════════\n");
455
456    println!("Scenario: Find first product with rating > 4.7 from {} products\n", products.len());
457
458    println!("  Eager approach (hypothetical):");
459    println!("    - Filter all {} products", products.len());
460    println!("    - Collect filtered results");
461    println!("    - Take first item");
462    println!("    - Wasted work: Check all items\n");
463
464    println!("  Lazy approach (actual):");
465    let _first_rated = LazyQuery::new(&products)
466        .where_(Product::rating_r(), |&r| r > 4.7)
467        .first();
468    println!("    - Starts checking products");
469    println!("    - Stops at first match");
470    println!("    - ✅ Early termination - checks ~3-5 items only!");
471
472    // ============================================================================
473    // Summary
474    // ============================================================================
475    println!("\n╔══════════════════════════════════════════════════════════════════╗");
476    println!("║  Summary: All Lazy Operations Demonstrated                      ║");
477    println!("╚══════════════════════════════════════════════════════════════════╝\n");
478
479    println!("✅ Lazy Query Operations:");
480    println!("   1. ✅ where_ - Lazy filtering");
481    println!("   2. ✅ select_lazy - Lazy projection");
482    println!("   3. ✅ take_lazy - Early termination");
483    println!("   4. ✅ skip_lazy - Pagination");
484    println!("   5. ✅ first - Short-circuit search");
485    println!("   6. ✅ any - Existence check (short-circuit)");
486    println!("   7. ✅ count - Count items");
487    println!("   8. ✅ sum_by - Sum aggregation");
488    println!("   9. ✅ avg_by - Average aggregation");
489    println!("   10. ✅ min_by_float - Minimum value");
490    println!("   11. ✅ max_by_float - Maximum value");
491    println!("   12. ✅ find - Find with predicate (short-circuit)");
492    println!("   13. ✅ for_each - Iteration");
493    println!("   14. ✅ fold - Custom aggregation");
494    println!("   15. ✅ all_match - Validation (short-circuit)");
495    println!("   16. ✅ into_iter - For loop support");
496    println!("   17. ✅ map_items - Transformation\n");
497
498    println!("✅ Arc<RwLock<T>> Benefits:");
499    println!("   • Thread-safe shared access");
500    println!("   • Interior mutability");
501    println!("   • Multiple readers, single writer");
502    println!("   • Reference counting (Arc)");
503    println!("   • Can be queried after extracting data\n");
504
505    println!("✅ HashMap<K, Arc<RwLock<V>>> Benefits:");
506    println!("   • Fast key-based lookup");
507    println!("   • Thread-safe value access");
508    println!("   • Can query all values");
509    println!("   • Can filter by key patterns");
510    println!("   • Perfect for shared state/caches\n");
511
512    println!("🎯 Use Cases:");
513    println!("   • Shared product catalogs");
514    println!("   • User session stores");
515    println!("   • Configuration caches");
516    println!("   • Real-time inventory systems");
517    println!("   • Multi-threaded data processing");
518    println!("   • Web server state management\n");
519
520    println!("✓ Arc<RwLock<T>> HashMap with all lazy operations demo complete!\n");
521}
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/derive_and_ext.rs (line 90)
13fn main() {
14    println!("Derive Macros and Extension Traits Example");
15    println!("===========================================\n");
16
17    let products = vec![
18        Product {
19            id: 1,
20            name: "Laptop".to_string(),
21            price: 999.99,
22            category: "Electronics".to_string(),
23            stock: 5,
24        },
25        Product {
26            id: 2,
27            name: "Mouse".to_string(),
28            price: 29.99,
29            category: "Electronics".to_string(),
30            stock: 50,
31        },
32        Product {
33            id: 3,
34            name: "Keyboard".to_string(),
35            price: 79.99,
36            category: "Electronics".to_string(),
37            stock: 30,
38        },
39        Product {
40            id: 4,
41            name: "Monitor".to_string(),
42            price: 299.99,
43            category: "Electronics".to_string(),
44            stock: 12,
45        },
46        Product {
47            id: 5,
48            name: "Desk Chair".to_string(),
49            price: 199.99,
50            category: "Furniture".to_string(),
51            stock: 8,
52        },
53    ];
54
55    println!("1. Using Extension Trait - Direct .query() on Vec");
56    println!("   Query: products.query().where_(price > 100).all()");
57    
58    let query = products
59        .query()
60        .where_(Product::price_r(), |&p| p > 100.0);
61    let expensive = query.all();
62    
63    println!("   Found {} expensive products:", expensive.len());
64    for product in &expensive {
65        println!("   - {} (${:.2})", product.name, product.price);
66    }
67    println!();
68
69    println!("2. Using Extension Trait - Direct .lazy_query() on Vec");
70    println!("   Query: products.lazy_query().where_(stock < 10).collect()");
71    
72    let low_stock: Vec<_> = products
73        .lazy_query()
74        .where_(Product::stock_r(), |&s| s < 10)
75        .collect();
76    
77    println!("   Found {} low stock products:", low_stock.len());
78    for product in &low_stock {
79        println!("   - {} (stock: {})", product.name, product.stock);
80    }
81    println!();
82
83    println!("3. Using Extension Trait - Chained Operations");
84    println!("   Query: products.lazy_query().where_(category == Electronics).take(2).select(name).collect()");
85    
86    let names: Vec<String> = products
87        .lazy_query()
88        .where_(Product::category_r(), |cat| cat == "Electronics")
89        .take_lazy(2)
90        .select_lazy(Product::name_r())
91        .collect();
92    
93    println!("   First 2 electronics:");
94    for name in &names {
95        println!("   - {}", name);
96    }
97    println!();
98
99    println!("4. Using QueryBuilder Derive - Static Methods");
100    println!("   Query: Product::query(&products).where_(price > 50).count()");
101    
102    let query4 = Product::query(&products)
103        .where_(Product::price_r(), |&p| p > 50.0);
104    let count = query4.count();
105    
106    println!("   Products over $50: {}", count);
107    println!();
108
109    println!("5. Using QueryBuilder Derive - Lazy Static Methods");
110    println!("   Query: Product::lazy_query(&products).first()");
111    
112    if let Some(first) = Product::lazy_query(&products).first() {
113        println!("   First product: {} (${:.2})", first.name, first.price);
114    }
115    println!();
116
117    println!("6. Complex Chain with Extension Trait");
118    println!("   Query: products.lazy_query()");
119    println!("          .where_(category == Electronics)");
120    println!("          .where_(price < 500)");
121    println!("          .map(|p| format!(\"{{}} - ${{:.2}}\", p.name, p.price))");
122    println!("          .collect()");
123    
124    let formatted: Vec<String> = products
125        .lazy_query()
126        .where_(Product::category_r(), |cat| cat == "Electronics")
127        .where_(Product::price_r(), |&p| p < 500.0)
128        .map_items(|p| format!("{} - ${:.2}", p.name, p.price))
129        .collect();
130    
131    println!("   Affordable electronics:");
132    for item in &formatted {
133        println!("   - {}", item);
134    }
135    println!();
136
137    println!("7. Aggregation with Extension Trait");
138    println!("   Query: products.lazy_query().sum_by(Product::stock())");
139    
140    let total_stock = products
141        .lazy_query()
142        .sum_by(Product::stock_r());
143    
144    println!("   Total stock across all products: {}", total_stock);
145    println!();
146
147    println!("8. Find with Extension Trait");
148    println!("   Query: products.lazy_query().find(|p| p.name.contains(\"Chair\"))");
149    
150    if let Some(chair) = products.lazy_query().find(|p| p.name.contains("Chair")) {
151        println!("   Found: {} in {}", chair.name, chair.category);
152    }
153    println!();
154
155    println!("9. Early Termination with Extension Trait");
156    println!("   Query: products.lazy_query().where_(price > 1000).any()");
157    
158    let has_luxury = products
159        .lazy_query()
160        .where_(Product::price_r(), |&p| p > 1000.0)
161        .any();
162    
163    println!("   Has products over $1000: {}", has_luxury);
164    println!();
165
166    println!("10. Slice Extension Trait");
167    println!("    Query: (&products[..]).lazy_query().count()");
168    
169    let slice_count = (&products[..])
170        .lazy_query()
171        .count();
172    
173    println!("    Count from slice: {}", slice_count);
174    println!();
175
176    println!("Summary:");
177    println!("--------");
178    println!("✓ Extension trait QueryExt adds .query() and .lazy_query() to containers");
179    println!("✓ Derive macro QueryBuilder adds static methods Product::query() and Product::lazy_query()");
180    println!("✓ Both approaches provide the same query functionality");
181    println!("✓ Extension trait is more ergonomic: products.query() vs Query::new(&products)");
182    println!("✓ All iterator optimizations (fusion, early termination) still apply");
183}
More examples
Hide additional examples
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}
examples/arc_rwlock_hashmap.rs (line 106)
59fn main() {
60    println!("\n╔══════════════════════════════════════════════════════════════════╗");
61    println!("║  Arc<RwLock<T>> HashMap Lazy Query Demo                         ║");
62    println!("║  Thread-safe shared data with lazy evaluation                   ║");
63    println!("╚══════════════════════════════════════════════════════════════════╝\n");
64
65    let product_map = create_sample_data();
66    println!("Created product catalog:");
67    println!("  Total products: {}", product_map.len());
68    println!("  Keys: {:?}\n", product_map.keys().take(3).collect::<Vec<_>>());
69
70    // Extract products for querying
71    let products = extract_products(&product_map);
72    println!("Extracted {} products from Arc<RwLock<Product>>\n", products.len());
73
74    // ============================================================================
75    // LAZY OPERATION 1: where_ - Lazy Filtering
76    // ============================================================================
77    println!("═══════════════════════════════════════════════════════════════");
78    println!("Lazy Operation 1: where_ (filtering)");
79    println!("═══════════════════════════════════════════════════════════════\n");
80
81    println!("Building filtered query (nothing executes yet)...");
82    let electronics_query = LazyQuery::new(&products)
83        .where_(Product::category_r(), |cat| cat == "Electronics")
84        .where_(Product::active_r(), |&active| active)
85        .where_(Product::stock_r(), |&stock| stock > 20);
86
87    println!("  ✅ Query built (deferred execution)\n");
88
89    println!("Collecting results (executes now)...");
90    let electronics: Vec<_> = electronics_query.collect();
91    println!("  Found {} electronics in stock", electronics.len());
92    for p in &electronics {
93        println!("    • {}: {} in stock", p.name, p.stock);
94    }
95
96    // ============================================================================
97    // LAZY OPERATION 2: select_lazy - Lazy Projection
98    // ============================================================================
99    println!("\n═══════════════════════════════════════════════════════════════");
100    println!("Lazy Operation 2: select_lazy (projection)");
101    println!("═══════════════════════════════════════════════════════════════\n");
102
103    println!("Selecting product names (lazy)...");
104    let names: Vec<String> = LazyQuery::new(&products)
105        .where_(Product::category_r(), |cat| cat == "Furniture")
106        .select_lazy(Product::name_r())
107        .collect();
108
109    println!("  Furniture names ({}):", names.len());
110    for name in &names {
111        println!("    • {}", name);
112    }
113
114    // ============================================================================
115    // LAZY OPERATION 3: take_lazy - Early Termination
116    // ============================================================================
117    println!("\n═══════════════════════════════════════════════════════════════");
118    println!("Lazy Operation 3: take_lazy (early termination)");
119    println!("═══════════════════════════════════════════════════════════════\n");
120
121    println!("Getting first 3 electronics...");
122    let first_3: Vec<_> = LazyQuery::new(&products)
123        .where_(Product::category_r(), |cat| cat == "Electronics")
124        .take_lazy(3)
125        .collect();
126
127    println!("  First 3 electronics:");
128    for (i, p) in first_3.iter().enumerate() {
129        println!("    {}. {} - ${:.2}", i + 1, p.name, p.price);
130    }
131    println!("  ✅ Stopped after finding 3 items!");
132
133    // ============================================================================
134    // LAZY OPERATION 4: skip_lazy - Pagination
135    // ============================================================================
136    println!("\n═══════════════════════════════════════════════════════════════");
137    println!("Lazy Operation 4: skip_lazy (pagination)");
138    println!("═══════════════════════════════════════════════════════════════\n");
139
140    println!("Getting page 2 (skip 3, take 3)...");
141    let page_2: Vec<_> = LazyQuery::new(&products)
142        .where_(Product::active_r(), |&active| active)
143        .skip_lazy(3)
144        .take_lazy(3)
145        .collect();
146
147    println!("  Page 2 items:");
148    for (i, p) in page_2.iter().enumerate() {
149        println!("    {}. {}", i + 4, p.name);
150    }
151
152    // ============================================================================
153    // LAZY OPERATION 5: first - Short-Circuit Search
154    // ============================================================================
155    println!("\n═══════════════════════════════════════════════════════════════");
156    println!("Lazy Operation 5: first (short-circuit)");
157    println!("═══════════════════════════════════════════════════════════════\n");
158
159    println!("Finding first expensive item (>$1000)...");
160    let expensive = LazyQuery::new(&products)
161        .where_(Product::price_r(), |&price| price > 1000.0)
162        .first();
163
164    match expensive {
165        Some(p) => println!("  Found: {} - ${:.2}", p.name, p.price),
166        None => println!("  Not found"),
167    }
168    println!("  ✅ Stopped at first match!");
169
170    // ============================================================================
171    // LAZY OPERATION 6: any - Existence Check
172    // ============================================================================
173    println!("\n═══════════════════════════════════════════════════════════════");
174    println!("Lazy Operation 6: any (existence check)");
175    println!("═══════════════════════════════════════════════════════════════\n");
176
177    println!("Checking if any furniture exists...");
178    let has_furniture = LazyQuery::new(&products)
179        .where_(Product::category_r(), |cat| cat == "Furniture")
180        .any();
181
182    println!("  Has furniture: {}", has_furniture);
183    println!("  ✅ Stopped immediately after finding first match!");
184
185    // ============================================================================
186    // LAZY OPERATION 7: count - Count Matching Items
187    // ============================================================================
188    println!("\n═══════════════════════════════════════════════════════════════");
189    println!("Lazy Operation 7: count");
190    println!("═══════════════════════════════════════════════════════════════\n");
191
192    let electronics_count = LazyQuery::new(&products)
193        .where_(Product::category_r(), |cat| cat == "Electronics")
194        .count();
195
196    println!("  Electronics count: {}", electronics_count);
197
198    // ============================================================================
199    // LAZY OPERATION 8: sum_by - Aggregation
200    // ============================================================================
201    println!("\n═══════════════════════════════════════════════════════════════");
202    println!("Lazy Operation 8: sum_by (aggregation)");
203    println!("═══════════════════════════════════════════════════════════════\n");
204
205    let total_value: f64 = LazyQuery::new(&products)
206        .where_(Product::category_r(), |cat| cat == "Electronics")
207        .sum_by(Product::price_r());
208
209    println!("  Total electronics value: ${:.2}", total_value);
210
211    // ============================================================================
212    // LAZY OPERATION 9: avg_by - Average
213    // ============================================================================
214    println!("\n═══════════════════════════════════════════════════════════════");
215    println!("Lazy Operation 9: avg_by");
216    println!("═══════════════════════════════════════════════════════════════\n");
217
218    let avg_price = LazyQuery::new(&products)
219        .where_(Product::category_r(), |cat| cat == "Furniture")
220        .avg_by(Product::price_r())
221        .unwrap_or(0.0);
222
223    println!("  Average furniture price: ${:.2}", avg_price);
224
225    // ============================================================================
226    // LAZY OPERATION 10: min_by_float / max_by_float
227    // ============================================================================
228    println!("\n═══════════════════════════════════════════════════════════════");
229    println!("Lazy Operation 10: min_by_float / max_by_float");
230    println!("═══════════════════════════════════════════════════════════════\n");
231
232    let min_price = LazyQuery::new(&products)
233        .where_(Product::active_r(), |&active| active)
234        .min_by_float(Product::price_r())
235        .unwrap_or(0.0);
236
237    let max_price = LazyQuery::new(&products)
238        .where_(Product::active_r(), |&active| active)
239        .max_by_float(Product::price_r())
240        .unwrap_or(0.0);
241
242    println!("  Price range for active products:");
243    println!("    Min: ${:.2}", min_price);
244    println!("    Max: ${:.2}", max_price);
245
246    // ============================================================================
247    // LAZY OPERATION 11: find - Find with Predicate
248    // ============================================================================
249    println!("\n═══════════════════════════════════════════════════════════════");
250    println!("Lazy Operation 11: find (with predicate)");
251    println!("═══════════════════════════════════════════════════════════════\n");
252
253    let high_rated = LazyQuery::new(&products)
254        .where_(Product::category_r(), |cat| cat == "Electronics")
255        .find(|item| item.rating > 4.7);
256
257    if let Some(product) = high_rated {
258        println!("  First highly-rated electronic:");
259        println!("    {}: Rating {:.1}", product.name, product.rating);
260    }
261
262    // ============================================================================
263    // LAZY OPERATION 12: for_each - Iteration
264    // ============================================================================
265    println!("\n═══════════════════════════════════════════════════════════════");
266    println!("Lazy Operation 12: for_each (iteration)");
267    println!("═══════════════════════════════════════════════════════════════\n");
268
269    println!("  Low stock alerts:");
270    LazyQuery::new(&products)
271        .where_(Product::stock_r(), |&stock| stock < 20)
272        .for_each(|product| {
273            println!("    ⚠️  {}: Only {} in stock", product.name, product.stock);
274        });
275
276    // ============================================================================
277    // LAZY OPERATION 13: fold - Custom Aggregation
278    // ============================================================================
279    println!("\n═══════════════════════════════════════════════════════════════");
280    println!("Lazy Operation 14: fold (custom aggregation)");
281    println!("═══════════════════════════════════════════════════════════════\n");
282
283    let total_inventory_value = LazyQuery::new(&products)
284        .where_(Product::active_r(), |&active| active)
285        .fold(0.0, |acc, product| {
286            acc + (product.price * product.stock as f64)
287        });
288
289    println!("  Total inventory value: ${:.2}", total_inventory_value);
290
291    // ============================================================================
292    // LAZY OPERATION 14: all_match - Validation
293    // ============================================================================
294    println!("\n═══════════════════════════════════════════════════════════════");
295    println!("Lazy Operation 15: all_match (validation)");
296    println!("═══════════════════════════════════════════════════════════════\n");
297
298    let all_priced = LazyQuery::new(&products)
299        .all_match(|item| item.price > 0.0);
300
301    println!("  All products have valid prices: {}", all_priced);
302
303    // ============================================================================
304    // LAZY OPERATION 15: into_iter - For Loop
305    // ============================================================================
306    println!("\n═══════════════════════════════════════════════════════════════");
307    println!("Lazy Operation 16: into_iter (for loop)");
308    println!("═══════════════════════════════════════════════════════════════\n");
309
310    println!("  High-value products (>$300):");
311    for product in LazyQuery::new(&products)
312        .where_(Product::price_r(), |&p| p > 300.0)
313        .take_lazy(5)
314    {
315        println!("    • {}: ${:.2}", product.name, product.price);
316    }
317
318    // ============================================================================
319    // LAZY OPERATION 16: map_items - Transform
320    // ============================================================================
321    println!("\n═══════════════════════════════════════════════════════════════");
322    println!("Lazy Operation 17: map_items (transformation)");
323    println!("═══════════════════════════════════════════════════════════════\n");
324
325    let price_tags: Vec<String> = LazyQuery::new(&products)
326        .where_(Product::category_r(), |cat| cat == "Electronics")
327        .map_items(|p| format!("{}: ${:.2}", p.name, p.price))
328        .take(5)
329        .collect();
330
331    println!("  Electronics price tags:");
332    for tag in &price_tags {
333        println!("    • {}", tag);
334    }
335
336    // ============================================================================
337    // COMPLEX EXAMPLE: Multi-Stage Lazy Pipeline
338    // ============================================================================
339    println!("\n═══════════════════════════════════════════════════════════════");
340    println!("Complex Example: Multi-stage lazy pipeline");
341    println!("═══════════════════════════════════════════════════════════════\n");
342
343    println!("Building complex query:");
344    println!("  1. Filter by category (Electronics)");
345    println!("  2. Filter by price range ($50-$500)");
346    println!("  3. Filter by rating (>4.5)");
347    println!("  4. Select names");
348    println!("  5. Take first 3");
349    println!();
350
351    let results: Vec<String> = LazyQuery::new(&products)
352        .where_(Product::category_r(), |cat| cat == "Electronics")
353        .where_(Product::price_r(), |&p| p >= 50.0 && p <= 500.0)
354        .where_(Product::rating_r(), |&r| r > 4.5)
355        .select_lazy(Product::name_r())
356        .take(3)
357        .collect();
358
359    println!("  Results:");
360    for (i, name) in results.iter().enumerate() {
361        println!("    {}. {}", i + 1, name);
362    }
363    println!("  ✅ All operations fused and executed lazily!");
364
365    // ============================================================================
366    // THREAD-SAFE UPDATES WITH RWLOCK
367    // ============================================================================
368    println!("\n═══════════════════════════════════════════════════════════════");
369    println!("Bonus: Thread-safe updates with RwLock");
370    println!("═══════════════════════════════════════════════════════════════\n");
371
372    // Update a product through the Arc<RwLock>
373    if let Some(product_arc) = product_map.get("PROD-002") {
374        println!("Updating PROD-002 stock...");
375        
376        // Write lock for mutation
377        if let Ok(mut product) = product_arc.write() {
378            let old_stock = product.stock;
379            product.stock = 25;
380            println!("  Stock updated: {} → {}", old_stock, product.stock);
381        }
382    }
383
384    // Query again to see the update
385    let updated_products = extract_products(&product_map);
386    let mouse = LazyQuery::new(&updated_products)
387        .find(|p| p.id == 2);
388
389    if let Some(product) = mouse {
390        println!("  Verified update: {} now has {} in stock", product.name, product.stock);
391    }
392
393    // ============================================================================
394    // PRACTICAL EXAMPLE: Price Analysis by Category
395    // ============================================================================
396    println!("\n═══════════════════════════════════════════════════════════════");
397    println!("Practical Example: Price analysis by category");
398    println!("═══════════════════════════════════════════════════════════════\n");
399
400    let categories = vec!["Electronics", "Furniture"];
401
402    for category in categories {
403        println!("  {} Statistics:", category);
404        
405        // Filter products by category first
406        let cat_products: Vec<Product> = products.iter()
407            .filter(|p| p.category == category)
408            .cloned()
409            .collect();
410
411        let count = LazyQuery::new(&cat_products).count();
412        let total = LazyQuery::new(&cat_products).sum_by(Product::price_r());
413        let avg = LazyQuery::new(&cat_products).avg_by(Product::price_r()).unwrap_or(0.0);
414        let min = LazyQuery::new(&cat_products).min_by_float(Product::price_r()).unwrap_or(0.0);
415        let max = LazyQuery::new(&cat_products).max_by_float(Product::price_r()).unwrap_or(0.0);
416
417        println!("    Count: {}", count);
418        println!("    Total: ${:.2}", total);
419        println!("    Average: ${:.2}", avg);
420        println!("    Range: ${:.2} - ${:.2}\n", min, max);
421    }
422
423    // ============================================================================
424    // COMBINING WITH HASHMAP OPERATIONS
425    // ============================================================================
426    println!("═══════════════════════════════════════════════════════════════");
427    println!("HashMap Integration: Query by key patterns");
428    println!("═══════════════════════════════════════════════════════════════\n");
429
430    // Filter HashMap by key pattern
431    let electronics_keys: Vec<String> = product_map
432        .iter()
433        .filter(|(_key, value)| {
434            // Read the value to check category
435            if let Ok(guard) = value.read() {
436                guard.category == "Electronics"
437            } else {
438                false
439            }
440        })
441        .map(|(key, _value)| key.clone())
442        .collect();
443
444    println!("  Electronics product IDs:");
445    for key in electronics_keys.iter().take(5) {
446        println!("    • {}", key);
447    }
448
449    // ============================================================================
450    // PERFORMANCE DEMONSTRATION
451    // ============================================================================
452    println!("\n═══════════════════════════════════════════════════════════════");
453    println!("Performance: Lazy vs Eager comparison");
454    println!("═══════════════════════════════════════════════════════════════\n");
455
456    println!("Scenario: Find first product with rating > 4.7 from {} products\n", products.len());
457
458    println!("  Eager approach (hypothetical):");
459    println!("    - Filter all {} products", products.len());
460    println!("    - Collect filtered results");
461    println!("    - Take first item");
462    println!("    - Wasted work: Check all items\n");
463
464    println!("  Lazy approach (actual):");
465    let _first_rated = LazyQuery::new(&products)
466        .where_(Product::rating_r(), |&r| r > 4.7)
467        .first();
468    println!("    - Starts checking products");
469    println!("    - Stops at first match");
470    println!("    - ✅ Early termination - checks ~3-5 items only!");
471
472    // ============================================================================
473    // Summary
474    // ============================================================================
475    println!("\n╔══════════════════════════════════════════════════════════════════╗");
476    println!("║  Summary: All Lazy Operations Demonstrated                      ║");
477    println!("╚══════════════════════════════════════════════════════════════════╝\n");
478
479    println!("✅ Lazy Query Operations:");
480    println!("   1. ✅ where_ - Lazy filtering");
481    println!("   2. ✅ select_lazy - Lazy projection");
482    println!("   3. ✅ take_lazy - Early termination");
483    println!("   4. ✅ skip_lazy - Pagination");
484    println!("   5. ✅ first - Short-circuit search");
485    println!("   6. ✅ any - Existence check (short-circuit)");
486    println!("   7. ✅ count - Count items");
487    println!("   8. ✅ sum_by - Sum aggregation");
488    println!("   9. ✅ avg_by - Average aggregation");
489    println!("   10. ✅ min_by_float - Minimum value");
490    println!("   11. ✅ max_by_float - Maximum value");
491    println!("   12. ✅ find - Find with predicate (short-circuit)");
492    println!("   13. ✅ for_each - Iteration");
493    println!("   14. ✅ fold - Custom aggregation");
494    println!("   15. ✅ all_match - Validation (short-circuit)");
495    println!("   16. ✅ into_iter - For loop support");
496    println!("   17. ✅ map_items - Transformation\n");
497
498    println!("✅ Arc<RwLock<T>> Benefits:");
499    println!("   • Thread-safe shared access");
500    println!("   • Interior mutability");
501    println!("   • Multiple readers, single writer");
502    println!("   • Reference counting (Arc)");
503    println!("   • Can be queried after extracting data\n");
504
505    println!("✅ HashMap<K, Arc<RwLock<V>>> Benefits:");
506    println!("   • Fast key-based lookup");
507    println!("   • Thread-safe value access");
508    println!("   • Can query all values");
509    println!("   • Can filter by key patterns");
510    println!("   • Perfect for shared state/caches\n");
511
512    println!("🎯 Use Cases:");
513    println!("   • Shared product catalogs");
514    println!("   • User session stores");
515    println!("   • Configuration caches");
516    println!("   • Real-time inventory systems");
517    println!("   • Multi-threaded data processing");
518    println!("   • Web server state management\n");
519
520    println!("✓ Arc<RwLock<T>> HashMap with all lazy operations demo complete!\n");
521}
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/derive_and_ext.rs (line 89)
13fn main() {
14    println!("Derive Macros and Extension Traits Example");
15    println!("===========================================\n");
16
17    let products = vec![
18        Product {
19            id: 1,
20            name: "Laptop".to_string(),
21            price: 999.99,
22            category: "Electronics".to_string(),
23            stock: 5,
24        },
25        Product {
26            id: 2,
27            name: "Mouse".to_string(),
28            price: 29.99,
29            category: "Electronics".to_string(),
30            stock: 50,
31        },
32        Product {
33            id: 3,
34            name: "Keyboard".to_string(),
35            price: 79.99,
36            category: "Electronics".to_string(),
37            stock: 30,
38        },
39        Product {
40            id: 4,
41            name: "Monitor".to_string(),
42            price: 299.99,
43            category: "Electronics".to_string(),
44            stock: 12,
45        },
46        Product {
47            id: 5,
48            name: "Desk Chair".to_string(),
49            price: 199.99,
50            category: "Furniture".to_string(),
51            stock: 8,
52        },
53    ];
54
55    println!("1. Using Extension Trait - Direct .query() on Vec");
56    println!("   Query: products.query().where_(price > 100).all()");
57    
58    let query = products
59        .query()
60        .where_(Product::price_r(), |&p| p > 100.0);
61    let expensive = query.all();
62    
63    println!("   Found {} expensive products:", expensive.len());
64    for product in &expensive {
65        println!("   - {} (${:.2})", product.name, product.price);
66    }
67    println!();
68
69    println!("2. Using Extension Trait - Direct .lazy_query() on Vec");
70    println!("   Query: products.lazy_query().where_(stock < 10).collect()");
71    
72    let low_stock: Vec<_> = products
73        .lazy_query()
74        .where_(Product::stock_r(), |&s| s < 10)
75        .collect();
76    
77    println!("   Found {} low stock products:", low_stock.len());
78    for product in &low_stock {
79        println!("   - {} (stock: {})", product.name, product.stock);
80    }
81    println!();
82
83    println!("3. Using Extension Trait - Chained Operations");
84    println!("   Query: products.lazy_query().where_(category == Electronics).take(2).select(name).collect()");
85    
86    let names: Vec<String> = products
87        .lazy_query()
88        .where_(Product::category_r(), |cat| cat == "Electronics")
89        .take_lazy(2)
90        .select_lazy(Product::name_r())
91        .collect();
92    
93    println!("   First 2 electronics:");
94    for name in &names {
95        println!("   - {}", name);
96    }
97    println!();
98
99    println!("4. Using QueryBuilder Derive - Static Methods");
100    println!("   Query: Product::query(&products).where_(price > 50).count()");
101    
102    let query4 = Product::query(&products)
103        .where_(Product::price_r(), |&p| p > 50.0);
104    let count = query4.count();
105    
106    println!("   Products over $50: {}", count);
107    println!();
108
109    println!("5. Using QueryBuilder Derive - Lazy Static Methods");
110    println!("   Query: Product::lazy_query(&products).first()");
111    
112    if let Some(first) = Product::lazy_query(&products).first() {
113        println!("   First product: {} (${:.2})", first.name, first.price);
114    }
115    println!();
116
117    println!("6. Complex Chain with Extension Trait");
118    println!("   Query: products.lazy_query()");
119    println!("          .where_(category == Electronics)");
120    println!("          .where_(price < 500)");
121    println!("          .map(|p| format!(\"{{}} - ${{:.2}}\", p.name, p.price))");
122    println!("          .collect()");
123    
124    let formatted: Vec<String> = products
125        .lazy_query()
126        .where_(Product::category_r(), |cat| cat == "Electronics")
127        .where_(Product::price_r(), |&p| p < 500.0)
128        .map_items(|p| format!("{} - ${:.2}", p.name, p.price))
129        .collect();
130    
131    println!("   Affordable electronics:");
132    for item in &formatted {
133        println!("   - {}", item);
134    }
135    println!();
136
137    println!("7. Aggregation with Extension Trait");
138    println!("   Query: products.lazy_query().sum_by(Product::stock())");
139    
140    let total_stock = products
141        .lazy_query()
142        .sum_by(Product::stock_r());
143    
144    println!("   Total stock across all products: {}", total_stock);
145    println!();
146
147    println!("8. Find with Extension Trait");
148    println!("   Query: products.lazy_query().find(|p| p.name.contains(\"Chair\"))");
149    
150    if let Some(chair) = products.lazy_query().find(|p| p.name.contains("Chair")) {
151        println!("   Found: {} in {}", chair.name, chair.category);
152    }
153    println!();
154
155    println!("9. Early Termination with Extension Trait");
156    println!("   Query: products.lazy_query().where_(price > 1000).any()");
157    
158    let has_luxury = products
159        .lazy_query()
160        .where_(Product::price_r(), |&p| p > 1000.0)
161        .any();
162    
163    println!("   Has products over $1000: {}", has_luxury);
164    println!();
165
166    println!("10. Slice Extension Trait");
167    println!("    Query: (&products[..]).lazy_query().count()");
168    
169    let slice_count = (&products[..])
170        .lazy_query()
171        .count();
172    
173    println!("    Count from slice: {}", slice_count);
174    println!();
175
176    println!("Summary:");
177    println!("--------");
178    println!("✓ Extension trait QueryExt adds .query() and .lazy_query() to containers");
179    println!("✓ Derive macro QueryBuilder adds static methods Product::query() and Product::lazy_query()");
180    println!("✓ Both approaches provide the same query functionality");
181    println!("✓ Extension trait is more ergonomic: products.query() vs Query::new(&products)");
182    println!("✓ All iterator optimizations (fusion, early termination) still apply");
183}
More examples
Hide additional examples
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}
examples/macro_helpers.rs (line 329)
36fn main() {
37    println!("\n╔════════════════════════════════════════════════════════════════╗");
38    println!("║  Macro Helpers Demo - Reducing Boilerplate                    ║");
39    println!("╚════════════════════════════════════════════════════════════════╝\n");
40
41    let products = create_products();
42
43    // ============================================================================
44    // EXAMPLE 1: Simple Collection
45    // ============================================================================
46    println!("═══════════════════════════════════════════════════════════════");
47    println!("Example 1: collect_lazy! - Simple collection");
48    println!("═══════════════════════════════════════════════════════════════\n");
49
50    println!("❌ Without macro (verbose):");
51    println!("```rust");
52    println!("let results: Vec<_> = LazyQuery::new(&products).collect();");
53    println!("```\n");
54
55    println!("✅ With macro (concise):");
56    println!("```rust");
57    println!("let results = collect_lazy!(&products);");
58    println!("```\n");
59
60    let results = collect_lazy!(&products);
61    println!("Result: {} products collected\n", results.len());
62
63    // ============================================================================
64    // EXAMPLE 2: Filter and Collect
65    // ============================================================================
66    println!("═══════════════════════════════════════════════════════════════");
67    println!("Example 2: filter_collect! - Filter and collect");
68    println!("═══════════════════════════════════════════════════════════════\n");
69
70    println!("❌ Without macro (verbose):");
71    println!("```rust");
72    println!("let electronics: Vec<_> = LazyQuery::new(&products)");
73    println!("    .where_(Product::category_r(), |cat| cat == \"Electronics\")");
74    println!("    .collect();");
75    println!("```\n");
76
77    println!("✅ With macro (concise):");
78    println!("```rust");
79    println!("let electronics = filter_collect!(");
80    println!("    &products,");
81    println!("    Product::category_r(),");
82    println!("    |cat| cat == \"Electronics\"");
83    println!(");");
84    println!("```\n");
85
86    let electronics = filter_collect!(
87        &products,
88        Product::category_r(),
89        |cat| cat == "Electronics"
90    );
91    println!("Result: {} electronics\n", electronics.len());
92
93    // ============================================================================
94    // EXAMPLE 3: Count with Filter
95    // ============================================================================
96    println!("═══════════════════════════════════════════════════════════════");
97    println!("Example 3: count_where! - Count with filter");
98    println!("═══════════════════════════════════════════════════════════════\n");
99
100    println!("❌ Without macro (verbose):");
101    println!("```rust");
102    println!("let count = LazyQuery::new(&products)");
103    println!("    .where_(Product::stock_r(), |&s| s > 0)");
104    println!("    .count();");
105    println!("```\n");
106
107    println!("✅ With macro (concise):");
108    println!("```rust");
109    println!("let count = count_where!(&products, Product::stock_r(), |&s| s > 0);");
110    println!("```\n");
111
112    let count = count_where!(&products, Product::stock_r(), |&s| s > 0);
113    println!("Result: {} products in stock\n", count);
114
115    // ============================================================================
116    // EXAMPLE 4: Find First
117    // ============================================================================
118    println!("═══════════════════════════════════════════════════════════════");
119    println!("Example 4: find_first! - Find first matching item");
120    println!("═══════════════════════════════════════════════════════════════\n");
121
122    println!("❌ Without macro (verbose):");
123    println!("```rust");
124    println!("let found = LazyQuery::new(&products)");
125    println!("    .where_(Product::price_r(), |&p| p > 500.0)");
126    println!("    .first();");
127    println!("```\n");
128
129    println!("✅ With macro (concise):");
130    println!("```rust");
131    println!("let found = find_first!(&products, Product::price_r(), |&p| p > 500.0);");
132    println!("```\n");
133
134    let found = find_first!(&products, Product::price_r(), |&p| p > 500.0);
135    if let Some(p) = found {
136        println!("Result: Found {} at ${:.2}\n", p.name, p.price);
137    }
138
139    // ============================================================================
140    // EXAMPLE 5: Existence Check
141    // ============================================================================
142    println!("═══════════════════════════════════════════════════════════════");
143    println!("Example 5: exists_where! - Check if any item matches");
144    println!("═══════════════════════════════════════════════════════════════\n");
145
146    println!("❌ Without macro (verbose):");
147    println!("```rust");
148    println!("let has_furniture = LazyQuery::new(&products)");
149    println!("    .where_(Product::category_r(), |cat| cat == \"Furniture\")");
150    println!("    .any();");
151    println!("```\n");
152
153    println!("✅ With macro (concise):");
154    println!("```rust");
155    println!("let has_furniture = exists_where!(");
156    println!("    &products,");
157    println!("    Product::category_r(),");
158    println!("    |cat| cat == \"Furniture\"");
159    println!(");");
160    println!("```\n");
161
162    let has_furniture = exists_where!(
163        &products,
164        Product::category_r(),
165        |cat| cat == "Furniture"
166    );
167    println!("Result: Has furniture = {}\n", has_furniture);
168
169    // ============================================================================
170    // EXAMPLE 6: Pagination
171    // ============================================================================
172    println!("═══════════════════════════════════════════════════════════════");
173    println!("Example 6: paginate! - Quick pagination");
174    println!("═══════════════════════════════════════════════════════════════\n");
175
176    println!("❌ Without macro (verbose):");
177    println!("```rust");
178    println!("let page_2: Vec<_> = LazyQuery::new(&products)");
179    println!("    .skip_lazy(1 * 2)  // page * size");
180    println!("    .take_lazy(2)");
181    println!("    .collect();");
182    println!("```\n");
183
184    println!("✅ With macro (concise):");
185    println!("```rust");
186    println!("let page_2 = paginate!(&products, page: 1, size: 2);");
187    println!("```\n");
188
189    let page_2 = paginate!(&products, page: 1, size: 2);
190    println!("Result: Page 2 has {} items\n", page_2.len());
191
192    // ============================================================================
193    // EXAMPLE 7: Sum with Filter
194    // ============================================================================
195    println!("═══════════════════════════════════════════════════════════════");
196    println!("Example 7: sum_where! - Sum with filter");
197    println!("═══════════════════════════════════════════════════════════════\n");
198
199    println!("❌ Without macro (verbose):");
200    println!("```rust");
201    println!("let total: f64 = LazyQuery::new(&products)");
202    println!("    .where_(Product::active_r(), |&a| a)");
203    println!("    .sum_by(Product::price_r());");
204    println!("```\n");
205
206    println!("✅ With macro (concise):");
207    println!("```rust");
208    println!("let total = sum_where!(&products, Product::price_r(), Product::active_r(), |&a| a);");
209    println!("```\n");
210
211    let total = sum_where!(&products, Product::price_r(), Product::active_r(), |&a| a);
212    println!("Result: Total active products value = ${:.2}\n", total);
213
214    // ============================================================================
215    // EXAMPLE 8: Average with Filter
216    // ============================================================================
217    println!("═══════════════════════════════════════════════════════════════");
218    println!("Example 8: avg_where! - Average with filter");
219    println!("═══════════════════════════════════════════════════════════════\n");
220
221    println!("❌ Without macro (verbose):");
222    println!("```rust");
223    println!("let avg = LazyQuery::new(&products)");
224    println!("    .where_(Product::category_r(), |cat| cat == \"Electronics\")");
225    println!("    .avg_by(Product::price_r())");
226    println!("    .unwrap_or(0.0);");
227    println!("```\n");
228
229    println!("✅ With macro (concise):");
230    println!("```rust");
231    println!("let avg = avg_where!(");
232    println!("    &products,");
233    println!("    Product::price_r(),");
234    println!("    Product::category_r(),");
235    println!("    |cat| cat == \"Electronics\"");
236    println!(").unwrap_or(0.0);");
237    println!("```\n");
238
239    let avg = avg_where!(
240        &products,
241        Product::price_r(),
242        Product::category_r(),
243        |cat| cat == "Electronics"
244    ).unwrap_or(0.0);
245    println!("Result: Average electronics price = ${:.2}\n", avg);
246
247    // ============================================================================
248    // EXAMPLE 9: Select All
249    // ============================================================================
250    println!("═══════════════════════════════════════════════════════════════");
251    println!("Example 9: select_all! - Select field from all items");
252    println!("═══════════════════════════════════════════════════════════════\n");
253
254    println!("❌ Without macro (verbose):");
255    println!("```rust");
256    println!("let names: Vec<String> = LazyQuery::new(&products)");
257    println!("    .select_lazy(Product::name_r())");
258    println!("    .collect();");
259    println!("```\n");
260
261    println!("✅ With macro (concise):");
262    println!("```rust");
263    println!("let names = select_all!(&products, Product::name_r());");
264    println!("```\n");
265
266    let names: Vec<String> = select_all!(&products, Product::name_r());
267    println!("Result: {} product names\n", names.len());
268
269    // ============================================================================
270    // EXAMPLE 10: Select with Filter
271    // ============================================================================
272    println!("═══════════════════════════════════════════════════════════════");
273    println!("Example 10: select_where! - Select field with filter");
274    println!("═══════════════════════════════════════════════════════════════\n");
275
276    println!("❌ Without macro (verbose):");
277    println!("```rust");
278    println!("let furniture_names: Vec<String> = LazyQuery::new(&products)");
279    println!("    .where_(Product::category_r(), |cat| cat == \"Furniture\")");
280    println!("    .select_lazy(Product::name_r())");
281    println!("    .collect();");
282    println!("```\n");
283
284    println!("✅ With macro (concise):");
285    println!("```rust");
286    println!("let furniture_names = select_where!(");
287    println!("    &products,");
288    println!("    Product::name_r(),");
289    println!("    Product::category_r(),");
290    println!("    |cat| cat == \"Furniture\"");
291    println!(");");
292    println!("```\n");
293
294    let furniture_names: Vec<String> = select_where!(
295        &products,
296        Product::name_r(),
297        Product::category_r(),
298        |cat| cat == "Furniture"
299    );
300    println!("Result: {} furniture items\n", furniture_names.len());
301
302    // ============================================================================
303    // COMPARISON: Complex Query
304    // ============================================================================
305    println!("═══════════════════════════════════════════════════════════════");
306    println!("Complex Example: Before & After");
307    println!("═══════════════════════════════════════════════════════════════\n");
308
309    println!("Scenario: Filter electronics, under $500, in stock, get first 5\n");
310
311    println!("❌ WITHOUT MACROS (13 lines):");
312    println!("```rust");
313    println!("let results: Vec<_> = LazyQuery::new(&products)");
314    println!("    .where_(");
315    println!("        Product::category_r(),");
316    println!("        |cat| cat == \"Electronics\"");
317    println!("    )");
318    println!("    .where_(Product::price_r(), |&p| p < 500.0)");
319    println!("    .where_(Product::stock_r(), |&s| s > 0)");
320    println!("    .take_lazy(5)");
321    println!("    .collect();");
322    println!("```\n");
323
324    // Actual verbose version
325    let verbose_results: Vec<_> = LazyQuery::new(&products)
326        .where_(Product::category_r(), |cat| cat == "Electronics")
327        .where_(Product::price_r(), |&p| p < 500.0)
328        .where_(Product::stock_r(), |&s| s > 0)
329        .take_lazy(5)
330        .collect();
331
332    println!("✅ WITH MACROS (Shorter, but still need multiple filters):");
333    println!("```rust");
334    println!("let results = lazy_query!(&products)");
335    println!("    .where_(Product::category_r(), |cat| cat == \"Electronics\")");
336    println!("    .where_(Product::price_r(), |&p| p < 500.0)");
337    println!("    .where_(Product::stock_r(), |&s| s > 0)");
338    println!("    .take_lazy(5)");
339    println!("    .collect();");
340    println!("```\n");
341
342    let macro_results = lazy_query!(&products)
343        .where_(Product::category_r(), |cat| cat == "Electronics")
344        .where_(Product::price_r(), |&p| p < 500.0)
345        .where_(Product::stock_r(), |&s| s > 0)
346        .take_lazy(5)
347        .collect();
348
349    println!("Both approaches found {} items ✅\n", verbose_results.len());
350    assert_eq!(verbose_results.len(), macro_results.len());
351
352    // ============================================================================
353    // CODE REDUCTION METRICS
354    // ============================================================================
355    println!("═══════════════════════════════════════════════════════════════");
356    println!("Code Reduction Metrics");
357    println!("═══════════════════════════════════════════════════════════════\n");
358
359    println!("Pattern Comparisons:\n");
360
361    println!("  1. Simple collect:");
362    println!("     Before: LazyQuery::new(&data).collect()");
363    println!("     After:  collect_lazy!(&data)");
364    println!("     Saved:  ~20 characters\n");
365
366    println!("  2. Filter + collect:");
367    println!("     Before: LazyQuery::new(&data).where_(...).collect()");
368    println!("     After:  filter_collect!(&data, field, pred)");
369    println!("     Saved:  ~35 characters\n");
370
371    println!("  3. Count with filter:");
372    println!("     Before: LazyQuery::new(&data).where_(...).count()");
373    println!("     After:  count_where!(&data, field, pred)");
374    println!("     Saved:  ~30 characters\n");
375
376    println!("  4. Pagination:");
377    println!("     Before: LazyQuery::new(&data).skip_lazy(p*s).take_lazy(s).collect()");
378    println!("     After:  paginate!(&data, page: p, size: s)");
379    println!("     Saved:  ~45 characters\n");
380
381    println!("  5. Sum with filter:");
382    println!("     Before: LazyQuery::new(&data).where_(...).sum_by(...)");
383    println!("     After:  sum_where!(&data, sum_field, filter_field, pred)");
384    println!("     Saved:  ~25 characters\n");
385
386    // ============================================================================
387    // ALL MACRO DEMONSTRATIONS
388    // ============================================================================
389    println!("═══════════════════════════════════════════════════════════════");
390    println!("All Available Macros - Quick Reference");
391    println!("═══════════════════════════════════════════════════════════════\n");
392
393    println!("1. lazy_query!(&data)");
394    let _q1 = lazy_query!(&products);
395    println!("   → LazyQuery::new(&data)\n");
396
397    println!("2. query!(&data)");
398    let _q2 = query!(&products);
399    println!("   → Query::new(&data)\n");
400
401    println!("3. collect_lazy!(&data)");
402    let _r3 = collect_lazy!(&products);
403    println!("   → LazyQuery::new(&data).collect()\n");
404
405    println!("4. filter_collect!(&data, field, pred)");
406    let _r4 = filter_collect!(&products, Product::active_r(), |&a| a);
407    println!("   → LazyQuery::new(&data).where_(field, pred).collect()\n");
408
409    println!("5. count_where!(&data, field, pred)");
410    let _r5 = count_where!(&products, Product::active_r(), |&a| a);
411    println!("   → LazyQuery::new(&data).where_(field, pred).count()\n");
412
413    println!("6. find_first!(&data, field, pred)");
414    let _r6 = find_first!(&products, Product::id_r(), |&id| id == 1);
415    println!("   → LazyQuery::new(&data).where_(field, pred).first()\n");
416
417    println!("7. exists_where!(&data, field, pred)");
418    let _r7 = exists_where!(&products, Product::active_r(), |&a| a);
419    println!("   → LazyQuery::new(&data).where_(field, pred).any()\n");
420
421    println!("8. paginate!(&data, page: p, size: s)");
422    let _r8 = paginate!(&products, page: 0, size: 3);
423    println!("   → LazyQuery::new(&data).skip_lazy(p*s).take_lazy(s).collect()\n");
424
425    println!("9. sum_where!(&data, sum_field, filter_field, pred)");
426    let _r9 = sum_where!(&products, Product::price_r(), Product::active_r(), |&a| a);
427    println!("   → LazyQuery::new(&data).where_(filter_field, pred).sum_by(sum_field)\n");
428
429    println!("10. avg_where!(&data, avg_field, filter_field, pred)");
430    let _r10 = avg_where!(&products, Product::price_r(), Product::active_r(), |&a| a);
431    println!("    → LazyQuery::new(&data).where_(filter_field, pred).avg_by(avg_field)\n");
432
433    println!("11. select_all!(&data, field)");
434    let _r11: Vec<String> = select_all!(&products, Product::name_r());
435    println!("    → LazyQuery::new(&data).select_lazy(field).collect()\n");
436
437    println!("12. select_where!(&data, select_field, filter_field, pred)");
438    let _r12: Vec<String> = select_where!(&products, Product::name_r(), Product::active_r(), |&a| a);
439    println!("    → LazyQuery::new(&data).where_(filter, pred).select_lazy(field).collect()\n");
440
441    // ============================================================================
442    // Summary
443    // ============================================================================
444    println!("╔════════════════════════════════════════════════════════════════╗");
445    println!("║  Summary                                                       ║");
446    println!("╚════════════════════════════════════════════════════════════════╝\n");
447
448    println!("✅ 12 helper macros provided:");
449    println!("   • lazy_query! - Create LazyQuery");
450    println!("   • query! - Create Query");
451    println!("   • collect_lazy! - Quick collect");
452    println!("   • filter_collect! - Filter and collect");
453    println!("   • count_where! - Count with filter");
454    println!("   • find_first! - Find first match");
455    println!("   • exists_where! - Existence check");
456    println!("   • paginate! - Easy pagination");
457    println!("   • sum_where! - Sum with filter");
458    println!("   • avg_where! - Average with filter");
459    println!("   • select_all! - Select all");
460    println!("   • select_where! - Select with filter\n");
461
462    println!("📊 Benefits:");
463    println!("   • Less typing (20-45 characters saved per operation)");
464    println!("   • More readable code");
465    println!("   • Common patterns encapsulated");
466    println!("   • Same performance (zero-cost abstraction)");
467    println!("   • Type-safe (compile-time checked)\n");
468
469    println!("💡 When to use:");
470    println!("   • Use macros for simple, common patterns");
471    println!("   • Use full API for complex queries");
472    println!("   • Mix and match as needed\n");
473
474    println!("✓ Macro helpers demo complete!\n");
475}
examples/arc_rwlock_hashmap.rs (line 124)
59fn main() {
60    println!("\n╔══════════════════════════════════════════════════════════════════╗");
61    println!("║  Arc<RwLock<T>> HashMap Lazy Query Demo                         ║");
62    println!("║  Thread-safe shared data with lazy evaluation                   ║");
63    println!("╚══════════════════════════════════════════════════════════════════╝\n");
64
65    let product_map = create_sample_data();
66    println!("Created product catalog:");
67    println!("  Total products: {}", product_map.len());
68    println!("  Keys: {:?}\n", product_map.keys().take(3).collect::<Vec<_>>());
69
70    // Extract products for querying
71    let products = extract_products(&product_map);
72    println!("Extracted {} products from Arc<RwLock<Product>>\n", products.len());
73
74    // ============================================================================
75    // LAZY OPERATION 1: where_ - Lazy Filtering
76    // ============================================================================
77    println!("═══════════════════════════════════════════════════════════════");
78    println!("Lazy Operation 1: where_ (filtering)");
79    println!("═══════════════════════════════════════════════════════════════\n");
80
81    println!("Building filtered query (nothing executes yet)...");
82    let electronics_query = LazyQuery::new(&products)
83        .where_(Product::category_r(), |cat| cat == "Electronics")
84        .where_(Product::active_r(), |&active| active)
85        .where_(Product::stock_r(), |&stock| stock > 20);
86
87    println!("  ✅ Query built (deferred execution)\n");
88
89    println!("Collecting results (executes now)...");
90    let electronics: Vec<_> = electronics_query.collect();
91    println!("  Found {} electronics in stock", electronics.len());
92    for p in &electronics {
93        println!("    • {}: {} in stock", p.name, p.stock);
94    }
95
96    // ============================================================================
97    // LAZY OPERATION 2: select_lazy - Lazy Projection
98    // ============================================================================
99    println!("\n═══════════════════════════════════════════════════════════════");
100    println!("Lazy Operation 2: select_lazy (projection)");
101    println!("═══════════════════════════════════════════════════════════════\n");
102
103    println!("Selecting product names (lazy)...");
104    let names: Vec<String> = LazyQuery::new(&products)
105        .where_(Product::category_r(), |cat| cat == "Furniture")
106        .select_lazy(Product::name_r())
107        .collect();
108
109    println!("  Furniture names ({}):", names.len());
110    for name in &names {
111        println!("    • {}", name);
112    }
113
114    // ============================================================================
115    // LAZY OPERATION 3: take_lazy - Early Termination
116    // ============================================================================
117    println!("\n═══════════════════════════════════════════════════════════════");
118    println!("Lazy Operation 3: take_lazy (early termination)");
119    println!("═══════════════════════════════════════════════════════════════\n");
120
121    println!("Getting first 3 electronics...");
122    let first_3: Vec<_> = LazyQuery::new(&products)
123        .where_(Product::category_r(), |cat| cat == "Electronics")
124        .take_lazy(3)
125        .collect();
126
127    println!("  First 3 electronics:");
128    for (i, p) in first_3.iter().enumerate() {
129        println!("    {}. {} - ${:.2}", i + 1, p.name, p.price);
130    }
131    println!("  ✅ Stopped after finding 3 items!");
132
133    // ============================================================================
134    // LAZY OPERATION 4: skip_lazy - Pagination
135    // ============================================================================
136    println!("\n═══════════════════════════════════════════════════════════════");
137    println!("Lazy Operation 4: skip_lazy (pagination)");
138    println!("═══════════════════════════════════════════════════════════════\n");
139
140    println!("Getting page 2 (skip 3, take 3)...");
141    let page_2: Vec<_> = LazyQuery::new(&products)
142        .where_(Product::active_r(), |&active| active)
143        .skip_lazy(3)
144        .take_lazy(3)
145        .collect();
146
147    println!("  Page 2 items:");
148    for (i, p) in page_2.iter().enumerate() {
149        println!("    {}. {}", i + 4, p.name);
150    }
151
152    // ============================================================================
153    // LAZY OPERATION 5: first - Short-Circuit Search
154    // ============================================================================
155    println!("\n═══════════════════════════════════════════════════════════════");
156    println!("Lazy Operation 5: first (short-circuit)");
157    println!("═══════════════════════════════════════════════════════════════\n");
158
159    println!("Finding first expensive item (>$1000)...");
160    let expensive = LazyQuery::new(&products)
161        .where_(Product::price_r(), |&price| price > 1000.0)
162        .first();
163
164    match expensive {
165        Some(p) => println!("  Found: {} - ${:.2}", p.name, p.price),
166        None => println!("  Not found"),
167    }
168    println!("  ✅ Stopped at first match!");
169
170    // ============================================================================
171    // LAZY OPERATION 6: any - Existence Check
172    // ============================================================================
173    println!("\n═══════════════════════════════════════════════════════════════");
174    println!("Lazy Operation 6: any (existence check)");
175    println!("═══════════════════════════════════════════════════════════════\n");
176
177    println!("Checking if any furniture exists...");
178    let has_furniture = LazyQuery::new(&products)
179        .where_(Product::category_r(), |cat| cat == "Furniture")
180        .any();
181
182    println!("  Has furniture: {}", has_furniture);
183    println!("  ✅ Stopped immediately after finding first match!");
184
185    // ============================================================================
186    // LAZY OPERATION 7: count - Count Matching Items
187    // ============================================================================
188    println!("\n═══════════════════════════════════════════════════════════════");
189    println!("Lazy Operation 7: count");
190    println!("═══════════════════════════════════════════════════════════════\n");
191
192    let electronics_count = LazyQuery::new(&products)
193        .where_(Product::category_r(), |cat| cat == "Electronics")
194        .count();
195
196    println!("  Electronics count: {}", electronics_count);
197
198    // ============================================================================
199    // LAZY OPERATION 8: sum_by - Aggregation
200    // ============================================================================
201    println!("\n═══════════════════════════════════════════════════════════════");
202    println!("Lazy Operation 8: sum_by (aggregation)");
203    println!("═══════════════════════════════════════════════════════════════\n");
204
205    let total_value: f64 = LazyQuery::new(&products)
206        .where_(Product::category_r(), |cat| cat == "Electronics")
207        .sum_by(Product::price_r());
208
209    println!("  Total electronics value: ${:.2}", total_value);
210
211    // ============================================================================
212    // LAZY OPERATION 9: avg_by - Average
213    // ============================================================================
214    println!("\n═══════════════════════════════════════════════════════════════");
215    println!("Lazy Operation 9: avg_by");
216    println!("═══════════════════════════════════════════════════════════════\n");
217
218    let avg_price = LazyQuery::new(&products)
219        .where_(Product::category_r(), |cat| cat == "Furniture")
220        .avg_by(Product::price_r())
221        .unwrap_or(0.0);
222
223    println!("  Average furniture price: ${:.2}", avg_price);
224
225    // ============================================================================
226    // LAZY OPERATION 10: min_by_float / max_by_float
227    // ============================================================================
228    println!("\n═══════════════════════════════════════════════════════════════");
229    println!("Lazy Operation 10: min_by_float / max_by_float");
230    println!("═══════════════════════════════════════════════════════════════\n");
231
232    let min_price = LazyQuery::new(&products)
233        .where_(Product::active_r(), |&active| active)
234        .min_by_float(Product::price_r())
235        .unwrap_or(0.0);
236
237    let max_price = LazyQuery::new(&products)
238        .where_(Product::active_r(), |&active| active)
239        .max_by_float(Product::price_r())
240        .unwrap_or(0.0);
241
242    println!("  Price range for active products:");
243    println!("    Min: ${:.2}", min_price);
244    println!("    Max: ${:.2}", max_price);
245
246    // ============================================================================
247    // LAZY OPERATION 11: find - Find with Predicate
248    // ============================================================================
249    println!("\n═══════════════════════════════════════════════════════════════");
250    println!("Lazy Operation 11: find (with predicate)");
251    println!("═══════════════════════════════════════════════════════════════\n");
252
253    let high_rated = LazyQuery::new(&products)
254        .where_(Product::category_r(), |cat| cat == "Electronics")
255        .find(|item| item.rating > 4.7);
256
257    if let Some(product) = high_rated {
258        println!("  First highly-rated electronic:");
259        println!("    {}: Rating {:.1}", product.name, product.rating);
260    }
261
262    // ============================================================================
263    // LAZY OPERATION 12: for_each - Iteration
264    // ============================================================================
265    println!("\n═══════════════════════════════════════════════════════════════");
266    println!("Lazy Operation 12: for_each (iteration)");
267    println!("═══════════════════════════════════════════════════════════════\n");
268
269    println!("  Low stock alerts:");
270    LazyQuery::new(&products)
271        .where_(Product::stock_r(), |&stock| stock < 20)
272        .for_each(|product| {
273            println!("    ⚠️  {}: Only {} in stock", product.name, product.stock);
274        });
275
276    // ============================================================================
277    // LAZY OPERATION 13: fold - Custom Aggregation
278    // ============================================================================
279    println!("\n═══════════════════════════════════════════════════════════════");
280    println!("Lazy Operation 14: fold (custom aggregation)");
281    println!("═══════════════════════════════════════════════════════════════\n");
282
283    let total_inventory_value = LazyQuery::new(&products)
284        .where_(Product::active_r(), |&active| active)
285        .fold(0.0, |acc, product| {
286            acc + (product.price * product.stock as f64)
287        });
288
289    println!("  Total inventory value: ${:.2}", total_inventory_value);
290
291    // ============================================================================
292    // LAZY OPERATION 14: all_match - Validation
293    // ============================================================================
294    println!("\n═══════════════════════════════════════════════════════════════");
295    println!("Lazy Operation 15: all_match (validation)");
296    println!("═══════════════════════════════════════════════════════════════\n");
297
298    let all_priced = LazyQuery::new(&products)
299        .all_match(|item| item.price > 0.0);
300
301    println!("  All products have valid prices: {}", all_priced);
302
303    // ============================================================================
304    // LAZY OPERATION 15: into_iter - For Loop
305    // ============================================================================
306    println!("\n═══════════════════════════════════════════════════════════════");
307    println!("Lazy Operation 16: into_iter (for loop)");
308    println!("═══════════════════════════════════════════════════════════════\n");
309
310    println!("  High-value products (>$300):");
311    for product in LazyQuery::new(&products)
312        .where_(Product::price_r(), |&p| p > 300.0)
313        .take_lazy(5)
314    {
315        println!("    • {}: ${:.2}", product.name, product.price);
316    }
317
318    // ============================================================================
319    // LAZY OPERATION 16: map_items - Transform
320    // ============================================================================
321    println!("\n═══════════════════════════════════════════════════════════════");
322    println!("Lazy Operation 17: map_items (transformation)");
323    println!("═══════════════════════════════════════════════════════════════\n");
324
325    let price_tags: Vec<String> = LazyQuery::new(&products)
326        .where_(Product::category_r(), |cat| cat == "Electronics")
327        .map_items(|p| format!("{}: ${:.2}", p.name, p.price))
328        .take(5)
329        .collect();
330
331    println!("  Electronics price tags:");
332    for tag in &price_tags {
333        println!("    • {}", tag);
334    }
335
336    // ============================================================================
337    // COMPLEX EXAMPLE: Multi-Stage Lazy Pipeline
338    // ============================================================================
339    println!("\n═══════════════════════════════════════════════════════════════");
340    println!("Complex Example: Multi-stage lazy pipeline");
341    println!("═══════════════════════════════════════════════════════════════\n");
342
343    println!("Building complex query:");
344    println!("  1. Filter by category (Electronics)");
345    println!("  2. Filter by price range ($50-$500)");
346    println!("  3. Filter by rating (>4.5)");
347    println!("  4. Select names");
348    println!("  5. Take first 3");
349    println!();
350
351    let results: Vec<String> = LazyQuery::new(&products)
352        .where_(Product::category_r(), |cat| cat == "Electronics")
353        .where_(Product::price_r(), |&p| p >= 50.0 && p <= 500.0)
354        .where_(Product::rating_r(), |&r| r > 4.5)
355        .select_lazy(Product::name_r())
356        .take(3)
357        .collect();
358
359    println!("  Results:");
360    for (i, name) in results.iter().enumerate() {
361        println!("    {}. {}", i + 1, name);
362    }
363    println!("  ✅ All operations fused and executed lazily!");
364
365    // ============================================================================
366    // THREAD-SAFE UPDATES WITH RWLOCK
367    // ============================================================================
368    println!("\n═══════════════════════════════════════════════════════════════");
369    println!("Bonus: Thread-safe updates with RwLock");
370    println!("═══════════════════════════════════════════════════════════════\n");
371
372    // Update a product through the Arc<RwLock>
373    if let Some(product_arc) = product_map.get("PROD-002") {
374        println!("Updating PROD-002 stock...");
375        
376        // Write lock for mutation
377        if let Ok(mut product) = product_arc.write() {
378            let old_stock = product.stock;
379            product.stock = 25;
380            println!("  Stock updated: {} → {}", old_stock, product.stock);
381        }
382    }
383
384    // Query again to see the update
385    let updated_products = extract_products(&product_map);
386    let mouse = LazyQuery::new(&updated_products)
387        .find(|p| p.id == 2);
388
389    if let Some(product) = mouse {
390        println!("  Verified update: {} now has {} in stock", product.name, product.stock);
391    }
392
393    // ============================================================================
394    // PRACTICAL EXAMPLE: Price Analysis by Category
395    // ============================================================================
396    println!("\n═══════════════════════════════════════════════════════════════");
397    println!("Practical Example: Price analysis by category");
398    println!("═══════════════════════════════════════════════════════════════\n");
399
400    let categories = vec!["Electronics", "Furniture"];
401
402    for category in categories {
403        println!("  {} Statistics:", category);
404        
405        // Filter products by category first
406        let cat_products: Vec<Product> = products.iter()
407            .filter(|p| p.category == category)
408            .cloned()
409            .collect();
410
411        let count = LazyQuery::new(&cat_products).count();
412        let total = LazyQuery::new(&cat_products).sum_by(Product::price_r());
413        let avg = LazyQuery::new(&cat_products).avg_by(Product::price_r()).unwrap_or(0.0);
414        let min = LazyQuery::new(&cat_products).min_by_float(Product::price_r()).unwrap_or(0.0);
415        let max = LazyQuery::new(&cat_products).max_by_float(Product::price_r()).unwrap_or(0.0);
416
417        println!("    Count: {}", count);
418        println!("    Total: ${:.2}", total);
419        println!("    Average: ${:.2}", avg);
420        println!("    Range: ${:.2} - ${:.2}\n", min, max);
421    }
422
423    // ============================================================================
424    // COMBINING WITH HASHMAP OPERATIONS
425    // ============================================================================
426    println!("═══════════════════════════════════════════════════════════════");
427    println!("HashMap Integration: Query by key patterns");
428    println!("═══════════════════════════════════════════════════════════════\n");
429
430    // Filter HashMap by key pattern
431    let electronics_keys: Vec<String> = product_map
432        .iter()
433        .filter(|(_key, value)| {
434            // Read the value to check category
435            if let Ok(guard) = value.read() {
436                guard.category == "Electronics"
437            } else {
438                false
439            }
440        })
441        .map(|(key, _value)| key.clone())
442        .collect();
443
444    println!("  Electronics product IDs:");
445    for key in electronics_keys.iter().take(5) {
446        println!("    • {}", key);
447    }
448
449    // ============================================================================
450    // PERFORMANCE DEMONSTRATION
451    // ============================================================================
452    println!("\n═══════════════════════════════════════════════════════════════");
453    println!("Performance: Lazy vs Eager comparison");
454    println!("═══════════════════════════════════════════════════════════════\n");
455
456    println!("Scenario: Find first product with rating > 4.7 from {} products\n", products.len());
457
458    println!("  Eager approach (hypothetical):");
459    println!("    - Filter all {} products", products.len());
460    println!("    - Collect filtered results");
461    println!("    - Take first item");
462    println!("    - Wasted work: Check all items\n");
463
464    println!("  Lazy approach (actual):");
465    let _first_rated = LazyQuery::new(&products)
466        .where_(Product::rating_r(), |&r| r > 4.7)
467        .first();
468    println!("    - Starts checking products");
469    println!("    - Stops at first match");
470    println!("    - ✅ Early termination - checks ~3-5 items only!");
471
472    // ============================================================================
473    // Summary
474    // ============================================================================
475    println!("\n╔══════════════════════════════════════════════════════════════════╗");
476    println!("║  Summary: All Lazy Operations Demonstrated                      ║");
477    println!("╚══════════════════════════════════════════════════════════════════╝\n");
478
479    println!("✅ Lazy Query Operations:");
480    println!("   1. ✅ where_ - Lazy filtering");
481    println!("   2. ✅ select_lazy - Lazy projection");
482    println!("   3. ✅ take_lazy - Early termination");
483    println!("   4. ✅ skip_lazy - Pagination");
484    println!("   5. ✅ first - Short-circuit search");
485    println!("   6. ✅ any - Existence check (short-circuit)");
486    println!("   7. ✅ count - Count items");
487    println!("   8. ✅ sum_by - Sum aggregation");
488    println!("   9. ✅ avg_by - Average aggregation");
489    println!("   10. ✅ min_by_float - Minimum value");
490    println!("   11. ✅ max_by_float - Maximum value");
491    println!("   12. ✅ find - Find with predicate (short-circuit)");
492    println!("   13. ✅ for_each - Iteration");
493    println!("   14. ✅ fold - Custom aggregation");
494    println!("   15. ✅ all_match - Validation (short-circuit)");
495    println!("   16. ✅ into_iter - For loop support");
496    println!("   17. ✅ map_items - Transformation\n");
497
498    println!("✅ Arc<RwLock<T>> Benefits:");
499    println!("   • Thread-safe shared access");
500    println!("   • Interior mutability");
501    println!("   • Multiple readers, single writer");
502    println!("   • Reference counting (Arc)");
503    println!("   • Can be queried after extracting data\n");
504
505    println!("✅ HashMap<K, Arc<RwLock<V>>> Benefits:");
506    println!("   • Fast key-based lookup");
507    println!("   • Thread-safe value access");
508    println!("   • Can query all values");
509    println!("   • Can filter by key patterns");
510    println!("   • Perfect for shared state/caches\n");
511
512    println!("🎯 Use Cases:");
513    println!("   • Shared product catalogs");
514    println!("   • User session stores");
515    println!("   • Configuration caches");
516    println!("   • Real-time inventory systems");
517    println!("   • Multi-threaded data processing");
518    println!("   • Web server state management\n");
519
520    println!("✓ Arc<RwLock<T>> HashMap with all lazy operations demo complete!\n");
521}
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();
Examples found in repository?
examples/arc_rwlock_hashmap.rs (line 143)
59fn main() {
60    println!("\n╔══════════════════════════════════════════════════════════════════╗");
61    println!("║  Arc<RwLock<T>> HashMap Lazy Query Demo                         ║");
62    println!("║  Thread-safe shared data with lazy evaluation                   ║");
63    println!("╚══════════════════════════════════════════════════════════════════╝\n");
64
65    let product_map = create_sample_data();
66    println!("Created product catalog:");
67    println!("  Total products: {}", product_map.len());
68    println!("  Keys: {:?}\n", product_map.keys().take(3).collect::<Vec<_>>());
69
70    // Extract products for querying
71    let products = extract_products(&product_map);
72    println!("Extracted {} products from Arc<RwLock<Product>>\n", products.len());
73
74    // ============================================================================
75    // LAZY OPERATION 1: where_ - Lazy Filtering
76    // ============================================================================
77    println!("═══════════════════════════════════════════════════════════════");
78    println!("Lazy Operation 1: where_ (filtering)");
79    println!("═══════════════════════════════════════════════════════════════\n");
80
81    println!("Building filtered query (nothing executes yet)...");
82    let electronics_query = LazyQuery::new(&products)
83        .where_(Product::category_r(), |cat| cat == "Electronics")
84        .where_(Product::active_r(), |&active| active)
85        .where_(Product::stock_r(), |&stock| stock > 20);
86
87    println!("  ✅ Query built (deferred execution)\n");
88
89    println!("Collecting results (executes now)...");
90    let electronics: Vec<_> = electronics_query.collect();
91    println!("  Found {} electronics in stock", electronics.len());
92    for p in &electronics {
93        println!("    • {}: {} in stock", p.name, p.stock);
94    }
95
96    // ============================================================================
97    // LAZY OPERATION 2: select_lazy - Lazy Projection
98    // ============================================================================
99    println!("\n═══════════════════════════════════════════════════════════════");
100    println!("Lazy Operation 2: select_lazy (projection)");
101    println!("═══════════════════════════════════════════════════════════════\n");
102
103    println!("Selecting product names (lazy)...");
104    let names: Vec<String> = LazyQuery::new(&products)
105        .where_(Product::category_r(), |cat| cat == "Furniture")
106        .select_lazy(Product::name_r())
107        .collect();
108
109    println!("  Furniture names ({}):", names.len());
110    for name in &names {
111        println!("    • {}", name);
112    }
113
114    // ============================================================================
115    // LAZY OPERATION 3: take_lazy - Early Termination
116    // ============================================================================
117    println!("\n═══════════════════════════════════════════════════════════════");
118    println!("Lazy Operation 3: take_lazy (early termination)");
119    println!("═══════════════════════════════════════════════════════════════\n");
120
121    println!("Getting first 3 electronics...");
122    let first_3: Vec<_> = LazyQuery::new(&products)
123        .where_(Product::category_r(), |cat| cat == "Electronics")
124        .take_lazy(3)
125        .collect();
126
127    println!("  First 3 electronics:");
128    for (i, p) in first_3.iter().enumerate() {
129        println!("    {}. {} - ${:.2}", i + 1, p.name, p.price);
130    }
131    println!("  ✅ Stopped after finding 3 items!");
132
133    // ============================================================================
134    // LAZY OPERATION 4: skip_lazy - Pagination
135    // ============================================================================
136    println!("\n═══════════════════════════════════════════════════════════════");
137    println!("Lazy Operation 4: skip_lazy (pagination)");
138    println!("═══════════════════════════════════════════════════════════════\n");
139
140    println!("Getting page 2 (skip 3, take 3)...");
141    let page_2: Vec<_> = LazyQuery::new(&products)
142        .where_(Product::active_r(), |&active| active)
143        .skip_lazy(3)
144        .take_lazy(3)
145        .collect();
146
147    println!("  Page 2 items:");
148    for (i, p) in page_2.iter().enumerate() {
149        println!("    {}. {}", i + 4, p.name);
150    }
151
152    // ============================================================================
153    // LAZY OPERATION 5: first - Short-Circuit Search
154    // ============================================================================
155    println!("\n═══════════════════════════════════════════════════════════════");
156    println!("Lazy Operation 5: first (short-circuit)");
157    println!("═══════════════════════════════════════════════════════════════\n");
158
159    println!("Finding first expensive item (>$1000)...");
160    let expensive = LazyQuery::new(&products)
161        .where_(Product::price_r(), |&price| price > 1000.0)
162        .first();
163
164    match expensive {
165        Some(p) => println!("  Found: {} - ${:.2}", p.name, p.price),
166        None => println!("  Not found"),
167    }
168    println!("  ✅ Stopped at first match!");
169
170    // ============================================================================
171    // LAZY OPERATION 6: any - Existence Check
172    // ============================================================================
173    println!("\n═══════════════════════════════════════════════════════════════");
174    println!("Lazy Operation 6: any (existence check)");
175    println!("═══════════════════════════════════════════════════════════════\n");
176
177    println!("Checking if any furniture exists...");
178    let has_furniture = LazyQuery::new(&products)
179        .where_(Product::category_r(), |cat| cat == "Furniture")
180        .any();
181
182    println!("  Has furniture: {}", has_furniture);
183    println!("  ✅ Stopped immediately after finding first match!");
184
185    // ============================================================================
186    // LAZY OPERATION 7: count - Count Matching Items
187    // ============================================================================
188    println!("\n═══════════════════════════════════════════════════════════════");
189    println!("Lazy Operation 7: count");
190    println!("═══════════════════════════════════════════════════════════════\n");
191
192    let electronics_count = LazyQuery::new(&products)
193        .where_(Product::category_r(), |cat| cat == "Electronics")
194        .count();
195
196    println!("  Electronics count: {}", electronics_count);
197
198    // ============================================================================
199    // LAZY OPERATION 8: sum_by - Aggregation
200    // ============================================================================
201    println!("\n═══════════════════════════════════════════════════════════════");
202    println!("Lazy Operation 8: sum_by (aggregation)");
203    println!("═══════════════════════════════════════════════════════════════\n");
204
205    let total_value: f64 = LazyQuery::new(&products)
206        .where_(Product::category_r(), |cat| cat == "Electronics")
207        .sum_by(Product::price_r());
208
209    println!("  Total electronics value: ${:.2}", total_value);
210
211    // ============================================================================
212    // LAZY OPERATION 9: avg_by - Average
213    // ============================================================================
214    println!("\n═══════════════════════════════════════════════════════════════");
215    println!("Lazy Operation 9: avg_by");
216    println!("═══════════════════════════════════════════════════════════════\n");
217
218    let avg_price = LazyQuery::new(&products)
219        .where_(Product::category_r(), |cat| cat == "Furniture")
220        .avg_by(Product::price_r())
221        .unwrap_or(0.0);
222
223    println!("  Average furniture price: ${:.2}", avg_price);
224
225    // ============================================================================
226    // LAZY OPERATION 10: min_by_float / max_by_float
227    // ============================================================================
228    println!("\n═══════════════════════════════════════════════════════════════");
229    println!("Lazy Operation 10: min_by_float / max_by_float");
230    println!("═══════════════════════════════════════════════════════════════\n");
231
232    let min_price = LazyQuery::new(&products)
233        .where_(Product::active_r(), |&active| active)
234        .min_by_float(Product::price_r())
235        .unwrap_or(0.0);
236
237    let max_price = LazyQuery::new(&products)
238        .where_(Product::active_r(), |&active| active)
239        .max_by_float(Product::price_r())
240        .unwrap_or(0.0);
241
242    println!("  Price range for active products:");
243    println!("    Min: ${:.2}", min_price);
244    println!("    Max: ${:.2}", max_price);
245
246    // ============================================================================
247    // LAZY OPERATION 11: find - Find with Predicate
248    // ============================================================================
249    println!("\n═══════════════════════════════════════════════════════════════");
250    println!("Lazy Operation 11: find (with predicate)");
251    println!("═══════════════════════════════════════════════════════════════\n");
252
253    let high_rated = LazyQuery::new(&products)
254        .where_(Product::category_r(), |cat| cat == "Electronics")
255        .find(|item| item.rating > 4.7);
256
257    if let Some(product) = high_rated {
258        println!("  First highly-rated electronic:");
259        println!("    {}: Rating {:.1}", product.name, product.rating);
260    }
261
262    // ============================================================================
263    // LAZY OPERATION 12: for_each - Iteration
264    // ============================================================================
265    println!("\n═══════════════════════════════════════════════════════════════");
266    println!("Lazy Operation 12: for_each (iteration)");
267    println!("═══════════════════════════════════════════════════════════════\n");
268
269    println!("  Low stock alerts:");
270    LazyQuery::new(&products)
271        .where_(Product::stock_r(), |&stock| stock < 20)
272        .for_each(|product| {
273            println!("    ⚠️  {}: Only {} in stock", product.name, product.stock);
274        });
275
276    // ============================================================================
277    // LAZY OPERATION 13: fold - Custom Aggregation
278    // ============================================================================
279    println!("\n═══════════════════════════════════════════════════════════════");
280    println!("Lazy Operation 14: fold (custom aggregation)");
281    println!("═══════════════════════════════════════════════════════════════\n");
282
283    let total_inventory_value = LazyQuery::new(&products)
284        .where_(Product::active_r(), |&active| active)
285        .fold(0.0, |acc, product| {
286            acc + (product.price * product.stock as f64)
287        });
288
289    println!("  Total inventory value: ${:.2}", total_inventory_value);
290
291    // ============================================================================
292    // LAZY OPERATION 14: all_match - Validation
293    // ============================================================================
294    println!("\n═══════════════════════════════════════════════════════════════");
295    println!("Lazy Operation 15: all_match (validation)");
296    println!("═══════════════════════════════════════════════════════════════\n");
297
298    let all_priced = LazyQuery::new(&products)
299        .all_match(|item| item.price > 0.0);
300
301    println!("  All products have valid prices: {}", all_priced);
302
303    // ============================================================================
304    // LAZY OPERATION 15: into_iter - For Loop
305    // ============================================================================
306    println!("\n═══════════════════════════════════════════════════════════════");
307    println!("Lazy Operation 16: into_iter (for loop)");
308    println!("═══════════════════════════════════════════════════════════════\n");
309
310    println!("  High-value products (>$300):");
311    for product in LazyQuery::new(&products)
312        .where_(Product::price_r(), |&p| p > 300.0)
313        .take_lazy(5)
314    {
315        println!("    • {}: ${:.2}", product.name, product.price);
316    }
317
318    // ============================================================================
319    // LAZY OPERATION 16: map_items - Transform
320    // ============================================================================
321    println!("\n═══════════════════════════════════════════════════════════════");
322    println!("Lazy Operation 17: map_items (transformation)");
323    println!("═══════════════════════════════════════════════════════════════\n");
324
325    let price_tags: Vec<String> = LazyQuery::new(&products)
326        .where_(Product::category_r(), |cat| cat == "Electronics")
327        .map_items(|p| format!("{}: ${:.2}", p.name, p.price))
328        .take(5)
329        .collect();
330
331    println!("  Electronics price tags:");
332    for tag in &price_tags {
333        println!("    • {}", tag);
334    }
335
336    // ============================================================================
337    // COMPLEX EXAMPLE: Multi-Stage Lazy Pipeline
338    // ============================================================================
339    println!("\n═══════════════════════════════════════════════════════════════");
340    println!("Complex Example: Multi-stage lazy pipeline");
341    println!("═══════════════════════════════════════════════════════════════\n");
342
343    println!("Building complex query:");
344    println!("  1. Filter by category (Electronics)");
345    println!("  2. Filter by price range ($50-$500)");
346    println!("  3. Filter by rating (>4.5)");
347    println!("  4. Select names");
348    println!("  5. Take first 3");
349    println!();
350
351    let results: Vec<String> = LazyQuery::new(&products)
352        .where_(Product::category_r(), |cat| cat == "Electronics")
353        .where_(Product::price_r(), |&p| p >= 50.0 && p <= 500.0)
354        .where_(Product::rating_r(), |&r| r > 4.5)
355        .select_lazy(Product::name_r())
356        .take(3)
357        .collect();
358
359    println!("  Results:");
360    for (i, name) in results.iter().enumerate() {
361        println!("    {}. {}", i + 1, name);
362    }
363    println!("  ✅ All operations fused and executed lazily!");
364
365    // ============================================================================
366    // THREAD-SAFE UPDATES WITH RWLOCK
367    // ============================================================================
368    println!("\n═══════════════════════════════════════════════════════════════");
369    println!("Bonus: Thread-safe updates with RwLock");
370    println!("═══════════════════════════════════════════════════════════════\n");
371
372    // Update a product through the Arc<RwLock>
373    if let Some(product_arc) = product_map.get("PROD-002") {
374        println!("Updating PROD-002 stock...");
375        
376        // Write lock for mutation
377        if let Ok(mut product) = product_arc.write() {
378            let old_stock = product.stock;
379            product.stock = 25;
380            println!("  Stock updated: {} → {}", old_stock, product.stock);
381        }
382    }
383
384    // Query again to see the update
385    let updated_products = extract_products(&product_map);
386    let mouse = LazyQuery::new(&updated_products)
387        .find(|p| p.id == 2);
388
389    if let Some(product) = mouse {
390        println!("  Verified update: {} now has {} in stock", product.name, product.stock);
391    }
392
393    // ============================================================================
394    // PRACTICAL EXAMPLE: Price Analysis by Category
395    // ============================================================================
396    println!("\n═══════════════════════════════════════════════════════════════");
397    println!("Practical Example: Price analysis by category");
398    println!("═══════════════════════════════════════════════════════════════\n");
399
400    let categories = vec!["Electronics", "Furniture"];
401
402    for category in categories {
403        println!("  {} Statistics:", category);
404        
405        // Filter products by category first
406        let cat_products: Vec<Product> = products.iter()
407            .filter(|p| p.category == category)
408            .cloned()
409            .collect();
410
411        let count = LazyQuery::new(&cat_products).count();
412        let total = LazyQuery::new(&cat_products).sum_by(Product::price_r());
413        let avg = LazyQuery::new(&cat_products).avg_by(Product::price_r()).unwrap_or(0.0);
414        let min = LazyQuery::new(&cat_products).min_by_float(Product::price_r()).unwrap_or(0.0);
415        let max = LazyQuery::new(&cat_products).max_by_float(Product::price_r()).unwrap_or(0.0);
416
417        println!("    Count: {}", count);
418        println!("    Total: ${:.2}", total);
419        println!("    Average: ${:.2}", avg);
420        println!("    Range: ${:.2} - ${:.2}\n", min, max);
421    }
422
423    // ============================================================================
424    // COMBINING WITH HASHMAP OPERATIONS
425    // ============================================================================
426    println!("═══════════════════════════════════════════════════════════════");
427    println!("HashMap Integration: Query by key patterns");
428    println!("═══════════════════════════════════════════════════════════════\n");
429
430    // Filter HashMap by key pattern
431    let electronics_keys: Vec<String> = product_map
432        .iter()
433        .filter(|(_key, value)| {
434            // Read the value to check category
435            if let Ok(guard) = value.read() {
436                guard.category == "Electronics"
437            } else {
438                false
439            }
440        })
441        .map(|(key, _value)| key.clone())
442        .collect();
443
444    println!("  Electronics product IDs:");
445    for key in electronics_keys.iter().take(5) {
446        println!("    • {}", key);
447    }
448
449    // ============================================================================
450    // PERFORMANCE DEMONSTRATION
451    // ============================================================================
452    println!("\n═══════════════════════════════════════════════════════════════");
453    println!("Performance: Lazy vs Eager comparison");
454    println!("═══════════════════════════════════════════════════════════════\n");
455
456    println!("Scenario: Find first product with rating > 4.7 from {} products\n", products.len());
457
458    println!("  Eager approach (hypothetical):");
459    println!("    - Filter all {} products", products.len());
460    println!("    - Collect filtered results");
461    println!("    - Take first item");
462    println!("    - Wasted work: Check all items\n");
463
464    println!("  Lazy approach (actual):");
465    let _first_rated = LazyQuery::new(&products)
466        .where_(Product::rating_r(), |&r| r > 4.7)
467        .first();
468    println!("    - Starts checking products");
469    println!("    - Stops at first match");
470    println!("    - ✅ Early termination - checks ~3-5 items only!");
471
472    // ============================================================================
473    // Summary
474    // ============================================================================
475    println!("\n╔══════════════════════════════════════════════════════════════════╗");
476    println!("║  Summary: All Lazy Operations Demonstrated                      ║");
477    println!("╚══════════════════════════════════════════════════════════════════╝\n");
478
479    println!("✅ Lazy Query Operations:");
480    println!("   1. ✅ where_ - Lazy filtering");
481    println!("   2. ✅ select_lazy - Lazy projection");
482    println!("   3. ✅ take_lazy - Early termination");
483    println!("   4. ✅ skip_lazy - Pagination");
484    println!("   5. ✅ first - Short-circuit search");
485    println!("   6. ✅ any - Existence check (short-circuit)");
486    println!("   7. ✅ count - Count items");
487    println!("   8. ✅ sum_by - Sum aggregation");
488    println!("   9. ✅ avg_by - Average aggregation");
489    println!("   10. ✅ min_by_float - Minimum value");
490    println!("   11. ✅ max_by_float - Maximum value");
491    println!("   12. ✅ find - Find with predicate (short-circuit)");
492    println!("   13. ✅ for_each - Iteration");
493    println!("   14. ✅ fold - Custom aggregation");
494    println!("   15. ✅ all_match - Validation (short-circuit)");
495    println!("   16. ✅ into_iter - For loop support");
496    println!("   17. ✅ map_items - Transformation\n");
497
498    println!("✅ Arc<RwLock<T>> Benefits:");
499    println!("   • Thread-safe shared access");
500    println!("   • Interior mutability");
501    println!("   • Multiple readers, single writer");
502    println!("   • Reference counting (Arc)");
503    println!("   • Can be queried after extracting data\n");
504
505    println!("✅ HashMap<K, Arc<RwLock<V>>> Benefits:");
506    println!("   • Fast key-based lookup");
507    println!("   • Thread-safe value access");
508    println!("   • Can query all values");
509    println!("   • Can filter by key patterns");
510    println!("   • Perfect for shared state/caches\n");
511
512    println!("🎯 Use Cases:");
513    println!("   • Shared product catalogs");
514    println!("   • User session stores");
515    println!("   • Configuration caches");
516    println!("   • Real-time inventory systems");
517    println!("   • Multi-threaded data processing");
518    println!("   • Web server state management\n");
519
520    println!("✓ Arc<RwLock<T>> HashMap with all lazy operations demo complete!\n");
521}
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/individual_crates.rs (line 103)
27fn main() {
28    println!("Individual Crates Example");
29    println!("=========================\n");
30    println!("Using rust-queries-core + rust-queries-derive directly\n");
31
32    let products = vec![
33        Product {
34            id: 1,
35            name: "Laptop".to_string(),
36            price: 999.99,
37            category: "Electronics".to_string(),
38            stock: 5,
39        },
40        Product {
41            id: 2,
42            name: "Mouse".to_string(),
43            price: 29.99,
44            category: "Electronics".to_string(),
45            stock: 50,
46        },
47        Product {
48            id: 3,
49            name: "Keyboard".to_string(),
50            price: 79.99,
51            category: "Electronics".to_string(),
52            stock: 30,
53        },
54        Product {
55            id: 4,
56            name: "Monitor".to_string(),
57            price: 299.99,
58            category: "Electronics".to_string(),
59            stock: 12,
60        },
61        Product {
62            id: 5,
63            name: "Desk Chair".to_string(),
64            price: 199.99,
65            category: "Furniture".to_string(),
66            stock: 8,
67        },
68    ];
69
70    println!("1. QueryExt from rust_queries_core");
71    println!("   products.query().where_(price > 100).all()");
72    
73    let query = products
74        .query()  // From QueryExt trait
75        .where_(Product::price_r(), |&p| p > 100.0);
76    let expensive = query.all();
77    
78    println!("   Found {} expensive products:", expensive.len());
79    for product in expensive {
80        println!("   - {} (${:.2})", product.name, product.price);
81    }
82    println!();
83
84    println!("2. QueryBuilder from rust_queries_derive");
85    println!("   Product::query(&products).where_(stock < 10).all()");
86    
87    let query2 = Product::query(&products)  // From QueryBuilder derive
88        .where_(Product::stock_r(), |&s| s < 10);
89    let low_stock = query2.all();
90    
91    println!("   Found {} low stock products:", low_stock.len());
92    for product in low_stock {
93        println!("   - {} (stock: {})", product.name, product.stock);
94    }
95    println!();
96
97    println!("3. LazyQuery from rust_queries_core");
98    println!("   products.lazy_query().where_(...).collect()");
99    
100    let electronics: Vec<_> = products
101        .lazy_query()  // From QueryExt trait
102        .where_(Product::category_r(), |cat| cat == "Electronics")
103        .collect();
104    
105    println!("   Found {} electronics:", electronics.len());
106    for product in electronics {
107        println!("   - {}", product.name);
108    }
109    println!();
110
111    println!("4. Aggregations with LazyQuery");
112    println!("   products.lazy_query().sum_by(Product::price_r())");
113    
114    let total_value: f64 = products
115        .lazy_query()
116        .sum_by(Product::price_r());
117    
118    println!("   Total inventory value: ${:.2}", total_value);
119    println!();
120
121    println!("5. Early termination with lazy queries");
122    println!("   products.lazy_query().where_(...).first()");
123    
124    if let Some(first_cheap) = products
125        .lazy_query()
126        .where_(Product::price_r(), |&p| p < 50.0)
127        .first()
128    {
129        println!("   First cheap product: {} (${:.2})", first_cheap.name, first_cheap.price);
130    }
131    println!();
132
133    println!("6. Using Query (eager) from rust_queries_core");
134    println!("   Query::new(&products).where_(...).count()");
135    
136    let query3 = Query::new(&products)  // Traditional approach
137        .where_(Product::price_r(), |&p| p > 50.0);
138    let count = query3.count();
139    
140    println!("   Products over $50: {}", count);
141    println!();
142
143    println!("Summary:");
144    println!("--------");
145    println!("✓ rust_queries_core provides: Query, LazyQuery, QueryExt");
146    println!("✓ rust_queries_derive provides: #[derive(QueryBuilder)]");
147    println!("✓ key_paths_derive provides: #[derive(Keypaths)]");
148    println!("✓ All features work with individual crates!");
149}
More examples
Hide additional examples
examples/derive_and_ext.rs (line 75)
13fn main() {
14    println!("Derive Macros and Extension Traits Example");
15    println!("===========================================\n");
16
17    let products = vec![
18        Product {
19            id: 1,
20            name: "Laptop".to_string(),
21            price: 999.99,
22            category: "Electronics".to_string(),
23            stock: 5,
24        },
25        Product {
26            id: 2,
27            name: "Mouse".to_string(),
28            price: 29.99,
29            category: "Electronics".to_string(),
30            stock: 50,
31        },
32        Product {
33            id: 3,
34            name: "Keyboard".to_string(),
35            price: 79.99,
36            category: "Electronics".to_string(),
37            stock: 30,
38        },
39        Product {
40            id: 4,
41            name: "Monitor".to_string(),
42            price: 299.99,
43            category: "Electronics".to_string(),
44            stock: 12,
45        },
46        Product {
47            id: 5,
48            name: "Desk Chair".to_string(),
49            price: 199.99,
50            category: "Furniture".to_string(),
51            stock: 8,
52        },
53    ];
54
55    println!("1. Using Extension Trait - Direct .query() on Vec");
56    println!("   Query: products.query().where_(price > 100).all()");
57    
58    let query = products
59        .query()
60        .where_(Product::price_r(), |&p| p > 100.0);
61    let expensive = query.all();
62    
63    println!("   Found {} expensive products:", expensive.len());
64    for product in &expensive {
65        println!("   - {} (${:.2})", product.name, product.price);
66    }
67    println!();
68
69    println!("2. Using Extension Trait - Direct .lazy_query() on Vec");
70    println!("   Query: products.lazy_query().where_(stock < 10).collect()");
71    
72    let low_stock: Vec<_> = products
73        .lazy_query()
74        .where_(Product::stock_r(), |&s| s < 10)
75        .collect();
76    
77    println!("   Found {} low stock products:", low_stock.len());
78    for product in &low_stock {
79        println!("   - {} (stock: {})", product.name, product.stock);
80    }
81    println!();
82
83    println!("3. Using Extension Trait - Chained Operations");
84    println!("   Query: products.lazy_query().where_(category == Electronics).take(2).select(name).collect()");
85    
86    let names: Vec<String> = products
87        .lazy_query()
88        .where_(Product::category_r(), |cat| cat == "Electronics")
89        .take_lazy(2)
90        .select_lazy(Product::name_r())
91        .collect();
92    
93    println!("   First 2 electronics:");
94    for name in &names {
95        println!("   - {}", name);
96    }
97    println!();
98
99    println!("4. Using QueryBuilder Derive - Static Methods");
100    println!("   Query: Product::query(&products).where_(price > 50).count()");
101    
102    let query4 = Product::query(&products)
103        .where_(Product::price_r(), |&p| p > 50.0);
104    let count = query4.count();
105    
106    println!("   Products over $50: {}", count);
107    println!();
108
109    println!("5. Using QueryBuilder Derive - Lazy Static Methods");
110    println!("   Query: Product::lazy_query(&products).first()");
111    
112    if let Some(first) = Product::lazy_query(&products).first() {
113        println!("   First product: {} (${:.2})", first.name, first.price);
114    }
115    println!();
116
117    println!("6. Complex Chain with Extension Trait");
118    println!("   Query: products.lazy_query()");
119    println!("          .where_(category == Electronics)");
120    println!("          .where_(price < 500)");
121    println!("          .map(|p| format!(\"{{}} - ${{:.2}}\", p.name, p.price))");
122    println!("          .collect()");
123    
124    let formatted: Vec<String> = products
125        .lazy_query()
126        .where_(Product::category_r(), |cat| cat == "Electronics")
127        .where_(Product::price_r(), |&p| p < 500.0)
128        .map_items(|p| format!("{} - ${:.2}", p.name, p.price))
129        .collect();
130    
131    println!("   Affordable electronics:");
132    for item in &formatted {
133        println!("   - {}", item);
134    }
135    println!();
136
137    println!("7. Aggregation with Extension Trait");
138    println!("   Query: products.lazy_query().sum_by(Product::stock())");
139    
140    let total_stock = products
141        .lazy_query()
142        .sum_by(Product::stock_r());
143    
144    println!("   Total stock across all products: {}", total_stock);
145    println!();
146
147    println!("8. Find with Extension Trait");
148    println!("   Query: products.lazy_query().find(|p| p.name.contains(\"Chair\"))");
149    
150    if let Some(chair) = products.lazy_query().find(|p| p.name.contains("Chair")) {
151        println!("   Found: {} in {}", chair.name, chair.category);
152    }
153    println!();
154
155    println!("9. Early Termination with Extension Trait");
156    println!("   Query: products.lazy_query().where_(price > 1000).any()");
157    
158    let has_luxury = products
159        .lazy_query()
160        .where_(Product::price_r(), |&p| p > 1000.0)
161        .any();
162    
163    println!("   Has products over $1000: {}", has_luxury);
164    println!();
165
166    println!("10. Slice Extension Trait");
167    println!("    Query: (&products[..]).lazy_query().count()");
168    
169    let slice_count = (&products[..])
170        .lazy_query()
171        .count();
172    
173    println!("    Count from slice: {}", slice_count);
174    println!();
175
176    println!("Summary:");
177    println!("--------");
178    println!("✓ Extension trait QueryExt adds .query() and .lazy_query() to containers");
179    println!("✓ Derive macro QueryBuilder adds static methods Product::query() and Product::lazy_query()");
180    println!("✓ Both approaches provide the same query functionality");
181    println!("✓ Extension trait is more ergonomic: products.query() vs Query::new(&products)");
182    println!("✓ All iterator optimizations (fusion, early termination) still apply");
183}
examples/container_support.rs (line 103)
26fn main() {
27    println!("\n╔════════════════════════════════════════════════════════════════╗");
28    println!("║  Container Support Demo                                       ║");
29    println!("║  Query various collection types                               ║");
30    println!("╚════════════════════════════════════════════════════════════════╝\n");
31
32    // ============================================================================
33    // CONTAINER 1: Vec<T>
34    // ============================================================================
35    println!("═══════════════════════════════════════════════════════════════");
36    println!("Container 1: Vec<T>");
37    println!("═══════════════════════════════════════════════════════════════\n");
38
39    let vec_products = vec![
40        create_sample_product(1, "Laptop", 999, "Electronics"),
41        create_sample_product(2, "Mouse", 29, "Electronics"),
42        create_sample_product(3, "Desk", 299, "Furniture"),
43    ];
44
45    // Query Vec directly
46    let vec_query = Query::new(&vec_products)
47        .where_(Product::category_r(), |cat| cat == "Electronics");
48    let vec_results = vec_query.all();
49    println!("  Vec: Found {} electronics", vec_results.len());
50
51    // Lazy query on Vec
52    let lazy_count = LazyQuery::new(&vec_products)
53        .where_(Product::price_r(), |&p| p < 100)
54        .count();
55    println!("  Vec (lazy): {} items under $100", lazy_count);
56
57    // ============================================================================
58    // CONTAINER 2: VecDeque<T>
59    // ============================================================================
60    println!("\n═══════════════════════════════════════════════════════════════");
61    println!("Container 2: VecDeque<T>");
62    println!("═══════════════════════════════════════════════════════════════\n");
63
64    let mut deque_products = VecDeque::new();
65    deque_products.push_back(create_sample_product(1, "Keyboard", 129, "Electronics"));
66    deque_products.push_back(create_sample_product(2, "Monitor", 349, "Electronics"));
67    deque_products.push_back(create_sample_product(3, "Chair", 199, "Furniture"));
68
69    // Convert to owned Vec for querying
70    let deque_vec: Vec<Product> = deque_products.iter().cloned().collect();
71    let deque_query = Query::new(&deque_vec);
72    let deque_count = deque_query.count();
73    println!("  VecDeque: {} total items", deque_count);
74
75    // More efficient: use make_contiguous for zero-copy slice access
76    let contiguous = deque_products.make_contiguous();
77    let contiguous_query = Query::new(contiguous);
78    println!("  VecDeque (zero-copy): {} items", contiguous_query.count());
79
80    // ============================================================================
81    // CONTAINER 3: HashSet<T>
82    // ============================================================================
83    println!("\n═══════════════════════════════════════════════════════════════");
84    println!("Container 3: HashSet<T>");
85    println!("═══════════════════════════════════════════════════════════════\n");
86
87    let mut set_products = HashSet::new();
88    set_products.insert(create_sample_product(1, "Tablet", 499, "Electronics"));
89    set_products.insert(create_sample_product(2, "Phone", 799, "Electronics"));
90    set_products.insert(create_sample_product(3, "Lamp", 39, "Furniture"));
91
92    // Collect from HashSet to Vec for querying
93    let set_vec: Vec<Product> = set_products.iter().cloned().collect();
94    let set_query = Query::new(&set_vec)
95        .where_(Product::price_r(), |&p| p > 500);
96    let expensive = set_query.all();
97    println!("  HashSet: {} expensive items", expensive.len());
98
99    // Lazy on HashSet (convert to owned Vec first)
100    let set_owned: Vec<Product> = set_products.iter().cloned().collect();
101    let lazy_set: Vec<_> = LazyQuery::new(&set_owned)
102        .where_(Product::category_r(), |cat| cat == "Electronics")
103        .collect();
104    println!("  HashSet (lazy): {} electronics", lazy_set.len());
105
106    // ============================================================================
107    // CONTAINER 4: BTreeSet<T>
108    // ============================================================================
109    println!("\n═══════════════════════════════════════════════════════════════");
110    println!("Container 4: BTreeSet<T>");
111    println!("═══════════════════════════════════════════════════════════════\n");
112
113    let mut btree_set = BTreeSet::new();
114    btree_set.insert(create_sample_product(1, "Webcam", 79, "Electronics"));
115    btree_set.insert(create_sample_product(2, "Microphone", 129, "Electronics"));
116    btree_set.insert(create_sample_product(3, "Bookshelf", 149, "Furniture"));
117
118    let btree_vec: Vec<Product> = btree_set.iter().cloned().collect();
119    let btree_query = Query::new(&btree_vec);
120    println!("  BTreeSet: {} total items (sorted order!)", btree_query.count());
121    
122    // BTreeSet items are in sorted order
123    for (i, item) in btree_vec.iter().take(3).enumerate() {
124        println!("    {}. {} (ID: {})", i + 1, item.name, item.id);
125    }
126
127    // ============================================================================
128    // CONTAINER 5: HashMap<K, V> - Query Values
129    // ============================================================================
130    println!("\n═══════════════════════════════════════════════════════════════");
131    println!("Container 5: HashMap<K, V> - Querying values");
132    println!("═══════════════════════════════════════════════════════════════\n");
133
134    let mut map_products = HashMap::new();
135    map_products.insert("prod1", create_sample_product(1, "Speaker", 199, "Electronics"));
136    map_products.insert("prod2", create_sample_product(2, "Headphones", 149, "Electronics"));
137    map_products.insert("prod3", create_sample_product(3, "Ottoman", 249, "Furniture"));
138
139    // Query HashMap values (convert to owned Vec)
140    let map_vec: Vec<Product> = map_products.values().cloned().collect();
141    let map_query = Query::new(&map_vec)
142        .where_(Product::category_r(), |cat| cat == "Electronics");
143    let electronics = map_query.all();
144    println!("  HashMap: {} electronics", electronics.len());
145
146    // ============================================================================
147    // CONTAINER 6: BTreeMap<K, V> - Query Values
148    // ============================================================================
149    println!("\n═══════════════════════════════════════════════════════════════");
150    println!("Container 6: BTreeMap<K, V> - Querying values");
151    println!("═══════════════════════════════════════════════════════════════\n");
152
153    let mut btree_map = BTreeMap::new();
154    btree_map.insert(1, create_sample_product(1, "Router", 89, "Electronics"));
155    btree_map.insert(2, create_sample_product(2, "Switch", 129, "Electronics"));
156    btree_map.insert(3, create_sample_product(3, "Sofa", 899, "Furniture"));
157
158    let btree_map_vec: Vec<Product> = btree_map.values().cloned().collect();
159    let btree_map_query = Query::new(&btree_map_vec);
160    let avg_price = btree_map_query.sum(Product::price_r()) as f64 / btree_map.len() as f64;
161    println!("  BTreeMap: Average price ${:.2}", avg_price);
162
163    // ============================================================================
164    // CONTAINER 7: Arrays [T; N]
165    // ============================================================================
166    println!("\n═══════════════════════════════════════════════════════════════");
167    println!("Container 7: Arrays [T; N]");
168    println!("═══════════════════════════════════════════════════════════════\n");
169
170    let array_products = [
171        create_sample_product(1, "USB Cable", 15, "Electronics"),
172        create_sample_product(2, "HDMI Cable", 25, "Electronics"),
173        create_sample_product(3, "Power Strip", 35, "Electronics"),
174    ];
175
176    // Query array directly (as slice)
177    let array_query = Query::new(&array_products);
178    let total = array_query.sum(Product::price_r());
179    println!("  Array: Total value ${}", total);
180
181    // Lazy on array
182    let lazy_array: Vec<_> = LazyQuery::new(&array_products)
183        .where_(Product::price_r(), |&p| p > 20)
184        .collect();
185    println!("  Array (lazy): {} items over $20", lazy_array.len());
186
187    // ============================================================================
188    // CONTAINER 8: LinkedList<T>
189    // ============================================================================
190    println!("\n═══════════════════════════════════════════════════════════════");
191    println!("Container 8: LinkedList<T>");
192    println!("═══════════════════════════════════════════════════════════════\n");
193
194    let mut list_products = LinkedList::new();
195    list_products.push_back(create_sample_product(1, "SSD", 159, "Electronics"));
196    list_products.push_back(create_sample_product(2, "HDD", 79, "Electronics"));
197
198    let list_vec: Vec<Product> = list_products.iter().cloned().collect();
199    let list_query = Query::new(&list_vec);
200    println!("  LinkedList: {} items", list_query.count());
201
202    // ============================================================================
203    // CONTAINER 9: Option<T> and Result<T, E>
204    // ============================================================================
205    println!("\n═══════════════════════════════════════════════════════════════");
206    println!("Container 9: Option<T> and Result<T, E>");
207    println!("═══════════════════════════════════════════════════════════════\n");
208
209    let maybe_product = Some(create_sample_product(1, "Mystery Box", 99, "Special"));
210    
211    if let Some(ref product) = maybe_product {
212        let option_query = Query::new(std::slice::from_ref(product));
213        println!("  Option (Some): {} items", option_query.count());
214    }
215
216    let none_product: Option<Product> = None;
217    let none_count = none_product.iter().count();
218    println!("  Option (None): {} items", none_count);
219
220    // ============================================================================
221    // Summary
222    // ============================================================================
223    println!("\n╔════════════════════════════════════════════════════════════════╗");
224    println!("║  Supported Containers Summary                                  ║");
225    println!("╚════════════════════════════════════════════════════════════════╝\n");
226
227    println!("✅ Supported container types:");
228    println!("   • Vec<T>              - Standard vector");
229    println!("   • &[T]                - Slices");
230    println!("   • [T; N]              - Fixed-size arrays");
231    println!("   • VecDeque<T>         - Double-ended queue");
232    println!("   • LinkedList<T>       - Doubly-linked list");
233    println!("   • HashSet<T>          - Unordered set");
234    println!("   • BTreeSet<T>         - Ordered set");
235    println!("   • HashMap<K, V>       - Query values");
236    println!("   • BTreeMap<K, V>      - Query values (sorted)");
237    println!("   • Option<T>           - 0 or 1 item");
238    println!("   • Result<T, E>        - 0 or 1 item\n");
239
240    println!("📝 Usage patterns:");
241    println!("   • Direct: Query::new(&container) for Vec, slices, arrays");
242    println!("   • Convert: Collect to Vec for Sets and Maps");
243    println!("   • Lazy: LazyQuery::new(&slice) for any slice\n");
244
245    println!("💡 Tips:");
246    println!("   • Vec/slice: Direct support, most efficient");
247    println!("   • Sets: Iterate to Vec, then query");
248    println!("   • Maps: Use .values().collect() to query values");
249    println!("   • VecDeque: Use .as_slices() for zero-copy");
250    println!("   • For custom types: Implement Queryable trait\n");
251
252    println!("✓ Container support demo complete!\n");
253}
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}
examples/macro_helpers.rs (line 330)
36fn main() {
37    println!("\n╔════════════════════════════════════════════════════════════════╗");
38    println!("║  Macro Helpers Demo - Reducing Boilerplate                    ║");
39    println!("╚════════════════════════════════════════════════════════════════╝\n");
40
41    let products = create_products();
42
43    // ============================================================================
44    // EXAMPLE 1: Simple Collection
45    // ============================================================================
46    println!("═══════════════════════════════════════════════════════════════");
47    println!("Example 1: collect_lazy! - Simple collection");
48    println!("═══════════════════════════════════════════════════════════════\n");
49
50    println!("❌ Without macro (verbose):");
51    println!("```rust");
52    println!("let results: Vec<_> = LazyQuery::new(&products).collect();");
53    println!("```\n");
54
55    println!("✅ With macro (concise):");
56    println!("```rust");
57    println!("let results = collect_lazy!(&products);");
58    println!("```\n");
59
60    let results = collect_lazy!(&products);
61    println!("Result: {} products collected\n", results.len());
62
63    // ============================================================================
64    // EXAMPLE 2: Filter and Collect
65    // ============================================================================
66    println!("═══════════════════════════════════════════════════════════════");
67    println!("Example 2: filter_collect! - Filter and collect");
68    println!("═══════════════════════════════════════════════════════════════\n");
69
70    println!("❌ Without macro (verbose):");
71    println!("```rust");
72    println!("let electronics: Vec<_> = LazyQuery::new(&products)");
73    println!("    .where_(Product::category_r(), |cat| cat == \"Electronics\")");
74    println!("    .collect();");
75    println!("```\n");
76
77    println!("✅ With macro (concise):");
78    println!("```rust");
79    println!("let electronics = filter_collect!(");
80    println!("    &products,");
81    println!("    Product::category_r(),");
82    println!("    |cat| cat == \"Electronics\"");
83    println!(");");
84    println!("```\n");
85
86    let electronics = filter_collect!(
87        &products,
88        Product::category_r(),
89        |cat| cat == "Electronics"
90    );
91    println!("Result: {} electronics\n", electronics.len());
92
93    // ============================================================================
94    // EXAMPLE 3: Count with Filter
95    // ============================================================================
96    println!("═══════════════════════════════════════════════════════════════");
97    println!("Example 3: count_where! - Count with filter");
98    println!("═══════════════════════════════════════════════════════════════\n");
99
100    println!("❌ Without macro (verbose):");
101    println!("```rust");
102    println!("let count = LazyQuery::new(&products)");
103    println!("    .where_(Product::stock_r(), |&s| s > 0)");
104    println!("    .count();");
105    println!("```\n");
106
107    println!("✅ With macro (concise):");
108    println!("```rust");
109    println!("let count = count_where!(&products, Product::stock_r(), |&s| s > 0);");
110    println!("```\n");
111
112    let count = count_where!(&products, Product::stock_r(), |&s| s > 0);
113    println!("Result: {} products in stock\n", count);
114
115    // ============================================================================
116    // EXAMPLE 4: Find First
117    // ============================================================================
118    println!("═══════════════════════════════════════════════════════════════");
119    println!("Example 4: find_first! - Find first matching item");
120    println!("═══════════════════════════════════════════════════════════════\n");
121
122    println!("❌ Without macro (verbose):");
123    println!("```rust");
124    println!("let found = LazyQuery::new(&products)");
125    println!("    .where_(Product::price_r(), |&p| p > 500.0)");
126    println!("    .first();");
127    println!("```\n");
128
129    println!("✅ With macro (concise):");
130    println!("```rust");
131    println!("let found = find_first!(&products, Product::price_r(), |&p| p > 500.0);");
132    println!("```\n");
133
134    let found = find_first!(&products, Product::price_r(), |&p| p > 500.0);
135    if let Some(p) = found {
136        println!("Result: Found {} at ${:.2}\n", p.name, p.price);
137    }
138
139    // ============================================================================
140    // EXAMPLE 5: Existence Check
141    // ============================================================================
142    println!("═══════════════════════════════════════════════════════════════");
143    println!("Example 5: exists_where! - Check if any item matches");
144    println!("═══════════════════════════════════════════════════════════════\n");
145
146    println!("❌ Without macro (verbose):");
147    println!("```rust");
148    println!("let has_furniture = LazyQuery::new(&products)");
149    println!("    .where_(Product::category_r(), |cat| cat == \"Furniture\")");
150    println!("    .any();");
151    println!("```\n");
152
153    println!("✅ With macro (concise):");
154    println!("```rust");
155    println!("let has_furniture = exists_where!(");
156    println!("    &products,");
157    println!("    Product::category_r(),");
158    println!("    |cat| cat == \"Furniture\"");
159    println!(");");
160    println!("```\n");
161
162    let has_furniture = exists_where!(
163        &products,
164        Product::category_r(),
165        |cat| cat == "Furniture"
166    );
167    println!("Result: Has furniture = {}\n", has_furniture);
168
169    // ============================================================================
170    // EXAMPLE 6: Pagination
171    // ============================================================================
172    println!("═══════════════════════════════════════════════════════════════");
173    println!("Example 6: paginate! - Quick pagination");
174    println!("═══════════════════════════════════════════════════════════════\n");
175
176    println!("❌ Without macro (verbose):");
177    println!("```rust");
178    println!("let page_2: Vec<_> = LazyQuery::new(&products)");
179    println!("    .skip_lazy(1 * 2)  // page * size");
180    println!("    .take_lazy(2)");
181    println!("    .collect();");
182    println!("```\n");
183
184    println!("✅ With macro (concise):");
185    println!("```rust");
186    println!("let page_2 = paginate!(&products, page: 1, size: 2);");
187    println!("```\n");
188
189    let page_2 = paginate!(&products, page: 1, size: 2);
190    println!("Result: Page 2 has {} items\n", page_2.len());
191
192    // ============================================================================
193    // EXAMPLE 7: Sum with Filter
194    // ============================================================================
195    println!("═══════════════════════════════════════════════════════════════");
196    println!("Example 7: sum_where! - Sum with filter");
197    println!("═══════════════════════════════════════════════════════════════\n");
198
199    println!("❌ Without macro (verbose):");
200    println!("```rust");
201    println!("let total: f64 = LazyQuery::new(&products)");
202    println!("    .where_(Product::active_r(), |&a| a)");
203    println!("    .sum_by(Product::price_r());");
204    println!("```\n");
205
206    println!("✅ With macro (concise):");
207    println!("```rust");
208    println!("let total = sum_where!(&products, Product::price_r(), Product::active_r(), |&a| a);");
209    println!("```\n");
210
211    let total = sum_where!(&products, Product::price_r(), Product::active_r(), |&a| a);
212    println!("Result: Total active products value = ${:.2}\n", total);
213
214    // ============================================================================
215    // EXAMPLE 8: Average with Filter
216    // ============================================================================
217    println!("═══════════════════════════════════════════════════════════════");
218    println!("Example 8: avg_where! - Average with filter");
219    println!("═══════════════════════════════════════════════════════════════\n");
220
221    println!("❌ Without macro (verbose):");
222    println!("```rust");
223    println!("let avg = LazyQuery::new(&products)");
224    println!("    .where_(Product::category_r(), |cat| cat == \"Electronics\")");
225    println!("    .avg_by(Product::price_r())");
226    println!("    .unwrap_or(0.0);");
227    println!("```\n");
228
229    println!("✅ With macro (concise):");
230    println!("```rust");
231    println!("let avg = avg_where!(");
232    println!("    &products,");
233    println!("    Product::price_r(),");
234    println!("    Product::category_r(),");
235    println!("    |cat| cat == \"Electronics\"");
236    println!(").unwrap_or(0.0);");
237    println!("```\n");
238
239    let avg = avg_where!(
240        &products,
241        Product::price_r(),
242        Product::category_r(),
243        |cat| cat == "Electronics"
244    ).unwrap_or(0.0);
245    println!("Result: Average electronics price = ${:.2}\n", avg);
246
247    // ============================================================================
248    // EXAMPLE 9: Select All
249    // ============================================================================
250    println!("═══════════════════════════════════════════════════════════════");
251    println!("Example 9: select_all! - Select field from all items");
252    println!("═══════════════════════════════════════════════════════════════\n");
253
254    println!("❌ Without macro (verbose):");
255    println!("```rust");
256    println!("let names: Vec<String> = LazyQuery::new(&products)");
257    println!("    .select_lazy(Product::name_r())");
258    println!("    .collect();");
259    println!("```\n");
260
261    println!("✅ With macro (concise):");
262    println!("```rust");
263    println!("let names = select_all!(&products, Product::name_r());");
264    println!("```\n");
265
266    let names: Vec<String> = select_all!(&products, Product::name_r());
267    println!("Result: {} product names\n", names.len());
268
269    // ============================================================================
270    // EXAMPLE 10: Select with Filter
271    // ============================================================================
272    println!("═══════════════════════════════════════════════════════════════");
273    println!("Example 10: select_where! - Select field with filter");
274    println!("═══════════════════════════════════════════════════════════════\n");
275
276    println!("❌ Without macro (verbose):");
277    println!("```rust");
278    println!("let furniture_names: Vec<String> = LazyQuery::new(&products)");
279    println!("    .where_(Product::category_r(), |cat| cat == \"Furniture\")");
280    println!("    .select_lazy(Product::name_r())");
281    println!("    .collect();");
282    println!("```\n");
283
284    println!("✅ With macro (concise):");
285    println!("```rust");
286    println!("let furniture_names = select_where!(");
287    println!("    &products,");
288    println!("    Product::name_r(),");
289    println!("    Product::category_r(),");
290    println!("    |cat| cat == \"Furniture\"");
291    println!(");");
292    println!("```\n");
293
294    let furniture_names: Vec<String> = select_where!(
295        &products,
296        Product::name_r(),
297        Product::category_r(),
298        |cat| cat == "Furniture"
299    );
300    println!("Result: {} furniture items\n", furniture_names.len());
301
302    // ============================================================================
303    // COMPARISON: Complex Query
304    // ============================================================================
305    println!("═══════════════════════════════════════════════════════════════");
306    println!("Complex Example: Before & After");
307    println!("═══════════════════════════════════════════════════════════════\n");
308
309    println!("Scenario: Filter electronics, under $500, in stock, get first 5\n");
310
311    println!("❌ WITHOUT MACROS (13 lines):");
312    println!("```rust");
313    println!("let results: Vec<_> = LazyQuery::new(&products)");
314    println!("    .where_(");
315    println!("        Product::category_r(),");
316    println!("        |cat| cat == \"Electronics\"");
317    println!("    )");
318    println!("    .where_(Product::price_r(), |&p| p < 500.0)");
319    println!("    .where_(Product::stock_r(), |&s| s > 0)");
320    println!("    .take_lazy(5)");
321    println!("    .collect();");
322    println!("```\n");
323
324    // Actual verbose version
325    let verbose_results: Vec<_> = LazyQuery::new(&products)
326        .where_(Product::category_r(), |cat| cat == "Electronics")
327        .where_(Product::price_r(), |&p| p < 500.0)
328        .where_(Product::stock_r(), |&s| s > 0)
329        .take_lazy(5)
330        .collect();
331
332    println!("✅ WITH MACROS (Shorter, but still need multiple filters):");
333    println!("```rust");
334    println!("let results = lazy_query!(&products)");
335    println!("    .where_(Product::category_r(), |cat| cat == \"Electronics\")");
336    println!("    .where_(Product::price_r(), |&p| p < 500.0)");
337    println!("    .where_(Product::stock_r(), |&s| s > 0)");
338    println!("    .take_lazy(5)");
339    println!("    .collect();");
340    println!("```\n");
341
342    let macro_results = lazy_query!(&products)
343        .where_(Product::category_r(), |cat| cat == "Electronics")
344        .where_(Product::price_r(), |&p| p < 500.0)
345        .where_(Product::stock_r(), |&s| s > 0)
346        .take_lazy(5)
347        .collect();
348
349    println!("Both approaches found {} items ✅\n", verbose_results.len());
350    assert_eq!(verbose_results.len(), macro_results.len());
351
352    // ============================================================================
353    // CODE REDUCTION METRICS
354    // ============================================================================
355    println!("═══════════════════════════════════════════════════════════════");
356    println!("Code Reduction Metrics");
357    println!("═══════════════════════════════════════════════════════════════\n");
358
359    println!("Pattern Comparisons:\n");
360
361    println!("  1. Simple collect:");
362    println!("     Before: LazyQuery::new(&data).collect()");
363    println!("     After:  collect_lazy!(&data)");
364    println!("     Saved:  ~20 characters\n");
365
366    println!("  2. Filter + collect:");
367    println!("     Before: LazyQuery::new(&data).where_(...).collect()");
368    println!("     After:  filter_collect!(&data, field, pred)");
369    println!("     Saved:  ~35 characters\n");
370
371    println!("  3. Count with filter:");
372    println!("     Before: LazyQuery::new(&data).where_(...).count()");
373    println!("     After:  count_where!(&data, field, pred)");
374    println!("     Saved:  ~30 characters\n");
375
376    println!("  4. Pagination:");
377    println!("     Before: LazyQuery::new(&data).skip_lazy(p*s).take_lazy(s).collect()");
378    println!("     After:  paginate!(&data, page: p, size: s)");
379    println!("     Saved:  ~45 characters\n");
380
381    println!("  5. Sum with filter:");
382    println!("     Before: LazyQuery::new(&data).where_(...).sum_by(...)");
383    println!("     After:  sum_where!(&data, sum_field, filter_field, pred)");
384    println!("     Saved:  ~25 characters\n");
385
386    // ============================================================================
387    // ALL MACRO DEMONSTRATIONS
388    // ============================================================================
389    println!("═══════════════════════════════════════════════════════════════");
390    println!("All Available Macros - Quick Reference");
391    println!("═══════════════════════════════════════════════════════════════\n");
392
393    println!("1. lazy_query!(&data)");
394    let _q1 = lazy_query!(&products);
395    println!("   → LazyQuery::new(&data)\n");
396
397    println!("2. query!(&data)");
398    let _q2 = query!(&products);
399    println!("   → Query::new(&data)\n");
400
401    println!("3. collect_lazy!(&data)");
402    let _r3 = collect_lazy!(&products);
403    println!("   → LazyQuery::new(&data).collect()\n");
404
405    println!("4. filter_collect!(&data, field, pred)");
406    let _r4 = filter_collect!(&products, Product::active_r(), |&a| a);
407    println!("   → LazyQuery::new(&data).where_(field, pred).collect()\n");
408
409    println!("5. count_where!(&data, field, pred)");
410    let _r5 = count_where!(&products, Product::active_r(), |&a| a);
411    println!("   → LazyQuery::new(&data).where_(field, pred).count()\n");
412
413    println!("6. find_first!(&data, field, pred)");
414    let _r6 = find_first!(&products, Product::id_r(), |&id| id == 1);
415    println!("   → LazyQuery::new(&data).where_(field, pred).first()\n");
416
417    println!("7. exists_where!(&data, field, pred)");
418    let _r7 = exists_where!(&products, Product::active_r(), |&a| a);
419    println!("   → LazyQuery::new(&data).where_(field, pred).any()\n");
420
421    println!("8. paginate!(&data, page: p, size: s)");
422    let _r8 = paginate!(&products, page: 0, size: 3);
423    println!("   → LazyQuery::new(&data).skip_lazy(p*s).take_lazy(s).collect()\n");
424
425    println!("9. sum_where!(&data, sum_field, filter_field, pred)");
426    let _r9 = sum_where!(&products, Product::price_r(), Product::active_r(), |&a| a);
427    println!("   → LazyQuery::new(&data).where_(filter_field, pred).sum_by(sum_field)\n");
428
429    println!("10. avg_where!(&data, avg_field, filter_field, pred)");
430    let _r10 = avg_where!(&products, Product::price_r(), Product::active_r(), |&a| a);
431    println!("    → LazyQuery::new(&data).where_(filter_field, pred).avg_by(avg_field)\n");
432
433    println!("11. select_all!(&data, field)");
434    let _r11: Vec<String> = select_all!(&products, Product::name_r());
435    println!("    → LazyQuery::new(&data).select_lazy(field).collect()\n");
436
437    println!("12. select_where!(&data, select_field, filter_field, pred)");
438    let _r12: Vec<String> = select_where!(&products, Product::name_r(), Product::active_r(), |&a| a);
439    println!("    → LazyQuery::new(&data).where_(filter, pred).select_lazy(field).collect()\n");
440
441    // ============================================================================
442    // Summary
443    // ============================================================================
444    println!("╔════════════════════════════════════════════════════════════════╗");
445    println!("║  Summary                                                       ║");
446    println!("╚════════════════════════════════════════════════════════════════╝\n");
447
448    println!("✅ 12 helper macros provided:");
449    println!("   • lazy_query! - Create LazyQuery");
450    println!("   • query! - Create Query");
451    println!("   • collect_lazy! - Quick collect");
452    println!("   • filter_collect! - Filter and collect");
453    println!("   • count_where! - Count with filter");
454    println!("   • find_first! - Find first match");
455    println!("   • exists_where! - Existence check");
456    println!("   • paginate! - Easy pagination");
457    println!("   • sum_where! - Sum with filter");
458    println!("   • avg_where! - Average with filter");
459    println!("   • select_all! - Select all");
460    println!("   • select_where! - Select with filter\n");
461
462    println!("📊 Benefits:");
463    println!("   • Less typing (20-45 characters saved per operation)");
464    println!("   • More readable code");
465    println!("   • Common patterns encapsulated");
466    println!("   • Same performance (zero-cost abstraction)");
467    println!("   • Type-safe (compile-time checked)\n");
468
469    println!("💡 When to use:");
470    println!("   • Use macros for simple, common patterns");
471    println!("   • Use full API for complex queries");
472    println!("   • Mix and match as needed\n");
473
474    println!("✓ Macro helpers demo complete!\n");
475}
examples/arc_rwlock_hashmap.rs (line 90)
59fn main() {
60    println!("\n╔══════════════════════════════════════════════════════════════════╗");
61    println!("║  Arc<RwLock<T>> HashMap Lazy Query Demo                         ║");
62    println!("║  Thread-safe shared data with lazy evaluation                   ║");
63    println!("╚══════════════════════════════════════════════════════════════════╝\n");
64
65    let product_map = create_sample_data();
66    println!("Created product catalog:");
67    println!("  Total products: {}", product_map.len());
68    println!("  Keys: {:?}\n", product_map.keys().take(3).collect::<Vec<_>>());
69
70    // Extract products for querying
71    let products = extract_products(&product_map);
72    println!("Extracted {} products from Arc<RwLock<Product>>\n", products.len());
73
74    // ============================================================================
75    // LAZY OPERATION 1: where_ - Lazy Filtering
76    // ============================================================================
77    println!("═══════════════════════════════════════════════════════════════");
78    println!("Lazy Operation 1: where_ (filtering)");
79    println!("═══════════════════════════════════════════════════════════════\n");
80
81    println!("Building filtered query (nothing executes yet)...");
82    let electronics_query = LazyQuery::new(&products)
83        .where_(Product::category_r(), |cat| cat == "Electronics")
84        .where_(Product::active_r(), |&active| active)
85        .where_(Product::stock_r(), |&stock| stock > 20);
86
87    println!("  ✅ Query built (deferred execution)\n");
88
89    println!("Collecting results (executes now)...");
90    let electronics: Vec<_> = electronics_query.collect();
91    println!("  Found {} electronics in stock", electronics.len());
92    for p in &electronics {
93        println!("    • {}: {} in stock", p.name, p.stock);
94    }
95
96    // ============================================================================
97    // LAZY OPERATION 2: select_lazy - Lazy Projection
98    // ============================================================================
99    println!("\n═══════════════════════════════════════════════════════════════");
100    println!("Lazy Operation 2: select_lazy (projection)");
101    println!("═══════════════════════════════════════════════════════════════\n");
102
103    println!("Selecting product names (lazy)...");
104    let names: Vec<String> = LazyQuery::new(&products)
105        .where_(Product::category_r(), |cat| cat == "Furniture")
106        .select_lazy(Product::name_r())
107        .collect();
108
109    println!("  Furniture names ({}):", names.len());
110    for name in &names {
111        println!("    • {}", name);
112    }
113
114    // ============================================================================
115    // LAZY OPERATION 3: take_lazy - Early Termination
116    // ============================================================================
117    println!("\n═══════════════════════════════════════════════════════════════");
118    println!("Lazy Operation 3: take_lazy (early termination)");
119    println!("═══════════════════════════════════════════════════════════════\n");
120
121    println!("Getting first 3 electronics...");
122    let first_3: Vec<_> = LazyQuery::new(&products)
123        .where_(Product::category_r(), |cat| cat == "Electronics")
124        .take_lazy(3)
125        .collect();
126
127    println!("  First 3 electronics:");
128    for (i, p) in first_3.iter().enumerate() {
129        println!("    {}. {} - ${:.2}", i + 1, p.name, p.price);
130    }
131    println!("  ✅ Stopped after finding 3 items!");
132
133    // ============================================================================
134    // LAZY OPERATION 4: skip_lazy - Pagination
135    // ============================================================================
136    println!("\n═══════════════════════════════════════════════════════════════");
137    println!("Lazy Operation 4: skip_lazy (pagination)");
138    println!("═══════════════════════════════════════════════════════════════\n");
139
140    println!("Getting page 2 (skip 3, take 3)...");
141    let page_2: Vec<_> = LazyQuery::new(&products)
142        .where_(Product::active_r(), |&active| active)
143        .skip_lazy(3)
144        .take_lazy(3)
145        .collect();
146
147    println!("  Page 2 items:");
148    for (i, p) in page_2.iter().enumerate() {
149        println!("    {}. {}", i + 4, p.name);
150    }
151
152    // ============================================================================
153    // LAZY OPERATION 5: first - Short-Circuit Search
154    // ============================================================================
155    println!("\n═══════════════════════════════════════════════════════════════");
156    println!("Lazy Operation 5: first (short-circuit)");
157    println!("═══════════════════════════════════════════════════════════════\n");
158
159    println!("Finding first expensive item (>$1000)...");
160    let expensive = LazyQuery::new(&products)
161        .where_(Product::price_r(), |&price| price > 1000.0)
162        .first();
163
164    match expensive {
165        Some(p) => println!("  Found: {} - ${:.2}", p.name, p.price),
166        None => println!("  Not found"),
167    }
168    println!("  ✅ Stopped at first match!");
169
170    // ============================================================================
171    // LAZY OPERATION 6: any - Existence Check
172    // ============================================================================
173    println!("\n═══════════════════════════════════════════════════════════════");
174    println!("Lazy Operation 6: any (existence check)");
175    println!("═══════════════════════════════════════════════════════════════\n");
176
177    println!("Checking if any furniture exists...");
178    let has_furniture = LazyQuery::new(&products)
179        .where_(Product::category_r(), |cat| cat == "Furniture")
180        .any();
181
182    println!("  Has furniture: {}", has_furniture);
183    println!("  ✅ Stopped immediately after finding first match!");
184
185    // ============================================================================
186    // LAZY OPERATION 7: count - Count Matching Items
187    // ============================================================================
188    println!("\n═══════════════════════════════════════════════════════════════");
189    println!("Lazy Operation 7: count");
190    println!("═══════════════════════════════════════════════════════════════\n");
191
192    let electronics_count = LazyQuery::new(&products)
193        .where_(Product::category_r(), |cat| cat == "Electronics")
194        .count();
195
196    println!("  Electronics count: {}", electronics_count);
197
198    // ============================================================================
199    // LAZY OPERATION 8: sum_by - Aggregation
200    // ============================================================================
201    println!("\n═══════════════════════════════════════════════════════════════");
202    println!("Lazy Operation 8: sum_by (aggregation)");
203    println!("═══════════════════════════════════════════════════════════════\n");
204
205    let total_value: f64 = LazyQuery::new(&products)
206        .where_(Product::category_r(), |cat| cat == "Electronics")
207        .sum_by(Product::price_r());
208
209    println!("  Total electronics value: ${:.2}", total_value);
210
211    // ============================================================================
212    // LAZY OPERATION 9: avg_by - Average
213    // ============================================================================
214    println!("\n═══════════════════════════════════════════════════════════════");
215    println!("Lazy Operation 9: avg_by");
216    println!("═══════════════════════════════════════════════════════════════\n");
217
218    let avg_price = LazyQuery::new(&products)
219        .where_(Product::category_r(), |cat| cat == "Furniture")
220        .avg_by(Product::price_r())
221        .unwrap_or(0.0);
222
223    println!("  Average furniture price: ${:.2}", avg_price);
224
225    // ============================================================================
226    // LAZY OPERATION 10: min_by_float / max_by_float
227    // ============================================================================
228    println!("\n═══════════════════════════════════════════════════════════════");
229    println!("Lazy Operation 10: min_by_float / max_by_float");
230    println!("═══════════════════════════════════════════════════════════════\n");
231
232    let min_price = LazyQuery::new(&products)
233        .where_(Product::active_r(), |&active| active)
234        .min_by_float(Product::price_r())
235        .unwrap_or(0.0);
236
237    let max_price = LazyQuery::new(&products)
238        .where_(Product::active_r(), |&active| active)
239        .max_by_float(Product::price_r())
240        .unwrap_or(0.0);
241
242    println!("  Price range for active products:");
243    println!("    Min: ${:.2}", min_price);
244    println!("    Max: ${:.2}", max_price);
245
246    // ============================================================================
247    // LAZY OPERATION 11: find - Find with Predicate
248    // ============================================================================
249    println!("\n═══════════════════════════════════════════════════════════════");
250    println!("Lazy Operation 11: find (with predicate)");
251    println!("═══════════════════════════════════════════════════════════════\n");
252
253    let high_rated = LazyQuery::new(&products)
254        .where_(Product::category_r(), |cat| cat == "Electronics")
255        .find(|item| item.rating > 4.7);
256
257    if let Some(product) = high_rated {
258        println!("  First highly-rated electronic:");
259        println!("    {}: Rating {:.1}", product.name, product.rating);
260    }
261
262    // ============================================================================
263    // LAZY OPERATION 12: for_each - Iteration
264    // ============================================================================
265    println!("\n═══════════════════════════════════════════════════════════════");
266    println!("Lazy Operation 12: for_each (iteration)");
267    println!("═══════════════════════════════════════════════════════════════\n");
268
269    println!("  Low stock alerts:");
270    LazyQuery::new(&products)
271        .where_(Product::stock_r(), |&stock| stock < 20)
272        .for_each(|product| {
273            println!("    ⚠️  {}: Only {} in stock", product.name, product.stock);
274        });
275
276    // ============================================================================
277    // LAZY OPERATION 13: fold - Custom Aggregation
278    // ============================================================================
279    println!("\n═══════════════════════════════════════════════════════════════");
280    println!("Lazy Operation 14: fold (custom aggregation)");
281    println!("═══════════════════════════════════════════════════════════════\n");
282
283    let total_inventory_value = LazyQuery::new(&products)
284        .where_(Product::active_r(), |&active| active)
285        .fold(0.0, |acc, product| {
286            acc + (product.price * product.stock as f64)
287        });
288
289    println!("  Total inventory value: ${:.2}", total_inventory_value);
290
291    // ============================================================================
292    // LAZY OPERATION 14: all_match - Validation
293    // ============================================================================
294    println!("\n═══════════════════════════════════════════════════════════════");
295    println!("Lazy Operation 15: all_match (validation)");
296    println!("═══════════════════════════════════════════════════════════════\n");
297
298    let all_priced = LazyQuery::new(&products)
299        .all_match(|item| item.price > 0.0);
300
301    println!("  All products have valid prices: {}", all_priced);
302
303    // ============================================================================
304    // LAZY OPERATION 15: into_iter - For Loop
305    // ============================================================================
306    println!("\n═══════════════════════════════════════════════════════════════");
307    println!("Lazy Operation 16: into_iter (for loop)");
308    println!("═══════════════════════════════════════════════════════════════\n");
309
310    println!("  High-value products (>$300):");
311    for product in LazyQuery::new(&products)
312        .where_(Product::price_r(), |&p| p > 300.0)
313        .take_lazy(5)
314    {
315        println!("    • {}: ${:.2}", product.name, product.price);
316    }
317
318    // ============================================================================
319    // LAZY OPERATION 16: map_items - Transform
320    // ============================================================================
321    println!("\n═══════════════════════════════════════════════════════════════");
322    println!("Lazy Operation 17: map_items (transformation)");
323    println!("═══════════════════════════════════════════════════════════════\n");
324
325    let price_tags: Vec<String> = LazyQuery::new(&products)
326        .where_(Product::category_r(), |cat| cat == "Electronics")
327        .map_items(|p| format!("{}: ${:.2}", p.name, p.price))
328        .take(5)
329        .collect();
330
331    println!("  Electronics price tags:");
332    for tag in &price_tags {
333        println!("    • {}", tag);
334    }
335
336    // ============================================================================
337    // COMPLEX EXAMPLE: Multi-Stage Lazy Pipeline
338    // ============================================================================
339    println!("\n═══════════════════════════════════════════════════════════════");
340    println!("Complex Example: Multi-stage lazy pipeline");
341    println!("═══════════════════════════════════════════════════════════════\n");
342
343    println!("Building complex query:");
344    println!("  1. Filter by category (Electronics)");
345    println!("  2. Filter by price range ($50-$500)");
346    println!("  3. Filter by rating (>4.5)");
347    println!("  4. Select names");
348    println!("  5. Take first 3");
349    println!();
350
351    let results: Vec<String> = LazyQuery::new(&products)
352        .where_(Product::category_r(), |cat| cat == "Electronics")
353        .where_(Product::price_r(), |&p| p >= 50.0 && p <= 500.0)
354        .where_(Product::rating_r(), |&r| r > 4.5)
355        .select_lazy(Product::name_r())
356        .take(3)
357        .collect();
358
359    println!("  Results:");
360    for (i, name) in results.iter().enumerate() {
361        println!("    {}. {}", i + 1, name);
362    }
363    println!("  ✅ All operations fused and executed lazily!");
364
365    // ============================================================================
366    // THREAD-SAFE UPDATES WITH RWLOCK
367    // ============================================================================
368    println!("\n═══════════════════════════════════════════════════════════════");
369    println!("Bonus: Thread-safe updates with RwLock");
370    println!("═══════════════════════════════════════════════════════════════\n");
371
372    // Update a product through the Arc<RwLock>
373    if let Some(product_arc) = product_map.get("PROD-002") {
374        println!("Updating PROD-002 stock...");
375        
376        // Write lock for mutation
377        if let Ok(mut product) = product_arc.write() {
378            let old_stock = product.stock;
379            product.stock = 25;
380            println!("  Stock updated: {} → {}", old_stock, product.stock);
381        }
382    }
383
384    // Query again to see the update
385    let updated_products = extract_products(&product_map);
386    let mouse = LazyQuery::new(&updated_products)
387        .find(|p| p.id == 2);
388
389    if let Some(product) = mouse {
390        println!("  Verified update: {} now has {} in stock", product.name, product.stock);
391    }
392
393    // ============================================================================
394    // PRACTICAL EXAMPLE: Price Analysis by Category
395    // ============================================================================
396    println!("\n═══════════════════════════════════════════════════════════════");
397    println!("Practical Example: Price analysis by category");
398    println!("═══════════════════════════════════════════════════════════════\n");
399
400    let categories = vec!["Electronics", "Furniture"];
401
402    for category in categories {
403        println!("  {} Statistics:", category);
404        
405        // Filter products by category first
406        let cat_products: Vec<Product> = products.iter()
407            .filter(|p| p.category == category)
408            .cloned()
409            .collect();
410
411        let count = LazyQuery::new(&cat_products).count();
412        let total = LazyQuery::new(&cat_products).sum_by(Product::price_r());
413        let avg = LazyQuery::new(&cat_products).avg_by(Product::price_r()).unwrap_or(0.0);
414        let min = LazyQuery::new(&cat_products).min_by_float(Product::price_r()).unwrap_or(0.0);
415        let max = LazyQuery::new(&cat_products).max_by_float(Product::price_r()).unwrap_or(0.0);
416
417        println!("    Count: {}", count);
418        println!("    Total: ${:.2}", total);
419        println!("    Average: ${:.2}", avg);
420        println!("    Range: ${:.2} - ${:.2}\n", min, max);
421    }
422
423    // ============================================================================
424    // COMBINING WITH HASHMAP OPERATIONS
425    // ============================================================================
426    println!("═══════════════════════════════════════════════════════════════");
427    println!("HashMap Integration: Query by key patterns");
428    println!("═══════════════════════════════════════════════════════════════\n");
429
430    // Filter HashMap by key pattern
431    let electronics_keys: Vec<String> = product_map
432        .iter()
433        .filter(|(_key, value)| {
434            // Read the value to check category
435            if let Ok(guard) = value.read() {
436                guard.category == "Electronics"
437            } else {
438                false
439            }
440        })
441        .map(|(key, _value)| key.clone())
442        .collect();
443
444    println!("  Electronics product IDs:");
445    for key in electronics_keys.iter().take(5) {
446        println!("    • {}", key);
447    }
448
449    // ============================================================================
450    // PERFORMANCE DEMONSTRATION
451    // ============================================================================
452    println!("\n═══════════════════════════════════════════════════════════════");
453    println!("Performance: Lazy vs Eager comparison");
454    println!("═══════════════════════════════════════════════════════════════\n");
455
456    println!("Scenario: Find first product with rating > 4.7 from {} products\n", products.len());
457
458    println!("  Eager approach (hypothetical):");
459    println!("    - Filter all {} products", products.len());
460    println!("    - Collect filtered results");
461    println!("    - Take first item");
462    println!("    - Wasted work: Check all items\n");
463
464    println!("  Lazy approach (actual):");
465    let _first_rated = LazyQuery::new(&products)
466        .where_(Product::rating_r(), |&r| r > 4.7)
467        .first();
468    println!("    - Starts checking products");
469    println!("    - Stops at first match");
470    println!("    - ✅ Early termination - checks ~3-5 items only!");
471
472    // ============================================================================
473    // Summary
474    // ============================================================================
475    println!("\n╔══════════════════════════════════════════════════════════════════╗");
476    println!("║  Summary: All Lazy Operations Demonstrated                      ║");
477    println!("╚══════════════════════════════════════════════════════════════════╝\n");
478
479    println!("✅ Lazy Query Operations:");
480    println!("   1. ✅ where_ - Lazy filtering");
481    println!("   2. ✅ select_lazy - Lazy projection");
482    println!("   3. ✅ take_lazy - Early termination");
483    println!("   4. ✅ skip_lazy - Pagination");
484    println!("   5. ✅ first - Short-circuit search");
485    println!("   6. ✅ any - Existence check (short-circuit)");
486    println!("   7. ✅ count - Count items");
487    println!("   8. ✅ sum_by - Sum aggregation");
488    println!("   9. ✅ avg_by - Average aggregation");
489    println!("   10. ✅ min_by_float - Minimum value");
490    println!("   11. ✅ max_by_float - Maximum value");
491    println!("   12. ✅ find - Find with predicate (short-circuit)");
492    println!("   13. ✅ for_each - Iteration");
493    println!("   14. ✅ fold - Custom aggregation");
494    println!("   15. ✅ all_match - Validation (short-circuit)");
495    println!("   16. ✅ into_iter - For loop support");
496    println!("   17. ✅ map_items - Transformation\n");
497
498    println!("✅ Arc<RwLock<T>> Benefits:");
499    println!("   • Thread-safe shared access");
500    println!("   • Interior mutability");
501    println!("   • Multiple readers, single writer");
502    println!("   • Reference counting (Arc)");
503    println!("   • Can be queried after extracting data\n");
504
505    println!("✅ HashMap<K, Arc<RwLock<V>>> Benefits:");
506    println!("   • Fast key-based lookup");
507    println!("   • Thread-safe value access");
508    println!("   • Can query all values");
509    println!("   • Can filter by key patterns");
510    println!("   • Perfect for shared state/caches\n");
511
512    println!("🎯 Use Cases:");
513    println!("   • Shared product catalogs");
514    println!("   • User session stores");
515    println!("   • Configuration caches");
516    println!("   • Real-time inventory systems");
517    println!("   • Multi-threaded data processing");
518    println!("   • Web server state management\n");
519
520    println!("✓ Arc<RwLock<T>> HashMap with all lazy operations demo complete!\n");
521}
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/individual_crates.rs (line 127)
27fn main() {
28    println!("Individual Crates Example");
29    println!("=========================\n");
30    println!("Using rust-queries-core + rust-queries-derive directly\n");
31
32    let products = vec![
33        Product {
34            id: 1,
35            name: "Laptop".to_string(),
36            price: 999.99,
37            category: "Electronics".to_string(),
38            stock: 5,
39        },
40        Product {
41            id: 2,
42            name: "Mouse".to_string(),
43            price: 29.99,
44            category: "Electronics".to_string(),
45            stock: 50,
46        },
47        Product {
48            id: 3,
49            name: "Keyboard".to_string(),
50            price: 79.99,
51            category: "Electronics".to_string(),
52            stock: 30,
53        },
54        Product {
55            id: 4,
56            name: "Monitor".to_string(),
57            price: 299.99,
58            category: "Electronics".to_string(),
59            stock: 12,
60        },
61        Product {
62            id: 5,
63            name: "Desk Chair".to_string(),
64            price: 199.99,
65            category: "Furniture".to_string(),
66            stock: 8,
67        },
68    ];
69
70    println!("1. QueryExt from rust_queries_core");
71    println!("   products.query().where_(price > 100).all()");
72    
73    let query = products
74        .query()  // From QueryExt trait
75        .where_(Product::price_r(), |&p| p > 100.0);
76    let expensive = query.all();
77    
78    println!("   Found {} expensive products:", expensive.len());
79    for product in expensive {
80        println!("   - {} (${:.2})", product.name, product.price);
81    }
82    println!();
83
84    println!("2. QueryBuilder from rust_queries_derive");
85    println!("   Product::query(&products).where_(stock < 10).all()");
86    
87    let query2 = Product::query(&products)  // From QueryBuilder derive
88        .where_(Product::stock_r(), |&s| s < 10);
89    let low_stock = query2.all();
90    
91    println!("   Found {} low stock products:", low_stock.len());
92    for product in low_stock {
93        println!("   - {} (stock: {})", product.name, product.stock);
94    }
95    println!();
96
97    println!("3. LazyQuery from rust_queries_core");
98    println!("   products.lazy_query().where_(...).collect()");
99    
100    let electronics: Vec<_> = products
101        .lazy_query()  // From QueryExt trait
102        .where_(Product::category_r(), |cat| cat == "Electronics")
103        .collect();
104    
105    println!("   Found {} electronics:", electronics.len());
106    for product in electronics {
107        println!("   - {}", product.name);
108    }
109    println!();
110
111    println!("4. Aggregations with LazyQuery");
112    println!("   products.lazy_query().sum_by(Product::price_r())");
113    
114    let total_value: f64 = products
115        .lazy_query()
116        .sum_by(Product::price_r());
117    
118    println!("   Total inventory value: ${:.2}", total_value);
119    println!();
120
121    println!("5. Early termination with lazy queries");
122    println!("   products.lazy_query().where_(...).first()");
123    
124    if let Some(first_cheap) = products
125        .lazy_query()
126        .where_(Product::price_r(), |&p| p < 50.0)
127        .first()
128    {
129        println!("   First cheap product: {} (${:.2})", first_cheap.name, first_cheap.price);
130    }
131    println!();
132
133    println!("6. Using Query (eager) from rust_queries_core");
134    println!("   Query::new(&products).where_(...).count()");
135    
136    let query3 = Query::new(&products)  // Traditional approach
137        .where_(Product::price_r(), |&p| p > 50.0);
138    let count = query3.count();
139    
140    println!("   Products over $50: {}", count);
141    println!();
142
143    println!("Summary:");
144    println!("--------");
145    println!("✓ rust_queries_core provides: Query, LazyQuery, QueryExt");
146    println!("✓ rust_queries_derive provides: #[derive(QueryBuilder)]");
147    println!("✓ key_paths_derive provides: #[derive(Keypaths)]");
148    println!("✓ All features work with individual crates!");
149}
More examples
Hide additional examples
examples/derive_and_ext.rs (line 112)
13fn main() {
14    println!("Derive Macros and Extension Traits Example");
15    println!("===========================================\n");
16
17    let products = vec![
18        Product {
19            id: 1,
20            name: "Laptop".to_string(),
21            price: 999.99,
22            category: "Electronics".to_string(),
23            stock: 5,
24        },
25        Product {
26            id: 2,
27            name: "Mouse".to_string(),
28            price: 29.99,
29            category: "Electronics".to_string(),
30            stock: 50,
31        },
32        Product {
33            id: 3,
34            name: "Keyboard".to_string(),
35            price: 79.99,
36            category: "Electronics".to_string(),
37            stock: 30,
38        },
39        Product {
40            id: 4,
41            name: "Monitor".to_string(),
42            price: 299.99,
43            category: "Electronics".to_string(),
44            stock: 12,
45        },
46        Product {
47            id: 5,
48            name: "Desk Chair".to_string(),
49            price: 199.99,
50            category: "Furniture".to_string(),
51            stock: 8,
52        },
53    ];
54
55    println!("1. Using Extension Trait - Direct .query() on Vec");
56    println!("   Query: products.query().where_(price > 100).all()");
57    
58    let query = products
59        .query()
60        .where_(Product::price_r(), |&p| p > 100.0);
61    let expensive = query.all();
62    
63    println!("   Found {} expensive products:", expensive.len());
64    for product in &expensive {
65        println!("   - {} (${:.2})", product.name, product.price);
66    }
67    println!();
68
69    println!("2. Using Extension Trait - Direct .lazy_query() on Vec");
70    println!("   Query: products.lazy_query().where_(stock < 10).collect()");
71    
72    let low_stock: Vec<_> = products
73        .lazy_query()
74        .where_(Product::stock_r(), |&s| s < 10)
75        .collect();
76    
77    println!("   Found {} low stock products:", low_stock.len());
78    for product in &low_stock {
79        println!("   - {} (stock: {})", product.name, product.stock);
80    }
81    println!();
82
83    println!("3. Using Extension Trait - Chained Operations");
84    println!("   Query: products.lazy_query().where_(category == Electronics).take(2).select(name).collect()");
85    
86    let names: Vec<String> = products
87        .lazy_query()
88        .where_(Product::category_r(), |cat| cat == "Electronics")
89        .take_lazy(2)
90        .select_lazy(Product::name_r())
91        .collect();
92    
93    println!("   First 2 electronics:");
94    for name in &names {
95        println!("   - {}", name);
96    }
97    println!();
98
99    println!("4. Using QueryBuilder Derive - Static Methods");
100    println!("   Query: Product::query(&products).where_(price > 50).count()");
101    
102    let query4 = Product::query(&products)
103        .where_(Product::price_r(), |&p| p > 50.0);
104    let count = query4.count();
105    
106    println!("   Products over $50: {}", count);
107    println!();
108
109    println!("5. Using QueryBuilder Derive - Lazy Static Methods");
110    println!("   Query: Product::lazy_query(&products).first()");
111    
112    if let Some(first) = Product::lazy_query(&products).first() {
113        println!("   First product: {} (${:.2})", first.name, first.price);
114    }
115    println!();
116
117    println!("6. Complex Chain with Extension Trait");
118    println!("   Query: products.lazy_query()");
119    println!("          .where_(category == Electronics)");
120    println!("          .where_(price < 500)");
121    println!("          .map(|p| format!(\"{{}} - ${{:.2}}\", p.name, p.price))");
122    println!("          .collect()");
123    
124    let formatted: Vec<String> = products
125        .lazy_query()
126        .where_(Product::category_r(), |cat| cat == "Electronics")
127        .where_(Product::price_r(), |&p| p < 500.0)
128        .map_items(|p| format!("{} - ${:.2}", p.name, p.price))
129        .collect();
130    
131    println!("   Affordable electronics:");
132    for item in &formatted {
133        println!("   - {}", item);
134    }
135    println!();
136
137    println!("7. Aggregation with Extension Trait");
138    println!("   Query: products.lazy_query().sum_by(Product::stock())");
139    
140    let total_stock = products
141        .lazy_query()
142        .sum_by(Product::stock_r());
143    
144    println!("   Total stock across all products: {}", total_stock);
145    println!();
146
147    println!("8. Find with Extension Trait");
148    println!("   Query: products.lazy_query().find(|p| p.name.contains(\"Chair\"))");
149    
150    if let Some(chair) = products.lazy_query().find(|p| p.name.contains("Chair")) {
151        println!("   Found: {} in {}", chair.name, chair.category);
152    }
153    println!();
154
155    println!("9. Early Termination with Extension Trait");
156    println!("   Query: products.lazy_query().where_(price > 1000).any()");
157    
158    let has_luxury = products
159        .lazy_query()
160        .where_(Product::price_r(), |&p| p > 1000.0)
161        .any();
162    
163    println!("   Has products over $1000: {}", has_luxury);
164    println!();
165
166    println!("10. Slice Extension Trait");
167    println!("    Query: (&products[..]).lazy_query().count()");
168    
169    let slice_count = (&products[..])
170        .lazy_query()
171        .count();
172    
173    println!("    Count from slice: {}", slice_count);
174    println!();
175
176    println!("Summary:");
177    println!("--------");
178    println!("✓ Extension trait QueryExt adds .query() and .lazy_query() to containers");
179    println!("✓ Derive macro QueryBuilder adds static methods Product::query() and Product::lazy_query()");
180    println!("✓ Both approaches provide the same query functionality");
181    println!("✓ Extension trait is more ergonomic: products.query() vs Query::new(&products)");
182    println!("✓ All iterator optimizations (fusion, early termination) still apply");
183}
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}
examples/custom_queryable.rs (line 401)
230fn main() {
231    println!("\n╔════════════════════════════════════════════════════════════════╗");
232    println!("║  Custom Queryable Implementation Demo                         ║");
233    println!("╚════════════════════════════════════════════════════════════════╝\n");
234
235    // ============================================================================
236    // DEMO 1: PaginatedCollection
237    // ============================================================================
238    println!("═══════════════════════════════════════════════════════════════");
239    println!("Demo 1: PaginatedCollection (custom container)");
240    println!("═══════════════════════════════════════════════════════════════\n");
241
242    let mut paginated = PaginatedCollection::new(3); // 3 items per page
243    
244    paginated.add(create_sample_product(1, "Laptop", 999.0, "Electronics", true));
245    paginated.add(create_sample_product(2, "Mouse", 29.0, "Electronics", true));
246    paginated.add(create_sample_product(3, "Keyboard", 129.0, "Electronics", true));
247    paginated.add(create_sample_product(4, "Desk", 299.0, "Furniture", true));
248    paginated.add(create_sample_product(5, "Chair", 199.0, "Furniture", false));
249
250    println!("  Created paginated collection:");
251    println!("    Total items: {}", paginated.total_items());
252    println!("    Pages: {}", paginated.pages.len());
253
254    // Now we can query it using the Queryable trait!
255    // Collect to owned Vec for querying
256    let items: Vec<Product> = paginated.query_iter().cloned().collect();
257    let query = Query::new(&items)
258        .where_(Product::category_r(), |cat| cat == "Electronics");
259    let electronics = query.all();
260    
261    println!("\n  Querying paginated collection:");
262    println!("    Electronics found: {}", electronics.len());
263    for product in electronics {
264        println!("      • {}: ${:.2}", product.name, product.price);
265    }
266
267    // ============================================================================
268    // DEMO 2: CircularBuffer
269    // ============================================================================
270    println!("\n═══════════════════════════════════════════════════════════════");
271    println!("Demo 2: CircularBuffer (fixed capacity)");
272    println!("═══════════════════════════════════════════════════════════════\n");
273
274    let mut circular = CircularBuffer::new(3); // Capacity: 3
275    
276    circular.push(create_sample_product(1, "Product 1", 100.0, "A", true));
277    circular.push(create_sample_product(2, "Product 2", 200.0, "B", true));
278    circular.push(create_sample_product(3, "Product 3", 300.0, "C", true));
279    circular.push(create_sample_product(4, "Product 4", 400.0, "D", true)); // Pushes out Product 1
280
281    println!("  Circular buffer (capacity 3, added 4 items):");
282    println!("    Current size: {}", circular.len());
283
284    // Query the circular buffer
285    let circ_items: Vec<Product> = circular.query_iter().cloned().collect();
286    let circ_query = Query::new(&circ_items);
287    let avg_price = circ_query.avg(Product::price_r()).unwrap_or(0.0);
288    
289    println!("\n  Querying circular buffer:");
290    println!("    Average price: ${:.2}", avg_price);
291    println!("    Items:");
292    for (i, product) in circ_items.iter().enumerate() {
293        println!("      {}. {}: ${:.2}", i + 1, product.name, product.price);
294    }
295
296    // ============================================================================
297    // DEMO 3: FilteredStorage
298    // ============================================================================
299    println!("\n═══════════════════════════════════════════════════════════════");
300    println!("Demo 3: FilteredStorage (auto-filtering container)");
301    println!("═══════════════════════════════════════════════════════════════\n");
302
303    let mut filtered = FilteredStorage::new(|p: &Product| p.price < 200.0);
304    
305    println!("  FilteredStorage (only accepts items < $200):");
306    println!("    Adding Laptop ($999): {}", filtered.add(create_sample_product(1, "Laptop", 999.0, "Electronics", true)));
307    println!("    Adding Mouse ($29): {}", filtered.add(create_sample_product(2, "Mouse", 29.0, "Electronics", true)));
308    println!("    Adding Keyboard ($129): {}", filtered.add(create_sample_product(3, "Keyboard", 129.0, "Electronics", true)));
309    println!("    Total stored: {}", filtered.len());
310
311    // Query the filtered storage
312    let filt_items: Vec<Product> = filtered.query_iter().cloned().collect();
313    let filt_query = Query::new(&filt_items)
314        .where_(Product::in_stock_r(), |&v| v);
315    let in_stock = filt_query.all();
316    
317    println!("\n  Querying filtered storage:");
318    println!("    In stock items: {}", in_stock.len());
319
320    // ============================================================================
321    // DEMO 4: CategoryIndex
322    // ============================================================================
323    println!("\n═══════════════════════════════════════════════════════════════");
324    println!("Demo 4: CategoryIndex (indexed by category)");
325    println!("═══════════════════════════════════════════════════════════════\n");
326
327    let mut category_index = CategoryIndex::new();
328    
329    category_index.add("Electronics".to_string(), create_sample_product(1, "Monitor", 349.0, "Electronics", true));
330    category_index.add("Electronics".to_string(), create_sample_product(2, "Webcam", 79.0, "Electronics", true));
331    category_index.add("Furniture".to_string(), create_sample_product(3, "Desk", 299.0, "Furniture", true));
332    category_index.add("Furniture".to_string(), create_sample_product(4, "Lamp", 39.0, "Furniture", true));
333
334    println!("  CategoryIndex:");
335    println!("    Categories: {:?}", category_index.categories());
336    println!("    Total items: {}", category_index.total_items());
337
338    // Query across all categories
339    let idx_items: Vec<Product> = category_index.query_iter().cloned().collect();
340    let idx_query = Query::new(&idx_items);
341    let expensive = idx_query
342        .where_(Product::price_r(), |&p| p > 100.0);
343    let expensive_items = expensive.all();
344    
345    println!("\n  Querying category index:");
346    println!("    Expensive items (>$100): {}", expensive_items.len());
347    for product in expensive_items {
348        println!("      • {}: ${:.2} ({})", product.name, product.price, product.category);
349    }
350
351    // ============================================================================
352    // DEMO 5: LazyLoader
353    // ============================================================================
354    println!("\n═══════════════════════════════════════════════════════════════");
355    println!("Demo 5: LazyLoader (simulated lazy loading)");
356    println!("═══════════════════════════════════════════════════════════════\n");
357
358    let loader = LazyLoader::new(vec![
359        create_sample_product(1, "Item 1", 50.0, "A", true),
360        create_sample_product(2, "Item 2", 150.0, "B", true),
361        create_sample_product(3, "Item 3", 250.0, "C", true),
362    ]);
363
364    println!("  LazyLoader:");
365    println!("    Total available: {}", loader.total_count());
366    println!("    Currently loaded: {}", loader.loaded_count());
367
368    // Query loaded items
369    let loader_items: Vec<Product> = loader.query_iter().cloned().collect();
370    let loader_query = Query::new(&loader_items);
371    let total_value = loader_query.sum(Product::price_r());
372    
373    println!("\n  Querying lazy loader:");
374    println!("    Total value: ${:.2}", total_value);
375
376    // ============================================================================
377    // DEMO 6: Custom Container with LazyQuery
378    // ============================================================================
379    println!("\n═══════════════════════════════════════════════════════════════");
380    println!("Demo 6: Using LazyQuery with custom containers");
381    println!("═══════════════════════════════════════════════════════════════\n");
382
383    let mut circular = CircularBuffer::new(5);
384    for i in 1..=10 {
385        circular.push(create_sample_product(
386            i,
387            &format!("Product {}", i),
388            i as f64 * 50.0,
389            if i % 2 == 0 { "Even" } else { "Odd" },
390            true,
391        ));
392    }
393
394    println!("  Circular buffer (capacity 5, added 10 items):");
395    println!("    Current size: {}", circular.len());
396
397    // Use LazyQuery for early termination!
398    let circ_vec: Vec<Product> = circular.query_iter().cloned().collect();
399    let first_expensive = LazyQuery::new(&circ_vec)
400        .where_(Product::price_r(), |&p| p > 300.0)
401        .first();
402
403    if let Some(product) = first_expensive {
404        println!("\n  First expensive item (lazy query):");
405        println!("    {}: ${:.2}", product.name, product.price);
406    }
407
408    // ============================================================================
409    // DEMO 7: Implementing Queryable for Wrapper Types
410    // ============================================================================
411    println!("\n═══════════════════════════════════════════════════════════════");
412    println!("Demo 7: Queryable for wrapper types");
413    println!("═══════════════════════════════════════════════════════════════\n");
414
415    /// A simple wrapper around Vec with metadata
416    struct VersionedCollection<T> {
417        items: Vec<T>,
418        version: u32,
419        last_modified: String,
420    }
421
422    impl<T> Queryable<T> for VersionedCollection<T> {
423        fn query_iter(&self) -> Box<dyn Iterator<Item = &T> + '_> {
424            Box::new(self.items.iter())
425        }
426    }
427
428    let versioned = VersionedCollection {
429        items: vec![
430            create_sample_product(1, "V1 Product", 99.0, "Test", true),
431            create_sample_product(2, "V2 Product", 199.0, "Test", true),
432        ],
433        version: 2,
434        last_modified: "2025-10-11".to_string(),
435    };
436
437    println!("  VersionedCollection:");
438    println!("    Version: {}", versioned.version);
439    println!("    Last modified: {}", versioned.last_modified);
440
441    let versioned_items: Vec<Product> = versioned.query_iter().cloned().collect();
442    let query = Query::new(&versioned_items);
443    println!("    Items: {}", query.count());
444
445    // ============================================================================
446    // DEMO 8: Real-World Example - Cache with TTL
447    // ============================================================================
448    println!("\n═══════════════════════════════════════════════════════════════");
449    println!("Demo 8: Cache container (real-world example)");
450    println!("═══════════════════════════════════════════════════════════════\n");
451
452    use std::time::{Duration, SystemTime};
453
454    struct CachedItem<T> {
455        item: T,
456        inserted_at: SystemTime,
457        ttl: Duration,
458    }
459
460    struct Cache<T> {
461        items: Vec<CachedItem<T>>,
462    }
463
464    impl<T> Cache<T> {
465        fn new() -> Self {
466            Self { items: Vec::new() }
467        }
468
469        fn insert(&mut self, item: T, ttl: Duration) {
470            self.items.push(CachedItem {
471                item,
472                inserted_at: SystemTime::now(),
473                ttl,
474            });
475        }
476
477        fn valid_items(&self) -> Vec<&T> {
478            let now = SystemTime::now();
479            self.items
480                .iter()
481                .filter(|cached| {
482                    now.duration_since(cached.inserted_at)
483                        .map_or(false, |elapsed| elapsed < cached.ttl)
484                })
485                .map(|cached| &cached.item)
486                .collect()
487        }
488    }
489
490    // Implement Queryable to query only valid (non-expired) items
491    impl<T> Queryable<T> for Cache<T> {
492        fn query_iter(&self) -> Box<dyn Iterator<Item = &T> + '_> {
493            let now = SystemTime::now();
494            Box::new(
495                self.items
496                    .iter()
497                    .filter(move |cached| {
498                        now.duration_since(cached.inserted_at)
499                            .map_or(false, |elapsed| elapsed < cached.ttl)
500                    })
501                    .map(|cached| &cached.item),
502            )
503        }
504    }
505
506    let mut cache = Cache::new();
507    cache.insert(create_sample_product(1, "Cached Item 1", 100.0, "A", true), Duration::from_secs(60));
508    cache.insert(create_sample_product(2, "Cached Item 2", 200.0, "B", true), Duration::from_secs(60));
509
510    let valid = cache.valid_items();
511    println!("  Cache:");
512    println!("    Total items: {}", cache.items.len());
513    println!("    Valid items: {}", valid.len());
514
515    // Query the cache
516    let cache_items: Vec<Product> = cache.query_iter().cloned().collect();
517    let cache_query = Query::new(&cache_items);
518    println!("    Queryable items: {}", cache_query.count());
519
520    // ============================================================================
521    // Summary
522    // ============================================================================
523    println!("\n╔════════════════════════════════════════════════════════════════╗");
524    println!("║  Summary: Implementing Queryable                              ║");
525    println!("╚════════════════════════════════════════════════════════════════╝\n");
526
527    println!("✅ How to make any container queryable:\n");
528    println!("  1. Implement the Queryable<T> trait:");
529    println!("     ```rust");
530    println!("     impl<T> Queryable<T> for MyContainer<T> {{");
531    println!("         fn query_iter(&self) -> Box<dyn Iterator<Item = &T> + '_> {{");
532    println!("             Box::new(self.items.iter())");
533    println!("         }}");
534    println!("     }}");
535    println!("     ```\n");
536
537    println!("  2. Convert to Vec or slice for querying:");
538    println!("     ```rust");
539    println!("     let items: Vec<&Product> = container.query_iter().collect();");
540    println!("     let query = Query::new(&items);");
541    println!("     ```\n");
542
543    println!("  3. Now use all query operations:");
544    println!("     ```rust");
545    println!("     let results = query.where_(...).all();");
546    println!("     let count = query.count();");
547    println!("     let total = query.sum(field);");
548    println!("     ```\n");
549
550    println!("📝 Custom containers demonstrated:");
551    println!("   • PaginatedCollection - Items stored in pages");
552    println!("   • CircularBuffer - Fixed-capacity FIFO buffer");
553    println!("   • FilteredStorage - Auto-filtering container");
554    println!("   • CategoryIndex - Indexed by category");
555    println!("   • LazyLoader - Simulated lazy loading");
556    println!("   • VersionedCollection - Wrapper with metadata");
557    println!("   • Cache - TTL-based cache\n");
558
559    println!("💡 Use cases:");
560    println!("   • Database result wrappers");
561    println!("   • Custom data structures");
562    println!("   • Specialized collections");
563    println!("   • Caches and buffers");
564    println!("   • Event streams");
565    println!("   • Any container that holds items!\n");
566
567    println!("✓ Custom Queryable demo complete!\n");
568}
examples/arc_rwlock_hashmap.rs (line 162)
59fn main() {
60    println!("\n╔══════════════════════════════════════════════════════════════════╗");
61    println!("║  Arc<RwLock<T>> HashMap Lazy Query Demo                         ║");
62    println!("║  Thread-safe shared data with lazy evaluation                   ║");
63    println!("╚══════════════════════════════════════════════════════════════════╝\n");
64
65    let product_map = create_sample_data();
66    println!("Created product catalog:");
67    println!("  Total products: {}", product_map.len());
68    println!("  Keys: {:?}\n", product_map.keys().take(3).collect::<Vec<_>>());
69
70    // Extract products for querying
71    let products = extract_products(&product_map);
72    println!("Extracted {} products from Arc<RwLock<Product>>\n", products.len());
73
74    // ============================================================================
75    // LAZY OPERATION 1: where_ - Lazy Filtering
76    // ============================================================================
77    println!("═══════════════════════════════════════════════════════════════");
78    println!("Lazy Operation 1: where_ (filtering)");
79    println!("═══════════════════════════════════════════════════════════════\n");
80
81    println!("Building filtered query (nothing executes yet)...");
82    let electronics_query = LazyQuery::new(&products)
83        .where_(Product::category_r(), |cat| cat == "Electronics")
84        .where_(Product::active_r(), |&active| active)
85        .where_(Product::stock_r(), |&stock| stock > 20);
86
87    println!("  ✅ Query built (deferred execution)\n");
88
89    println!("Collecting results (executes now)...");
90    let electronics: Vec<_> = electronics_query.collect();
91    println!("  Found {} electronics in stock", electronics.len());
92    for p in &electronics {
93        println!("    • {}: {} in stock", p.name, p.stock);
94    }
95
96    // ============================================================================
97    // LAZY OPERATION 2: select_lazy - Lazy Projection
98    // ============================================================================
99    println!("\n═══════════════════════════════════════════════════════════════");
100    println!("Lazy Operation 2: select_lazy (projection)");
101    println!("═══════════════════════════════════════════════════════════════\n");
102
103    println!("Selecting product names (lazy)...");
104    let names: Vec<String> = LazyQuery::new(&products)
105        .where_(Product::category_r(), |cat| cat == "Furniture")
106        .select_lazy(Product::name_r())
107        .collect();
108
109    println!("  Furniture names ({}):", names.len());
110    for name in &names {
111        println!("    • {}", name);
112    }
113
114    // ============================================================================
115    // LAZY OPERATION 3: take_lazy - Early Termination
116    // ============================================================================
117    println!("\n═══════════════════════════════════════════════════════════════");
118    println!("Lazy Operation 3: take_lazy (early termination)");
119    println!("═══════════════════════════════════════════════════════════════\n");
120
121    println!("Getting first 3 electronics...");
122    let first_3: Vec<_> = LazyQuery::new(&products)
123        .where_(Product::category_r(), |cat| cat == "Electronics")
124        .take_lazy(3)
125        .collect();
126
127    println!("  First 3 electronics:");
128    for (i, p) in first_3.iter().enumerate() {
129        println!("    {}. {} - ${:.2}", i + 1, p.name, p.price);
130    }
131    println!("  ✅ Stopped after finding 3 items!");
132
133    // ============================================================================
134    // LAZY OPERATION 4: skip_lazy - Pagination
135    // ============================================================================
136    println!("\n═══════════════════════════════════════════════════════════════");
137    println!("Lazy Operation 4: skip_lazy (pagination)");
138    println!("═══════════════════════════════════════════════════════════════\n");
139
140    println!("Getting page 2 (skip 3, take 3)...");
141    let page_2: Vec<_> = LazyQuery::new(&products)
142        .where_(Product::active_r(), |&active| active)
143        .skip_lazy(3)
144        .take_lazy(3)
145        .collect();
146
147    println!("  Page 2 items:");
148    for (i, p) in page_2.iter().enumerate() {
149        println!("    {}. {}", i + 4, p.name);
150    }
151
152    // ============================================================================
153    // LAZY OPERATION 5: first - Short-Circuit Search
154    // ============================================================================
155    println!("\n═══════════════════════════════════════════════════════════════");
156    println!("Lazy Operation 5: first (short-circuit)");
157    println!("═══════════════════════════════════════════════════════════════\n");
158
159    println!("Finding first expensive item (>$1000)...");
160    let expensive = LazyQuery::new(&products)
161        .where_(Product::price_r(), |&price| price > 1000.0)
162        .first();
163
164    match expensive {
165        Some(p) => println!("  Found: {} - ${:.2}", p.name, p.price),
166        None => println!("  Not found"),
167    }
168    println!("  ✅ Stopped at first match!");
169
170    // ============================================================================
171    // LAZY OPERATION 6: any - Existence Check
172    // ============================================================================
173    println!("\n═══════════════════════════════════════════════════════════════");
174    println!("Lazy Operation 6: any (existence check)");
175    println!("═══════════════════════════════════════════════════════════════\n");
176
177    println!("Checking if any furniture exists...");
178    let has_furniture = LazyQuery::new(&products)
179        .where_(Product::category_r(), |cat| cat == "Furniture")
180        .any();
181
182    println!("  Has furniture: {}", has_furniture);
183    println!("  ✅ Stopped immediately after finding first match!");
184
185    // ============================================================================
186    // LAZY OPERATION 7: count - Count Matching Items
187    // ============================================================================
188    println!("\n═══════════════════════════════════════════════════════════════");
189    println!("Lazy Operation 7: count");
190    println!("═══════════════════════════════════════════════════════════════\n");
191
192    let electronics_count = LazyQuery::new(&products)
193        .where_(Product::category_r(), |cat| cat == "Electronics")
194        .count();
195
196    println!("  Electronics count: {}", electronics_count);
197
198    // ============================================================================
199    // LAZY OPERATION 8: sum_by - Aggregation
200    // ============================================================================
201    println!("\n═══════════════════════════════════════════════════════════════");
202    println!("Lazy Operation 8: sum_by (aggregation)");
203    println!("═══════════════════════════════════════════════════════════════\n");
204
205    let total_value: f64 = LazyQuery::new(&products)
206        .where_(Product::category_r(), |cat| cat == "Electronics")
207        .sum_by(Product::price_r());
208
209    println!("  Total electronics value: ${:.2}", total_value);
210
211    // ============================================================================
212    // LAZY OPERATION 9: avg_by - Average
213    // ============================================================================
214    println!("\n═══════════════════════════════════════════════════════════════");
215    println!("Lazy Operation 9: avg_by");
216    println!("═══════════════════════════════════════════════════════════════\n");
217
218    let avg_price = LazyQuery::new(&products)
219        .where_(Product::category_r(), |cat| cat == "Furniture")
220        .avg_by(Product::price_r())
221        .unwrap_or(0.0);
222
223    println!("  Average furniture price: ${:.2}", avg_price);
224
225    // ============================================================================
226    // LAZY OPERATION 10: min_by_float / max_by_float
227    // ============================================================================
228    println!("\n═══════════════════════════════════════════════════════════════");
229    println!("Lazy Operation 10: min_by_float / max_by_float");
230    println!("═══════════════════════════════════════════════════════════════\n");
231
232    let min_price = LazyQuery::new(&products)
233        .where_(Product::active_r(), |&active| active)
234        .min_by_float(Product::price_r())
235        .unwrap_or(0.0);
236
237    let max_price = LazyQuery::new(&products)
238        .where_(Product::active_r(), |&active| active)
239        .max_by_float(Product::price_r())
240        .unwrap_or(0.0);
241
242    println!("  Price range for active products:");
243    println!("    Min: ${:.2}", min_price);
244    println!("    Max: ${:.2}", max_price);
245
246    // ============================================================================
247    // LAZY OPERATION 11: find - Find with Predicate
248    // ============================================================================
249    println!("\n═══════════════════════════════════════════════════════════════");
250    println!("Lazy Operation 11: find (with predicate)");
251    println!("═══════════════════════════════════════════════════════════════\n");
252
253    let high_rated = LazyQuery::new(&products)
254        .where_(Product::category_r(), |cat| cat == "Electronics")
255        .find(|item| item.rating > 4.7);
256
257    if let Some(product) = high_rated {
258        println!("  First highly-rated electronic:");
259        println!("    {}: Rating {:.1}", product.name, product.rating);
260    }
261
262    // ============================================================================
263    // LAZY OPERATION 12: for_each - Iteration
264    // ============================================================================
265    println!("\n═══════════════════════════════════════════════════════════════");
266    println!("Lazy Operation 12: for_each (iteration)");
267    println!("═══════════════════════════════════════════════════════════════\n");
268
269    println!("  Low stock alerts:");
270    LazyQuery::new(&products)
271        .where_(Product::stock_r(), |&stock| stock < 20)
272        .for_each(|product| {
273            println!("    ⚠️  {}: Only {} in stock", product.name, product.stock);
274        });
275
276    // ============================================================================
277    // LAZY OPERATION 13: fold - Custom Aggregation
278    // ============================================================================
279    println!("\n═══════════════════════════════════════════════════════════════");
280    println!("Lazy Operation 14: fold (custom aggregation)");
281    println!("═══════════════════════════════════════════════════════════════\n");
282
283    let total_inventory_value = LazyQuery::new(&products)
284        .where_(Product::active_r(), |&active| active)
285        .fold(0.0, |acc, product| {
286            acc + (product.price * product.stock as f64)
287        });
288
289    println!("  Total inventory value: ${:.2}", total_inventory_value);
290
291    // ============================================================================
292    // LAZY OPERATION 14: all_match - Validation
293    // ============================================================================
294    println!("\n═══════════════════════════════════════════════════════════════");
295    println!("Lazy Operation 15: all_match (validation)");
296    println!("═══════════════════════════════════════════════════════════════\n");
297
298    let all_priced = LazyQuery::new(&products)
299        .all_match(|item| item.price > 0.0);
300
301    println!("  All products have valid prices: {}", all_priced);
302
303    // ============================================================================
304    // LAZY OPERATION 15: into_iter - For Loop
305    // ============================================================================
306    println!("\n═══════════════════════════════════════════════════════════════");
307    println!("Lazy Operation 16: into_iter (for loop)");
308    println!("═══════════════════════════════════════════════════════════════\n");
309
310    println!("  High-value products (>$300):");
311    for product in LazyQuery::new(&products)
312        .where_(Product::price_r(), |&p| p > 300.0)
313        .take_lazy(5)
314    {
315        println!("    • {}: ${:.2}", product.name, product.price);
316    }
317
318    // ============================================================================
319    // LAZY OPERATION 16: map_items - Transform
320    // ============================================================================
321    println!("\n═══════════════════════════════════════════════════════════════");
322    println!("Lazy Operation 17: map_items (transformation)");
323    println!("═══════════════════════════════════════════════════════════════\n");
324
325    let price_tags: Vec<String> = LazyQuery::new(&products)
326        .where_(Product::category_r(), |cat| cat == "Electronics")
327        .map_items(|p| format!("{}: ${:.2}", p.name, p.price))
328        .take(5)
329        .collect();
330
331    println!("  Electronics price tags:");
332    for tag in &price_tags {
333        println!("    • {}", tag);
334    }
335
336    // ============================================================================
337    // COMPLEX EXAMPLE: Multi-Stage Lazy Pipeline
338    // ============================================================================
339    println!("\n═══════════════════════════════════════════════════════════════");
340    println!("Complex Example: Multi-stage lazy pipeline");
341    println!("═══════════════════════════════════════════════════════════════\n");
342
343    println!("Building complex query:");
344    println!("  1. Filter by category (Electronics)");
345    println!("  2. Filter by price range ($50-$500)");
346    println!("  3. Filter by rating (>4.5)");
347    println!("  4. Select names");
348    println!("  5. Take first 3");
349    println!();
350
351    let results: Vec<String> = LazyQuery::new(&products)
352        .where_(Product::category_r(), |cat| cat == "Electronics")
353        .where_(Product::price_r(), |&p| p >= 50.0 && p <= 500.0)
354        .where_(Product::rating_r(), |&r| r > 4.5)
355        .select_lazy(Product::name_r())
356        .take(3)
357        .collect();
358
359    println!("  Results:");
360    for (i, name) in results.iter().enumerate() {
361        println!("    {}. {}", i + 1, name);
362    }
363    println!("  ✅ All operations fused and executed lazily!");
364
365    // ============================================================================
366    // THREAD-SAFE UPDATES WITH RWLOCK
367    // ============================================================================
368    println!("\n═══════════════════════════════════════════════════════════════");
369    println!("Bonus: Thread-safe updates with RwLock");
370    println!("═══════════════════════════════════════════════════════════════\n");
371
372    // Update a product through the Arc<RwLock>
373    if let Some(product_arc) = product_map.get("PROD-002") {
374        println!("Updating PROD-002 stock...");
375        
376        // Write lock for mutation
377        if let Ok(mut product) = product_arc.write() {
378            let old_stock = product.stock;
379            product.stock = 25;
380            println!("  Stock updated: {} → {}", old_stock, product.stock);
381        }
382    }
383
384    // Query again to see the update
385    let updated_products = extract_products(&product_map);
386    let mouse = LazyQuery::new(&updated_products)
387        .find(|p| p.id == 2);
388
389    if let Some(product) = mouse {
390        println!("  Verified update: {} now has {} in stock", product.name, product.stock);
391    }
392
393    // ============================================================================
394    // PRACTICAL EXAMPLE: Price Analysis by Category
395    // ============================================================================
396    println!("\n═══════════════════════════════════════════════════════════════");
397    println!("Practical Example: Price analysis by category");
398    println!("═══════════════════════════════════════════════════════════════\n");
399
400    let categories = vec!["Electronics", "Furniture"];
401
402    for category in categories {
403        println!("  {} Statistics:", category);
404        
405        // Filter products by category first
406        let cat_products: Vec<Product> = products.iter()
407            .filter(|p| p.category == category)
408            .cloned()
409            .collect();
410
411        let count = LazyQuery::new(&cat_products).count();
412        let total = LazyQuery::new(&cat_products).sum_by(Product::price_r());
413        let avg = LazyQuery::new(&cat_products).avg_by(Product::price_r()).unwrap_or(0.0);
414        let min = LazyQuery::new(&cat_products).min_by_float(Product::price_r()).unwrap_or(0.0);
415        let max = LazyQuery::new(&cat_products).max_by_float(Product::price_r()).unwrap_or(0.0);
416
417        println!("    Count: {}", count);
418        println!("    Total: ${:.2}", total);
419        println!("    Average: ${:.2}", avg);
420        println!("    Range: ${:.2} - ${:.2}\n", min, max);
421    }
422
423    // ============================================================================
424    // COMBINING WITH HASHMAP OPERATIONS
425    // ============================================================================
426    println!("═══════════════════════════════════════════════════════════════");
427    println!("HashMap Integration: Query by key patterns");
428    println!("═══════════════════════════════════════════════════════════════\n");
429
430    // Filter HashMap by key pattern
431    let electronics_keys: Vec<String> = product_map
432        .iter()
433        .filter(|(_key, value)| {
434            // Read the value to check category
435            if let Ok(guard) = value.read() {
436                guard.category == "Electronics"
437            } else {
438                false
439            }
440        })
441        .map(|(key, _value)| key.clone())
442        .collect();
443
444    println!("  Electronics product IDs:");
445    for key in electronics_keys.iter().take(5) {
446        println!("    • {}", key);
447    }
448
449    // ============================================================================
450    // PERFORMANCE DEMONSTRATION
451    // ============================================================================
452    println!("\n═══════════════════════════════════════════════════════════════");
453    println!("Performance: Lazy vs Eager comparison");
454    println!("═══════════════════════════════════════════════════════════════\n");
455
456    println!("Scenario: Find first product with rating > 4.7 from {} products\n", products.len());
457
458    println!("  Eager approach (hypothetical):");
459    println!("    - Filter all {} products", products.len());
460    println!("    - Collect filtered results");
461    println!("    - Take first item");
462    println!("    - Wasted work: Check all items\n");
463
464    println!("  Lazy approach (actual):");
465    let _first_rated = LazyQuery::new(&products)
466        .where_(Product::rating_r(), |&r| r > 4.7)
467        .first();
468    println!("    - Starts checking products");
469    println!("    - Stops at first match");
470    println!("    - ✅ Early termination - checks ~3-5 items only!");
471
472    // ============================================================================
473    // Summary
474    // ============================================================================
475    println!("\n╔══════════════════════════════════════════════════════════════════╗");
476    println!("║  Summary: All Lazy Operations Demonstrated                      ║");
477    println!("╚══════════════════════════════════════════════════════════════════╝\n");
478
479    println!("✅ Lazy Query Operations:");
480    println!("   1. ✅ where_ - Lazy filtering");
481    println!("   2. ✅ select_lazy - Lazy projection");
482    println!("   3. ✅ take_lazy - Early termination");
483    println!("   4. ✅ skip_lazy - Pagination");
484    println!("   5. ✅ first - Short-circuit search");
485    println!("   6. ✅ any - Existence check (short-circuit)");
486    println!("   7. ✅ count - Count items");
487    println!("   8. ✅ sum_by - Sum aggregation");
488    println!("   9. ✅ avg_by - Average aggregation");
489    println!("   10. ✅ min_by_float - Minimum value");
490    println!("   11. ✅ max_by_float - Maximum value");
491    println!("   12. ✅ find - Find with predicate (short-circuit)");
492    println!("   13. ✅ for_each - Iteration");
493    println!("   14. ✅ fold - Custom aggregation");
494    println!("   15. ✅ all_match - Validation (short-circuit)");
495    println!("   16. ✅ into_iter - For loop support");
496    println!("   17. ✅ map_items - Transformation\n");
497
498    println!("✅ Arc<RwLock<T>> Benefits:");
499    println!("   • Thread-safe shared access");
500    println!("   • Interior mutability");
501    println!("   • Multiple readers, single writer");
502    println!("   • Reference counting (Arc)");
503    println!("   • Can be queried after extracting data\n");
504
505    println!("✅ HashMap<K, Arc<RwLock<V>>> Benefits:");
506    println!("   • Fast key-based lookup");
507    println!("   • Thread-safe value access");
508    println!("   • Can query all values");
509    println!("   • Can filter by key patterns");
510    println!("   • Perfect for shared state/caches\n");
511
512    println!("🎯 Use Cases:");
513    println!("   • Shared product catalogs");
514    println!("   • User session stores");
515    println!("   • Configuration caches");
516    println!("   • Real-time inventory systems");
517    println!("   • Multi-threaded data processing");
518    println!("   • Web server state management\n");
519
520    println!("✓ Arc<RwLock<T>> HashMap with all lazy operations demo complete!\n");
521}
Source

pub fn count(self) -> usize

Counts items (terminal operation - executes query).

§Example
let count = query.count();
Examples found in repository?
examples/derive_and_ext.rs (line 171)
13fn main() {
14    println!("Derive Macros and Extension Traits Example");
15    println!("===========================================\n");
16
17    let products = vec![
18        Product {
19            id: 1,
20            name: "Laptop".to_string(),
21            price: 999.99,
22            category: "Electronics".to_string(),
23            stock: 5,
24        },
25        Product {
26            id: 2,
27            name: "Mouse".to_string(),
28            price: 29.99,
29            category: "Electronics".to_string(),
30            stock: 50,
31        },
32        Product {
33            id: 3,
34            name: "Keyboard".to_string(),
35            price: 79.99,
36            category: "Electronics".to_string(),
37            stock: 30,
38        },
39        Product {
40            id: 4,
41            name: "Monitor".to_string(),
42            price: 299.99,
43            category: "Electronics".to_string(),
44            stock: 12,
45        },
46        Product {
47            id: 5,
48            name: "Desk Chair".to_string(),
49            price: 199.99,
50            category: "Furniture".to_string(),
51            stock: 8,
52        },
53    ];
54
55    println!("1. Using Extension Trait - Direct .query() on Vec");
56    println!("   Query: products.query().where_(price > 100).all()");
57    
58    let query = products
59        .query()
60        .where_(Product::price_r(), |&p| p > 100.0);
61    let expensive = query.all();
62    
63    println!("   Found {} expensive products:", expensive.len());
64    for product in &expensive {
65        println!("   - {} (${:.2})", product.name, product.price);
66    }
67    println!();
68
69    println!("2. Using Extension Trait - Direct .lazy_query() on Vec");
70    println!("   Query: products.lazy_query().where_(stock < 10).collect()");
71    
72    let low_stock: Vec<_> = products
73        .lazy_query()
74        .where_(Product::stock_r(), |&s| s < 10)
75        .collect();
76    
77    println!("   Found {} low stock products:", low_stock.len());
78    for product in &low_stock {
79        println!("   - {} (stock: {})", product.name, product.stock);
80    }
81    println!();
82
83    println!("3. Using Extension Trait - Chained Operations");
84    println!("   Query: products.lazy_query().where_(category == Electronics).take(2).select(name).collect()");
85    
86    let names: Vec<String> = products
87        .lazy_query()
88        .where_(Product::category_r(), |cat| cat == "Electronics")
89        .take_lazy(2)
90        .select_lazy(Product::name_r())
91        .collect();
92    
93    println!("   First 2 electronics:");
94    for name in &names {
95        println!("   - {}", name);
96    }
97    println!();
98
99    println!("4. Using QueryBuilder Derive - Static Methods");
100    println!("   Query: Product::query(&products).where_(price > 50).count()");
101    
102    let query4 = Product::query(&products)
103        .where_(Product::price_r(), |&p| p > 50.0);
104    let count = query4.count();
105    
106    println!("   Products over $50: {}", count);
107    println!();
108
109    println!("5. Using QueryBuilder Derive - Lazy Static Methods");
110    println!("   Query: Product::lazy_query(&products).first()");
111    
112    if let Some(first) = Product::lazy_query(&products).first() {
113        println!("   First product: {} (${:.2})", first.name, first.price);
114    }
115    println!();
116
117    println!("6. Complex Chain with Extension Trait");
118    println!("   Query: products.lazy_query()");
119    println!("          .where_(category == Electronics)");
120    println!("          .where_(price < 500)");
121    println!("          .map(|p| format!(\"{{}} - ${{:.2}}\", p.name, p.price))");
122    println!("          .collect()");
123    
124    let formatted: Vec<String> = products
125        .lazy_query()
126        .where_(Product::category_r(), |cat| cat == "Electronics")
127        .where_(Product::price_r(), |&p| p < 500.0)
128        .map_items(|p| format!("{} - ${:.2}", p.name, p.price))
129        .collect();
130    
131    println!("   Affordable electronics:");
132    for item in &formatted {
133        println!("   - {}", item);
134    }
135    println!();
136
137    println!("7. Aggregation with Extension Trait");
138    println!("   Query: products.lazy_query().sum_by(Product::stock())");
139    
140    let total_stock = products
141        .lazy_query()
142        .sum_by(Product::stock_r());
143    
144    println!("   Total stock across all products: {}", total_stock);
145    println!();
146
147    println!("8. Find with Extension Trait");
148    println!("   Query: products.lazy_query().find(|p| p.name.contains(\"Chair\"))");
149    
150    if let Some(chair) = products.lazy_query().find(|p| p.name.contains("Chair")) {
151        println!("   Found: {} in {}", chair.name, chair.category);
152    }
153    println!();
154
155    println!("9. Early Termination with Extension Trait");
156    println!("   Query: products.lazy_query().where_(price > 1000).any()");
157    
158    let has_luxury = products
159        .lazy_query()
160        .where_(Product::price_r(), |&p| p > 1000.0)
161        .any();
162    
163    println!("   Has products over $1000: {}", has_luxury);
164    println!();
165
166    println!("10. Slice Extension Trait");
167    println!("    Query: (&products[..]).lazy_query().count()");
168    
169    let slice_count = (&products[..])
170        .lazy_query()
171        .count();
172    
173    println!("    Count from slice: {}", slice_count);
174    println!();
175
176    println!("Summary:");
177    println!("--------");
178    println!("✓ Extension trait QueryExt adds .query() and .lazy_query() to containers");
179    println!("✓ Derive macro QueryBuilder adds static methods Product::query() and Product::lazy_query()");
180    println!("✓ Both approaches provide the same query functionality");
181    println!("✓ Extension trait is more ergonomic: products.query() vs Query::new(&products)");
182    println!("✓ All iterator optimizations (fusion, early termination) still apply");
183}
More examples
Hide additional examples
examples/container_support.rs (line 54)
26fn main() {
27    println!("\n╔════════════════════════════════════════════════════════════════╗");
28    println!("║  Container Support Demo                                       ║");
29    println!("║  Query various collection types                               ║");
30    println!("╚════════════════════════════════════════════════════════════════╝\n");
31
32    // ============================================================================
33    // CONTAINER 1: Vec<T>
34    // ============================================================================
35    println!("═══════════════════════════════════════════════════════════════");
36    println!("Container 1: Vec<T>");
37    println!("═══════════════════════════════════════════════════════════════\n");
38
39    let vec_products = vec![
40        create_sample_product(1, "Laptop", 999, "Electronics"),
41        create_sample_product(2, "Mouse", 29, "Electronics"),
42        create_sample_product(3, "Desk", 299, "Furniture"),
43    ];
44
45    // Query Vec directly
46    let vec_query = Query::new(&vec_products)
47        .where_(Product::category_r(), |cat| cat == "Electronics");
48    let vec_results = vec_query.all();
49    println!("  Vec: Found {} electronics", vec_results.len());
50
51    // Lazy query on Vec
52    let lazy_count = LazyQuery::new(&vec_products)
53        .where_(Product::price_r(), |&p| p < 100)
54        .count();
55    println!("  Vec (lazy): {} items under $100", lazy_count);
56
57    // ============================================================================
58    // CONTAINER 2: VecDeque<T>
59    // ============================================================================
60    println!("\n═══════════════════════════════════════════════════════════════");
61    println!("Container 2: VecDeque<T>");
62    println!("═══════════════════════════════════════════════════════════════\n");
63
64    let mut deque_products = VecDeque::new();
65    deque_products.push_back(create_sample_product(1, "Keyboard", 129, "Electronics"));
66    deque_products.push_back(create_sample_product(2, "Monitor", 349, "Electronics"));
67    deque_products.push_back(create_sample_product(3, "Chair", 199, "Furniture"));
68
69    // Convert to owned Vec for querying
70    let deque_vec: Vec<Product> = deque_products.iter().cloned().collect();
71    let deque_query = Query::new(&deque_vec);
72    let deque_count = deque_query.count();
73    println!("  VecDeque: {} total items", deque_count);
74
75    // More efficient: use make_contiguous for zero-copy slice access
76    let contiguous = deque_products.make_contiguous();
77    let contiguous_query = Query::new(contiguous);
78    println!("  VecDeque (zero-copy): {} items", contiguous_query.count());
79
80    // ============================================================================
81    // CONTAINER 3: HashSet<T>
82    // ============================================================================
83    println!("\n═══════════════════════════════════════════════════════════════");
84    println!("Container 3: HashSet<T>");
85    println!("═══════════════════════════════════════════════════════════════\n");
86
87    let mut set_products = HashSet::new();
88    set_products.insert(create_sample_product(1, "Tablet", 499, "Electronics"));
89    set_products.insert(create_sample_product(2, "Phone", 799, "Electronics"));
90    set_products.insert(create_sample_product(3, "Lamp", 39, "Furniture"));
91
92    // Collect from HashSet to Vec for querying
93    let set_vec: Vec<Product> = set_products.iter().cloned().collect();
94    let set_query = Query::new(&set_vec)
95        .where_(Product::price_r(), |&p| p > 500);
96    let expensive = set_query.all();
97    println!("  HashSet: {} expensive items", expensive.len());
98
99    // Lazy on HashSet (convert to owned Vec first)
100    let set_owned: Vec<Product> = set_products.iter().cloned().collect();
101    let lazy_set: Vec<_> = LazyQuery::new(&set_owned)
102        .where_(Product::category_r(), |cat| cat == "Electronics")
103        .collect();
104    println!("  HashSet (lazy): {} electronics", lazy_set.len());
105
106    // ============================================================================
107    // CONTAINER 4: BTreeSet<T>
108    // ============================================================================
109    println!("\n═══════════════════════════════════════════════════════════════");
110    println!("Container 4: BTreeSet<T>");
111    println!("═══════════════════════════════════════════════════════════════\n");
112
113    let mut btree_set = BTreeSet::new();
114    btree_set.insert(create_sample_product(1, "Webcam", 79, "Electronics"));
115    btree_set.insert(create_sample_product(2, "Microphone", 129, "Electronics"));
116    btree_set.insert(create_sample_product(3, "Bookshelf", 149, "Furniture"));
117
118    let btree_vec: Vec<Product> = btree_set.iter().cloned().collect();
119    let btree_query = Query::new(&btree_vec);
120    println!("  BTreeSet: {} total items (sorted order!)", btree_query.count());
121    
122    // BTreeSet items are in sorted order
123    for (i, item) in btree_vec.iter().take(3).enumerate() {
124        println!("    {}. {} (ID: {})", i + 1, item.name, item.id);
125    }
126
127    // ============================================================================
128    // CONTAINER 5: HashMap<K, V> - Query Values
129    // ============================================================================
130    println!("\n═══════════════════════════════════════════════════════════════");
131    println!("Container 5: HashMap<K, V> - Querying values");
132    println!("═══════════════════════════════════════════════════════════════\n");
133
134    let mut map_products = HashMap::new();
135    map_products.insert("prod1", create_sample_product(1, "Speaker", 199, "Electronics"));
136    map_products.insert("prod2", create_sample_product(2, "Headphones", 149, "Electronics"));
137    map_products.insert("prod3", create_sample_product(3, "Ottoman", 249, "Furniture"));
138
139    // Query HashMap values (convert to owned Vec)
140    let map_vec: Vec<Product> = map_products.values().cloned().collect();
141    let map_query = Query::new(&map_vec)
142        .where_(Product::category_r(), |cat| cat == "Electronics");
143    let electronics = map_query.all();
144    println!("  HashMap: {} electronics", electronics.len());
145
146    // ============================================================================
147    // CONTAINER 6: BTreeMap<K, V> - Query Values
148    // ============================================================================
149    println!("\n═══════════════════════════════════════════════════════════════");
150    println!("Container 6: BTreeMap<K, V> - Querying values");
151    println!("═══════════════════════════════════════════════════════════════\n");
152
153    let mut btree_map = BTreeMap::new();
154    btree_map.insert(1, create_sample_product(1, "Router", 89, "Electronics"));
155    btree_map.insert(2, create_sample_product(2, "Switch", 129, "Electronics"));
156    btree_map.insert(3, create_sample_product(3, "Sofa", 899, "Furniture"));
157
158    let btree_map_vec: Vec<Product> = btree_map.values().cloned().collect();
159    let btree_map_query = Query::new(&btree_map_vec);
160    let avg_price = btree_map_query.sum(Product::price_r()) as f64 / btree_map.len() as f64;
161    println!("  BTreeMap: Average price ${:.2}", avg_price);
162
163    // ============================================================================
164    // CONTAINER 7: Arrays [T; N]
165    // ============================================================================
166    println!("\n═══════════════════════════════════════════════════════════════");
167    println!("Container 7: Arrays [T; N]");
168    println!("═══════════════════════════════════════════════════════════════\n");
169
170    let array_products = [
171        create_sample_product(1, "USB Cable", 15, "Electronics"),
172        create_sample_product(2, "HDMI Cable", 25, "Electronics"),
173        create_sample_product(3, "Power Strip", 35, "Electronics"),
174    ];
175
176    // Query array directly (as slice)
177    let array_query = Query::new(&array_products);
178    let total = array_query.sum(Product::price_r());
179    println!("  Array: Total value ${}", total);
180
181    // Lazy on array
182    let lazy_array: Vec<_> = LazyQuery::new(&array_products)
183        .where_(Product::price_r(), |&p| p > 20)
184        .collect();
185    println!("  Array (lazy): {} items over $20", lazy_array.len());
186
187    // ============================================================================
188    // CONTAINER 8: LinkedList<T>
189    // ============================================================================
190    println!("\n═══════════════════════════════════════════════════════════════");
191    println!("Container 8: LinkedList<T>");
192    println!("═══════════════════════════════════════════════════════════════\n");
193
194    let mut list_products = LinkedList::new();
195    list_products.push_back(create_sample_product(1, "SSD", 159, "Electronics"));
196    list_products.push_back(create_sample_product(2, "HDD", 79, "Electronics"));
197
198    let list_vec: Vec<Product> = list_products.iter().cloned().collect();
199    let list_query = Query::new(&list_vec);
200    println!("  LinkedList: {} items", list_query.count());
201
202    // ============================================================================
203    // CONTAINER 9: Option<T> and Result<T, E>
204    // ============================================================================
205    println!("\n═══════════════════════════════════════════════════════════════");
206    println!("Container 9: Option<T> and Result<T, E>");
207    println!("═══════════════════════════════════════════════════════════════\n");
208
209    let maybe_product = Some(create_sample_product(1, "Mystery Box", 99, "Special"));
210    
211    if let Some(ref product) = maybe_product {
212        let option_query = Query::new(std::slice::from_ref(product));
213        println!("  Option (Some): {} items", option_query.count());
214    }
215
216    let none_product: Option<Product> = None;
217    let none_count = none_product.iter().count();
218    println!("  Option (None): {} items", none_count);
219
220    // ============================================================================
221    // Summary
222    // ============================================================================
223    println!("\n╔════════════════════════════════════════════════════════════════╗");
224    println!("║  Supported Containers Summary                                  ║");
225    println!("╚════════════════════════════════════════════════════════════════╝\n");
226
227    println!("✅ Supported container types:");
228    println!("   • Vec<T>              - Standard vector");
229    println!("   • &[T]                - Slices");
230    println!("   • [T; N]              - Fixed-size arrays");
231    println!("   • VecDeque<T>         - Double-ended queue");
232    println!("   • LinkedList<T>       - Doubly-linked list");
233    println!("   • HashSet<T>          - Unordered set");
234    println!("   • BTreeSet<T>         - Ordered set");
235    println!("   • HashMap<K, V>       - Query values");
236    println!("   • BTreeMap<K, V>      - Query values (sorted)");
237    println!("   • Option<T>           - 0 or 1 item");
238    println!("   • Result<T, E>        - 0 or 1 item\n");
239
240    println!("📝 Usage patterns:");
241    println!("   • Direct: Query::new(&container) for Vec, slices, arrays");
242    println!("   • Convert: Collect to Vec for Sets and Maps");
243    println!("   • Lazy: LazyQuery::new(&slice) for any slice\n");
244
245    println!("💡 Tips:");
246    println!("   • Vec/slice: Direct support, most efficient");
247    println!("   • Sets: Iterate to Vec, then query");
248    println!("   • Maps: Use .values().collect() to query values");
249    println!("   • VecDeque: Use .as_slices() for zero-copy");
250    println!("   • For custom types: Implement Queryable trait\n");
251
252    println!("✓ Container support demo complete!\n");
253}
examples/arc_rwlock_hashmap.rs (line 194)
59fn main() {
60    println!("\n╔══════════════════════════════════════════════════════════════════╗");
61    println!("║  Arc<RwLock<T>> HashMap Lazy Query Demo                         ║");
62    println!("║  Thread-safe shared data with lazy evaluation                   ║");
63    println!("╚══════════════════════════════════════════════════════════════════╝\n");
64
65    let product_map = create_sample_data();
66    println!("Created product catalog:");
67    println!("  Total products: {}", product_map.len());
68    println!("  Keys: {:?}\n", product_map.keys().take(3).collect::<Vec<_>>());
69
70    // Extract products for querying
71    let products = extract_products(&product_map);
72    println!("Extracted {} products from Arc<RwLock<Product>>\n", products.len());
73
74    // ============================================================================
75    // LAZY OPERATION 1: where_ - Lazy Filtering
76    // ============================================================================
77    println!("═══════════════════════════════════════════════════════════════");
78    println!("Lazy Operation 1: where_ (filtering)");
79    println!("═══════════════════════════════════════════════════════════════\n");
80
81    println!("Building filtered query (nothing executes yet)...");
82    let electronics_query = LazyQuery::new(&products)
83        .where_(Product::category_r(), |cat| cat == "Electronics")
84        .where_(Product::active_r(), |&active| active)
85        .where_(Product::stock_r(), |&stock| stock > 20);
86
87    println!("  ✅ Query built (deferred execution)\n");
88
89    println!("Collecting results (executes now)...");
90    let electronics: Vec<_> = electronics_query.collect();
91    println!("  Found {} electronics in stock", electronics.len());
92    for p in &electronics {
93        println!("    • {}: {} in stock", p.name, p.stock);
94    }
95
96    // ============================================================================
97    // LAZY OPERATION 2: select_lazy - Lazy Projection
98    // ============================================================================
99    println!("\n═══════════════════════════════════════════════════════════════");
100    println!("Lazy Operation 2: select_lazy (projection)");
101    println!("═══════════════════════════════════════════════════════════════\n");
102
103    println!("Selecting product names (lazy)...");
104    let names: Vec<String> = LazyQuery::new(&products)
105        .where_(Product::category_r(), |cat| cat == "Furniture")
106        .select_lazy(Product::name_r())
107        .collect();
108
109    println!("  Furniture names ({}):", names.len());
110    for name in &names {
111        println!("    • {}", name);
112    }
113
114    // ============================================================================
115    // LAZY OPERATION 3: take_lazy - Early Termination
116    // ============================================================================
117    println!("\n═══════════════════════════════════════════════════════════════");
118    println!("Lazy Operation 3: take_lazy (early termination)");
119    println!("═══════════════════════════════════════════════════════════════\n");
120
121    println!("Getting first 3 electronics...");
122    let first_3: Vec<_> = LazyQuery::new(&products)
123        .where_(Product::category_r(), |cat| cat == "Electronics")
124        .take_lazy(3)
125        .collect();
126
127    println!("  First 3 electronics:");
128    for (i, p) in first_3.iter().enumerate() {
129        println!("    {}. {} - ${:.2}", i + 1, p.name, p.price);
130    }
131    println!("  ✅ Stopped after finding 3 items!");
132
133    // ============================================================================
134    // LAZY OPERATION 4: skip_lazy - Pagination
135    // ============================================================================
136    println!("\n═══════════════════════════════════════════════════════════════");
137    println!("Lazy Operation 4: skip_lazy (pagination)");
138    println!("═══════════════════════════════════════════════════════════════\n");
139
140    println!("Getting page 2 (skip 3, take 3)...");
141    let page_2: Vec<_> = LazyQuery::new(&products)
142        .where_(Product::active_r(), |&active| active)
143        .skip_lazy(3)
144        .take_lazy(3)
145        .collect();
146
147    println!("  Page 2 items:");
148    for (i, p) in page_2.iter().enumerate() {
149        println!("    {}. {}", i + 4, p.name);
150    }
151
152    // ============================================================================
153    // LAZY OPERATION 5: first - Short-Circuit Search
154    // ============================================================================
155    println!("\n═══════════════════════════════════════════════════════════════");
156    println!("Lazy Operation 5: first (short-circuit)");
157    println!("═══════════════════════════════════════════════════════════════\n");
158
159    println!("Finding first expensive item (>$1000)...");
160    let expensive = LazyQuery::new(&products)
161        .where_(Product::price_r(), |&price| price > 1000.0)
162        .first();
163
164    match expensive {
165        Some(p) => println!("  Found: {} - ${:.2}", p.name, p.price),
166        None => println!("  Not found"),
167    }
168    println!("  ✅ Stopped at first match!");
169
170    // ============================================================================
171    // LAZY OPERATION 6: any - Existence Check
172    // ============================================================================
173    println!("\n═══════════════════════════════════════════════════════════════");
174    println!("Lazy Operation 6: any (existence check)");
175    println!("═══════════════════════════════════════════════════════════════\n");
176
177    println!("Checking if any furniture exists...");
178    let has_furniture = LazyQuery::new(&products)
179        .where_(Product::category_r(), |cat| cat == "Furniture")
180        .any();
181
182    println!("  Has furniture: {}", has_furniture);
183    println!("  ✅ Stopped immediately after finding first match!");
184
185    // ============================================================================
186    // LAZY OPERATION 7: count - Count Matching Items
187    // ============================================================================
188    println!("\n═══════════════════════════════════════════════════════════════");
189    println!("Lazy Operation 7: count");
190    println!("═══════════════════════════════════════════════════════════════\n");
191
192    let electronics_count = LazyQuery::new(&products)
193        .where_(Product::category_r(), |cat| cat == "Electronics")
194        .count();
195
196    println!("  Electronics count: {}", electronics_count);
197
198    // ============================================================================
199    // LAZY OPERATION 8: sum_by - Aggregation
200    // ============================================================================
201    println!("\n═══════════════════════════════════════════════════════════════");
202    println!("Lazy Operation 8: sum_by (aggregation)");
203    println!("═══════════════════════════════════════════════════════════════\n");
204
205    let total_value: f64 = LazyQuery::new(&products)
206        .where_(Product::category_r(), |cat| cat == "Electronics")
207        .sum_by(Product::price_r());
208
209    println!("  Total electronics value: ${:.2}", total_value);
210
211    // ============================================================================
212    // LAZY OPERATION 9: avg_by - Average
213    // ============================================================================
214    println!("\n═══════════════════════════════════════════════════════════════");
215    println!("Lazy Operation 9: avg_by");
216    println!("═══════════════════════════════════════════════════════════════\n");
217
218    let avg_price = LazyQuery::new(&products)
219        .where_(Product::category_r(), |cat| cat == "Furniture")
220        .avg_by(Product::price_r())
221        .unwrap_or(0.0);
222
223    println!("  Average furniture price: ${:.2}", avg_price);
224
225    // ============================================================================
226    // LAZY OPERATION 10: min_by_float / max_by_float
227    // ============================================================================
228    println!("\n═══════════════════════════════════════════════════════════════");
229    println!("Lazy Operation 10: min_by_float / max_by_float");
230    println!("═══════════════════════════════════════════════════════════════\n");
231
232    let min_price = LazyQuery::new(&products)
233        .where_(Product::active_r(), |&active| active)
234        .min_by_float(Product::price_r())
235        .unwrap_or(0.0);
236
237    let max_price = LazyQuery::new(&products)
238        .where_(Product::active_r(), |&active| active)
239        .max_by_float(Product::price_r())
240        .unwrap_or(0.0);
241
242    println!("  Price range for active products:");
243    println!("    Min: ${:.2}", min_price);
244    println!("    Max: ${:.2}", max_price);
245
246    // ============================================================================
247    // LAZY OPERATION 11: find - Find with Predicate
248    // ============================================================================
249    println!("\n═══════════════════════════════════════════════════════════════");
250    println!("Lazy Operation 11: find (with predicate)");
251    println!("═══════════════════════════════════════════════════════════════\n");
252
253    let high_rated = LazyQuery::new(&products)
254        .where_(Product::category_r(), |cat| cat == "Electronics")
255        .find(|item| item.rating > 4.7);
256
257    if let Some(product) = high_rated {
258        println!("  First highly-rated electronic:");
259        println!("    {}: Rating {:.1}", product.name, product.rating);
260    }
261
262    // ============================================================================
263    // LAZY OPERATION 12: for_each - Iteration
264    // ============================================================================
265    println!("\n═══════════════════════════════════════════════════════════════");
266    println!("Lazy Operation 12: for_each (iteration)");
267    println!("═══════════════════════════════════════════════════════════════\n");
268
269    println!("  Low stock alerts:");
270    LazyQuery::new(&products)
271        .where_(Product::stock_r(), |&stock| stock < 20)
272        .for_each(|product| {
273            println!("    ⚠️  {}: Only {} in stock", product.name, product.stock);
274        });
275
276    // ============================================================================
277    // LAZY OPERATION 13: fold - Custom Aggregation
278    // ============================================================================
279    println!("\n═══════════════════════════════════════════════════════════════");
280    println!("Lazy Operation 14: fold (custom aggregation)");
281    println!("═══════════════════════════════════════════════════════════════\n");
282
283    let total_inventory_value = LazyQuery::new(&products)
284        .where_(Product::active_r(), |&active| active)
285        .fold(0.0, |acc, product| {
286            acc + (product.price * product.stock as f64)
287        });
288
289    println!("  Total inventory value: ${:.2}", total_inventory_value);
290
291    // ============================================================================
292    // LAZY OPERATION 14: all_match - Validation
293    // ============================================================================
294    println!("\n═══════════════════════════════════════════════════════════════");
295    println!("Lazy Operation 15: all_match (validation)");
296    println!("═══════════════════════════════════════════════════════════════\n");
297
298    let all_priced = LazyQuery::new(&products)
299        .all_match(|item| item.price > 0.0);
300
301    println!("  All products have valid prices: {}", all_priced);
302
303    // ============================================================================
304    // LAZY OPERATION 15: into_iter - For Loop
305    // ============================================================================
306    println!("\n═══════════════════════════════════════════════════════════════");
307    println!("Lazy Operation 16: into_iter (for loop)");
308    println!("═══════════════════════════════════════════════════════════════\n");
309
310    println!("  High-value products (>$300):");
311    for product in LazyQuery::new(&products)
312        .where_(Product::price_r(), |&p| p > 300.0)
313        .take_lazy(5)
314    {
315        println!("    • {}: ${:.2}", product.name, product.price);
316    }
317
318    // ============================================================================
319    // LAZY OPERATION 16: map_items - Transform
320    // ============================================================================
321    println!("\n═══════════════════════════════════════════════════════════════");
322    println!("Lazy Operation 17: map_items (transformation)");
323    println!("═══════════════════════════════════════════════════════════════\n");
324
325    let price_tags: Vec<String> = LazyQuery::new(&products)
326        .where_(Product::category_r(), |cat| cat == "Electronics")
327        .map_items(|p| format!("{}: ${:.2}", p.name, p.price))
328        .take(5)
329        .collect();
330
331    println!("  Electronics price tags:");
332    for tag in &price_tags {
333        println!("    • {}", tag);
334    }
335
336    // ============================================================================
337    // COMPLEX EXAMPLE: Multi-Stage Lazy Pipeline
338    // ============================================================================
339    println!("\n═══════════════════════════════════════════════════════════════");
340    println!("Complex Example: Multi-stage lazy pipeline");
341    println!("═══════════════════════════════════════════════════════════════\n");
342
343    println!("Building complex query:");
344    println!("  1. Filter by category (Electronics)");
345    println!("  2. Filter by price range ($50-$500)");
346    println!("  3. Filter by rating (>4.5)");
347    println!("  4. Select names");
348    println!("  5. Take first 3");
349    println!();
350
351    let results: Vec<String> = LazyQuery::new(&products)
352        .where_(Product::category_r(), |cat| cat == "Electronics")
353        .where_(Product::price_r(), |&p| p >= 50.0 && p <= 500.0)
354        .where_(Product::rating_r(), |&r| r > 4.5)
355        .select_lazy(Product::name_r())
356        .take(3)
357        .collect();
358
359    println!("  Results:");
360    for (i, name) in results.iter().enumerate() {
361        println!("    {}. {}", i + 1, name);
362    }
363    println!("  ✅ All operations fused and executed lazily!");
364
365    // ============================================================================
366    // THREAD-SAFE UPDATES WITH RWLOCK
367    // ============================================================================
368    println!("\n═══════════════════════════════════════════════════════════════");
369    println!("Bonus: Thread-safe updates with RwLock");
370    println!("═══════════════════════════════════════════════════════════════\n");
371
372    // Update a product through the Arc<RwLock>
373    if let Some(product_arc) = product_map.get("PROD-002") {
374        println!("Updating PROD-002 stock...");
375        
376        // Write lock for mutation
377        if let Ok(mut product) = product_arc.write() {
378            let old_stock = product.stock;
379            product.stock = 25;
380            println!("  Stock updated: {} → {}", old_stock, product.stock);
381        }
382    }
383
384    // Query again to see the update
385    let updated_products = extract_products(&product_map);
386    let mouse = LazyQuery::new(&updated_products)
387        .find(|p| p.id == 2);
388
389    if let Some(product) = mouse {
390        println!("  Verified update: {} now has {} in stock", product.name, product.stock);
391    }
392
393    // ============================================================================
394    // PRACTICAL EXAMPLE: Price Analysis by Category
395    // ============================================================================
396    println!("\n═══════════════════════════════════════════════════════════════");
397    println!("Practical Example: Price analysis by category");
398    println!("═══════════════════════════════════════════════════════════════\n");
399
400    let categories = vec!["Electronics", "Furniture"];
401
402    for category in categories {
403        println!("  {} Statistics:", category);
404        
405        // Filter products by category first
406        let cat_products: Vec<Product> = products.iter()
407            .filter(|p| p.category == category)
408            .cloned()
409            .collect();
410
411        let count = LazyQuery::new(&cat_products).count();
412        let total = LazyQuery::new(&cat_products).sum_by(Product::price_r());
413        let avg = LazyQuery::new(&cat_products).avg_by(Product::price_r()).unwrap_or(0.0);
414        let min = LazyQuery::new(&cat_products).min_by_float(Product::price_r()).unwrap_or(0.0);
415        let max = LazyQuery::new(&cat_products).max_by_float(Product::price_r()).unwrap_or(0.0);
416
417        println!("    Count: {}", count);
418        println!("    Total: ${:.2}", total);
419        println!("    Average: ${:.2}", avg);
420        println!("    Range: ${:.2} - ${:.2}\n", min, max);
421    }
422
423    // ============================================================================
424    // COMBINING WITH HASHMAP OPERATIONS
425    // ============================================================================
426    println!("═══════════════════════════════════════════════════════════════");
427    println!("HashMap Integration: Query by key patterns");
428    println!("═══════════════════════════════════════════════════════════════\n");
429
430    // Filter HashMap by key pattern
431    let electronics_keys: Vec<String> = product_map
432        .iter()
433        .filter(|(_key, value)| {
434            // Read the value to check category
435            if let Ok(guard) = value.read() {
436                guard.category == "Electronics"
437            } else {
438                false
439            }
440        })
441        .map(|(key, _value)| key.clone())
442        .collect();
443
444    println!("  Electronics product IDs:");
445    for key in electronics_keys.iter().take(5) {
446        println!("    • {}", key);
447    }
448
449    // ============================================================================
450    // PERFORMANCE DEMONSTRATION
451    // ============================================================================
452    println!("\n═══════════════════════════════════════════════════════════════");
453    println!("Performance: Lazy vs Eager comparison");
454    println!("═══════════════════════════════════════════════════════════════\n");
455
456    println!("Scenario: Find first product with rating > 4.7 from {} products\n", products.len());
457
458    println!("  Eager approach (hypothetical):");
459    println!("    - Filter all {} products", products.len());
460    println!("    - Collect filtered results");
461    println!("    - Take first item");
462    println!("    - Wasted work: Check all items\n");
463
464    println!("  Lazy approach (actual):");
465    let _first_rated = LazyQuery::new(&products)
466        .where_(Product::rating_r(), |&r| r > 4.7)
467        .first();
468    println!("    - Starts checking products");
469    println!("    - Stops at first match");
470    println!("    - ✅ Early termination - checks ~3-5 items only!");
471
472    // ============================================================================
473    // Summary
474    // ============================================================================
475    println!("\n╔══════════════════════════════════════════════════════════════════╗");
476    println!("║  Summary: All Lazy Operations Demonstrated                      ║");
477    println!("╚══════════════════════════════════════════════════════════════════╝\n");
478
479    println!("✅ Lazy Query Operations:");
480    println!("   1. ✅ where_ - Lazy filtering");
481    println!("   2. ✅ select_lazy - Lazy projection");
482    println!("   3. ✅ take_lazy - Early termination");
483    println!("   4. ✅ skip_lazy - Pagination");
484    println!("   5. ✅ first - Short-circuit search");
485    println!("   6. ✅ any - Existence check (short-circuit)");
486    println!("   7. ✅ count - Count items");
487    println!("   8. ✅ sum_by - Sum aggregation");
488    println!("   9. ✅ avg_by - Average aggregation");
489    println!("   10. ✅ min_by_float - Minimum value");
490    println!("   11. ✅ max_by_float - Maximum value");
491    println!("   12. ✅ find - Find with predicate (short-circuit)");
492    println!("   13. ✅ for_each - Iteration");
493    println!("   14. ✅ fold - Custom aggregation");
494    println!("   15. ✅ all_match - Validation (short-circuit)");
495    println!("   16. ✅ into_iter - For loop support");
496    println!("   17. ✅ map_items - Transformation\n");
497
498    println!("✅ Arc<RwLock<T>> Benefits:");
499    println!("   • Thread-safe shared access");
500    println!("   • Interior mutability");
501    println!("   • Multiple readers, single writer");
502    println!("   • Reference counting (Arc)");
503    println!("   • Can be queried after extracting data\n");
504
505    println!("✅ HashMap<K, Arc<RwLock<V>>> Benefits:");
506    println!("   • Fast key-based lookup");
507    println!("   • Thread-safe value access");
508    println!("   • Can query all values");
509    println!("   • Can filter by key patterns");
510    println!("   • Perfect for shared state/caches\n");
511
512    println!("🎯 Use Cases:");
513    println!("   • Shared product catalogs");
514    println!("   • User session stores");
515    println!("   • Configuration caches");
516    println!("   • Real-time inventory systems");
517    println!("   • Multi-threaded data processing");
518    println!("   • Web server state management\n");
519
520    println!("✓ Arc<RwLock<T>> HashMap with all lazy operations demo complete!\n");
521}
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/derive_and_ext.rs (line 161)
13fn main() {
14    println!("Derive Macros and Extension Traits Example");
15    println!("===========================================\n");
16
17    let products = vec![
18        Product {
19            id: 1,
20            name: "Laptop".to_string(),
21            price: 999.99,
22            category: "Electronics".to_string(),
23            stock: 5,
24        },
25        Product {
26            id: 2,
27            name: "Mouse".to_string(),
28            price: 29.99,
29            category: "Electronics".to_string(),
30            stock: 50,
31        },
32        Product {
33            id: 3,
34            name: "Keyboard".to_string(),
35            price: 79.99,
36            category: "Electronics".to_string(),
37            stock: 30,
38        },
39        Product {
40            id: 4,
41            name: "Monitor".to_string(),
42            price: 299.99,
43            category: "Electronics".to_string(),
44            stock: 12,
45        },
46        Product {
47            id: 5,
48            name: "Desk Chair".to_string(),
49            price: 199.99,
50            category: "Furniture".to_string(),
51            stock: 8,
52        },
53    ];
54
55    println!("1. Using Extension Trait - Direct .query() on Vec");
56    println!("   Query: products.query().where_(price > 100).all()");
57    
58    let query = products
59        .query()
60        .where_(Product::price_r(), |&p| p > 100.0);
61    let expensive = query.all();
62    
63    println!("   Found {} expensive products:", expensive.len());
64    for product in &expensive {
65        println!("   - {} (${:.2})", product.name, product.price);
66    }
67    println!();
68
69    println!("2. Using Extension Trait - Direct .lazy_query() on Vec");
70    println!("   Query: products.lazy_query().where_(stock < 10).collect()");
71    
72    let low_stock: Vec<_> = products
73        .lazy_query()
74        .where_(Product::stock_r(), |&s| s < 10)
75        .collect();
76    
77    println!("   Found {} low stock products:", low_stock.len());
78    for product in &low_stock {
79        println!("   - {} (stock: {})", product.name, product.stock);
80    }
81    println!();
82
83    println!("3. Using Extension Trait - Chained Operations");
84    println!("   Query: products.lazy_query().where_(category == Electronics).take(2).select(name).collect()");
85    
86    let names: Vec<String> = products
87        .lazy_query()
88        .where_(Product::category_r(), |cat| cat == "Electronics")
89        .take_lazy(2)
90        .select_lazy(Product::name_r())
91        .collect();
92    
93    println!("   First 2 electronics:");
94    for name in &names {
95        println!("   - {}", name);
96    }
97    println!();
98
99    println!("4. Using QueryBuilder Derive - Static Methods");
100    println!("   Query: Product::query(&products).where_(price > 50).count()");
101    
102    let query4 = Product::query(&products)
103        .where_(Product::price_r(), |&p| p > 50.0);
104    let count = query4.count();
105    
106    println!("   Products over $50: {}", count);
107    println!();
108
109    println!("5. Using QueryBuilder Derive - Lazy Static Methods");
110    println!("   Query: Product::lazy_query(&products).first()");
111    
112    if let Some(first) = Product::lazy_query(&products).first() {
113        println!("   First product: {} (${:.2})", first.name, first.price);
114    }
115    println!();
116
117    println!("6. Complex Chain with Extension Trait");
118    println!("   Query: products.lazy_query()");
119    println!("          .where_(category == Electronics)");
120    println!("          .where_(price < 500)");
121    println!("          .map(|p| format!(\"{{}} - ${{:.2}}\", p.name, p.price))");
122    println!("          .collect()");
123    
124    let formatted: Vec<String> = products
125        .lazy_query()
126        .where_(Product::category_r(), |cat| cat == "Electronics")
127        .where_(Product::price_r(), |&p| p < 500.0)
128        .map_items(|p| format!("{} - ${:.2}", p.name, p.price))
129        .collect();
130    
131    println!("   Affordable electronics:");
132    for item in &formatted {
133        println!("   - {}", item);
134    }
135    println!();
136
137    println!("7. Aggregation with Extension Trait");
138    println!("   Query: products.lazy_query().sum_by(Product::stock())");
139    
140    let total_stock = products
141        .lazy_query()
142        .sum_by(Product::stock_r());
143    
144    println!("   Total stock across all products: {}", total_stock);
145    println!();
146
147    println!("8. Find with Extension Trait");
148    println!("   Query: products.lazy_query().find(|p| p.name.contains(\"Chair\"))");
149    
150    if let Some(chair) = products.lazy_query().find(|p| p.name.contains("Chair")) {
151        println!("   Found: {} in {}", chair.name, chair.category);
152    }
153    println!();
154
155    println!("9. Early Termination with Extension Trait");
156    println!("   Query: products.lazy_query().where_(price > 1000).any()");
157    
158    let has_luxury = products
159        .lazy_query()
160        .where_(Product::price_r(), |&p| p > 1000.0)
161        .any();
162    
163    println!("   Has products over $1000: {}", has_luxury);
164    println!();
165
166    println!("10. Slice Extension Trait");
167    println!("    Query: (&products[..]).lazy_query().count()");
168    
169    let slice_count = (&products[..])
170        .lazy_query()
171        .count();
172    
173    println!("    Count from slice: {}", slice_count);
174    println!();
175
176    println!("Summary:");
177    println!("--------");
178    println!("✓ Extension trait QueryExt adds .query() and .lazy_query() to containers");
179    println!("✓ Derive macro QueryBuilder adds static methods Product::query() and Product::lazy_query()");
180    println!("✓ Both approaches provide the same query functionality");
181    println!("✓ Extension trait is more ergonomic: products.query() vs Query::new(&products)");
182    println!("✓ All iterator optimizations (fusion, early termination) still apply");
183}
More examples
Hide additional examples
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}
examples/arc_rwlock_hashmap.rs (line 180)
59fn main() {
60    println!("\n╔══════════════════════════════════════════════════════════════════╗");
61    println!("║  Arc<RwLock<T>> HashMap Lazy Query Demo                         ║");
62    println!("║  Thread-safe shared data with lazy evaluation                   ║");
63    println!("╚══════════════════════════════════════════════════════════════════╝\n");
64
65    let product_map = create_sample_data();
66    println!("Created product catalog:");
67    println!("  Total products: {}", product_map.len());
68    println!("  Keys: {:?}\n", product_map.keys().take(3).collect::<Vec<_>>());
69
70    // Extract products for querying
71    let products = extract_products(&product_map);
72    println!("Extracted {} products from Arc<RwLock<Product>>\n", products.len());
73
74    // ============================================================================
75    // LAZY OPERATION 1: where_ - Lazy Filtering
76    // ============================================================================
77    println!("═══════════════════════════════════════════════════════════════");
78    println!("Lazy Operation 1: where_ (filtering)");
79    println!("═══════════════════════════════════════════════════════════════\n");
80
81    println!("Building filtered query (nothing executes yet)...");
82    let electronics_query = LazyQuery::new(&products)
83        .where_(Product::category_r(), |cat| cat == "Electronics")
84        .where_(Product::active_r(), |&active| active)
85        .where_(Product::stock_r(), |&stock| stock > 20);
86
87    println!("  ✅ Query built (deferred execution)\n");
88
89    println!("Collecting results (executes now)...");
90    let electronics: Vec<_> = electronics_query.collect();
91    println!("  Found {} electronics in stock", electronics.len());
92    for p in &electronics {
93        println!("    • {}: {} in stock", p.name, p.stock);
94    }
95
96    // ============================================================================
97    // LAZY OPERATION 2: select_lazy - Lazy Projection
98    // ============================================================================
99    println!("\n═══════════════════════════════════════════════════════════════");
100    println!("Lazy Operation 2: select_lazy (projection)");
101    println!("═══════════════════════════════════════════════════════════════\n");
102
103    println!("Selecting product names (lazy)...");
104    let names: Vec<String> = LazyQuery::new(&products)
105        .where_(Product::category_r(), |cat| cat == "Furniture")
106        .select_lazy(Product::name_r())
107        .collect();
108
109    println!("  Furniture names ({}):", names.len());
110    for name in &names {
111        println!("    • {}", name);
112    }
113
114    // ============================================================================
115    // LAZY OPERATION 3: take_lazy - Early Termination
116    // ============================================================================
117    println!("\n═══════════════════════════════════════════════════════════════");
118    println!("Lazy Operation 3: take_lazy (early termination)");
119    println!("═══════════════════════════════════════════════════════════════\n");
120
121    println!("Getting first 3 electronics...");
122    let first_3: Vec<_> = LazyQuery::new(&products)
123        .where_(Product::category_r(), |cat| cat == "Electronics")
124        .take_lazy(3)
125        .collect();
126
127    println!("  First 3 electronics:");
128    for (i, p) in first_3.iter().enumerate() {
129        println!("    {}. {} - ${:.2}", i + 1, p.name, p.price);
130    }
131    println!("  ✅ Stopped after finding 3 items!");
132
133    // ============================================================================
134    // LAZY OPERATION 4: skip_lazy - Pagination
135    // ============================================================================
136    println!("\n═══════════════════════════════════════════════════════════════");
137    println!("Lazy Operation 4: skip_lazy (pagination)");
138    println!("═══════════════════════════════════════════════════════════════\n");
139
140    println!("Getting page 2 (skip 3, take 3)...");
141    let page_2: Vec<_> = LazyQuery::new(&products)
142        .where_(Product::active_r(), |&active| active)
143        .skip_lazy(3)
144        .take_lazy(3)
145        .collect();
146
147    println!("  Page 2 items:");
148    for (i, p) in page_2.iter().enumerate() {
149        println!("    {}. {}", i + 4, p.name);
150    }
151
152    // ============================================================================
153    // LAZY OPERATION 5: first - Short-Circuit Search
154    // ============================================================================
155    println!("\n═══════════════════════════════════════════════════════════════");
156    println!("Lazy Operation 5: first (short-circuit)");
157    println!("═══════════════════════════════════════════════════════════════\n");
158
159    println!("Finding first expensive item (>$1000)...");
160    let expensive = LazyQuery::new(&products)
161        .where_(Product::price_r(), |&price| price > 1000.0)
162        .first();
163
164    match expensive {
165        Some(p) => println!("  Found: {} - ${:.2}", p.name, p.price),
166        None => println!("  Not found"),
167    }
168    println!("  ✅ Stopped at first match!");
169
170    // ============================================================================
171    // LAZY OPERATION 6: any - Existence Check
172    // ============================================================================
173    println!("\n═══════════════════════════════════════════════════════════════");
174    println!("Lazy Operation 6: any (existence check)");
175    println!("═══════════════════════════════════════════════════════════════\n");
176
177    println!("Checking if any furniture exists...");
178    let has_furniture = LazyQuery::new(&products)
179        .where_(Product::category_r(), |cat| cat == "Furniture")
180        .any();
181
182    println!("  Has furniture: {}", has_furniture);
183    println!("  ✅ Stopped immediately after finding first match!");
184
185    // ============================================================================
186    // LAZY OPERATION 7: count - Count Matching Items
187    // ============================================================================
188    println!("\n═══════════════════════════════════════════════════════════════");
189    println!("Lazy Operation 7: count");
190    println!("═══════════════════════════════════════════════════════════════\n");
191
192    let electronics_count = LazyQuery::new(&products)
193        .where_(Product::category_r(), |cat| cat == "Electronics")
194        .count();
195
196    println!("  Electronics count: {}", electronics_count);
197
198    // ============================================================================
199    // LAZY OPERATION 8: sum_by - Aggregation
200    // ============================================================================
201    println!("\n═══════════════════════════════════════════════════════════════");
202    println!("Lazy Operation 8: sum_by (aggregation)");
203    println!("═══════════════════════════════════════════════════════════════\n");
204
205    let total_value: f64 = LazyQuery::new(&products)
206        .where_(Product::category_r(), |cat| cat == "Electronics")
207        .sum_by(Product::price_r());
208
209    println!("  Total electronics value: ${:.2}", total_value);
210
211    // ============================================================================
212    // LAZY OPERATION 9: avg_by - Average
213    // ============================================================================
214    println!("\n═══════════════════════════════════════════════════════════════");
215    println!("Lazy Operation 9: avg_by");
216    println!("═══════════════════════════════════════════════════════════════\n");
217
218    let avg_price = LazyQuery::new(&products)
219        .where_(Product::category_r(), |cat| cat == "Furniture")
220        .avg_by(Product::price_r())
221        .unwrap_or(0.0);
222
223    println!("  Average furniture price: ${:.2}", avg_price);
224
225    // ============================================================================
226    // LAZY OPERATION 10: min_by_float / max_by_float
227    // ============================================================================
228    println!("\n═══════════════════════════════════════════════════════════════");
229    println!("Lazy Operation 10: min_by_float / max_by_float");
230    println!("═══════════════════════════════════════════════════════════════\n");
231
232    let min_price = LazyQuery::new(&products)
233        .where_(Product::active_r(), |&active| active)
234        .min_by_float(Product::price_r())
235        .unwrap_or(0.0);
236
237    let max_price = LazyQuery::new(&products)
238        .where_(Product::active_r(), |&active| active)
239        .max_by_float(Product::price_r())
240        .unwrap_or(0.0);
241
242    println!("  Price range for active products:");
243    println!("    Min: ${:.2}", min_price);
244    println!("    Max: ${:.2}", max_price);
245
246    // ============================================================================
247    // LAZY OPERATION 11: find - Find with Predicate
248    // ============================================================================
249    println!("\n═══════════════════════════════════════════════════════════════");
250    println!("Lazy Operation 11: find (with predicate)");
251    println!("═══════════════════════════════════════════════════════════════\n");
252
253    let high_rated = LazyQuery::new(&products)
254        .where_(Product::category_r(), |cat| cat == "Electronics")
255        .find(|item| item.rating > 4.7);
256
257    if let Some(product) = high_rated {
258        println!("  First highly-rated electronic:");
259        println!("    {}: Rating {:.1}", product.name, product.rating);
260    }
261
262    // ============================================================================
263    // LAZY OPERATION 12: for_each - Iteration
264    // ============================================================================
265    println!("\n═══════════════════════════════════════════════════════════════");
266    println!("Lazy Operation 12: for_each (iteration)");
267    println!("═══════════════════════════════════════════════════════════════\n");
268
269    println!("  Low stock alerts:");
270    LazyQuery::new(&products)
271        .where_(Product::stock_r(), |&stock| stock < 20)
272        .for_each(|product| {
273            println!("    ⚠️  {}: Only {} in stock", product.name, product.stock);
274        });
275
276    // ============================================================================
277    // LAZY OPERATION 13: fold - Custom Aggregation
278    // ============================================================================
279    println!("\n═══════════════════════════════════════════════════════════════");
280    println!("Lazy Operation 14: fold (custom aggregation)");
281    println!("═══════════════════════════════════════════════════════════════\n");
282
283    let total_inventory_value = LazyQuery::new(&products)
284        .where_(Product::active_r(), |&active| active)
285        .fold(0.0, |acc, product| {
286            acc + (product.price * product.stock as f64)
287        });
288
289    println!("  Total inventory value: ${:.2}", total_inventory_value);
290
291    // ============================================================================
292    // LAZY OPERATION 14: all_match - Validation
293    // ============================================================================
294    println!("\n═══════════════════════════════════════════════════════════════");
295    println!("Lazy Operation 15: all_match (validation)");
296    println!("═══════════════════════════════════════════════════════════════\n");
297
298    let all_priced = LazyQuery::new(&products)
299        .all_match(|item| item.price > 0.0);
300
301    println!("  All products have valid prices: {}", all_priced);
302
303    // ============================================================================
304    // LAZY OPERATION 15: into_iter - For Loop
305    // ============================================================================
306    println!("\n═══════════════════════════════════════════════════════════════");
307    println!("Lazy Operation 16: into_iter (for loop)");
308    println!("═══════════════════════════════════════════════════════════════\n");
309
310    println!("  High-value products (>$300):");
311    for product in LazyQuery::new(&products)
312        .where_(Product::price_r(), |&p| p > 300.0)
313        .take_lazy(5)
314    {
315        println!("    • {}: ${:.2}", product.name, product.price);
316    }
317
318    // ============================================================================
319    // LAZY OPERATION 16: map_items - Transform
320    // ============================================================================
321    println!("\n═══════════════════════════════════════════════════════════════");
322    println!("Lazy Operation 17: map_items (transformation)");
323    println!("═══════════════════════════════════════════════════════════════\n");
324
325    let price_tags: Vec<String> = LazyQuery::new(&products)
326        .where_(Product::category_r(), |cat| cat == "Electronics")
327        .map_items(|p| format!("{}: ${:.2}", p.name, p.price))
328        .take(5)
329        .collect();
330
331    println!("  Electronics price tags:");
332    for tag in &price_tags {
333        println!("    • {}", tag);
334    }
335
336    // ============================================================================
337    // COMPLEX EXAMPLE: Multi-Stage Lazy Pipeline
338    // ============================================================================
339    println!("\n═══════════════════════════════════════════════════════════════");
340    println!("Complex Example: Multi-stage lazy pipeline");
341    println!("═══════════════════════════════════════════════════════════════\n");
342
343    println!("Building complex query:");
344    println!("  1. Filter by category (Electronics)");
345    println!("  2. Filter by price range ($50-$500)");
346    println!("  3. Filter by rating (>4.5)");
347    println!("  4. Select names");
348    println!("  5. Take first 3");
349    println!();
350
351    let results: Vec<String> = LazyQuery::new(&products)
352        .where_(Product::category_r(), |cat| cat == "Electronics")
353        .where_(Product::price_r(), |&p| p >= 50.0 && p <= 500.0)
354        .where_(Product::rating_r(), |&r| r > 4.5)
355        .select_lazy(Product::name_r())
356        .take(3)
357        .collect();
358
359    println!("  Results:");
360    for (i, name) in results.iter().enumerate() {
361        println!("    {}. {}", i + 1, name);
362    }
363    println!("  ✅ All operations fused and executed lazily!");
364
365    // ============================================================================
366    // THREAD-SAFE UPDATES WITH RWLOCK
367    // ============================================================================
368    println!("\n═══════════════════════════════════════════════════════════════");
369    println!("Bonus: Thread-safe updates with RwLock");
370    println!("═══════════════════════════════════════════════════════════════\n");
371
372    // Update a product through the Arc<RwLock>
373    if let Some(product_arc) = product_map.get("PROD-002") {
374        println!("Updating PROD-002 stock...");
375        
376        // Write lock for mutation
377        if let Ok(mut product) = product_arc.write() {
378            let old_stock = product.stock;
379            product.stock = 25;
380            println!("  Stock updated: {} → {}", old_stock, product.stock);
381        }
382    }
383
384    // Query again to see the update
385    let updated_products = extract_products(&product_map);
386    let mouse = LazyQuery::new(&updated_products)
387        .find(|p| p.id == 2);
388
389    if let Some(product) = mouse {
390        println!("  Verified update: {} now has {} in stock", product.name, product.stock);
391    }
392
393    // ============================================================================
394    // PRACTICAL EXAMPLE: Price Analysis by Category
395    // ============================================================================
396    println!("\n═══════════════════════════════════════════════════════════════");
397    println!("Practical Example: Price analysis by category");
398    println!("═══════════════════════════════════════════════════════════════\n");
399
400    let categories = vec!["Electronics", "Furniture"];
401
402    for category in categories {
403        println!("  {} Statistics:", category);
404        
405        // Filter products by category first
406        let cat_products: Vec<Product> = products.iter()
407            .filter(|p| p.category == category)
408            .cloned()
409            .collect();
410
411        let count = LazyQuery::new(&cat_products).count();
412        let total = LazyQuery::new(&cat_products).sum_by(Product::price_r());
413        let avg = LazyQuery::new(&cat_products).avg_by(Product::price_r()).unwrap_or(0.0);
414        let min = LazyQuery::new(&cat_products).min_by_float(Product::price_r()).unwrap_or(0.0);
415        let max = LazyQuery::new(&cat_products).max_by_float(Product::price_r()).unwrap_or(0.0);
416
417        println!("    Count: {}", count);
418        println!("    Total: ${:.2}", total);
419        println!("    Average: ${:.2}", avg);
420        println!("    Range: ${:.2} - ${:.2}\n", min, max);
421    }
422
423    // ============================================================================
424    // COMBINING WITH HASHMAP OPERATIONS
425    // ============================================================================
426    println!("═══════════════════════════════════════════════════════════════");
427    println!("HashMap Integration: Query by key patterns");
428    println!("═══════════════════════════════════════════════════════════════\n");
429
430    // Filter HashMap by key pattern
431    let electronics_keys: Vec<String> = product_map
432        .iter()
433        .filter(|(_key, value)| {
434            // Read the value to check category
435            if let Ok(guard) = value.read() {
436                guard.category == "Electronics"
437            } else {
438                false
439            }
440        })
441        .map(|(key, _value)| key.clone())
442        .collect();
443
444    println!("  Electronics product IDs:");
445    for key in electronics_keys.iter().take(5) {
446        println!("    • {}", key);
447    }
448
449    // ============================================================================
450    // PERFORMANCE DEMONSTRATION
451    // ============================================================================
452    println!("\n═══════════════════════════════════════════════════════════════");
453    println!("Performance: Lazy vs Eager comparison");
454    println!("═══════════════════════════════════════════════════════════════\n");
455
456    println!("Scenario: Find first product with rating > 4.7 from {} products\n", products.len());
457
458    println!("  Eager approach (hypothetical):");
459    println!("    - Filter all {} products", products.len());
460    println!("    - Collect filtered results");
461    println!("    - Take first item");
462    println!("    - Wasted work: Check all items\n");
463
464    println!("  Lazy approach (actual):");
465    let _first_rated = LazyQuery::new(&products)
466        .where_(Product::rating_r(), |&r| r > 4.7)
467        .first();
468    println!("    - Starts checking products");
469    println!("    - Stops at first match");
470    println!("    - ✅ Early termination - checks ~3-5 items only!");
471
472    // ============================================================================
473    // Summary
474    // ============================================================================
475    println!("\n╔══════════════════════════════════════════════════════════════════╗");
476    println!("║  Summary: All Lazy Operations Demonstrated                      ║");
477    println!("╚══════════════════════════════════════════════════════════════════╝\n");
478
479    println!("✅ Lazy Query Operations:");
480    println!("   1. ✅ where_ - Lazy filtering");
481    println!("   2. ✅ select_lazy - Lazy projection");
482    println!("   3. ✅ take_lazy - Early termination");
483    println!("   4. ✅ skip_lazy - Pagination");
484    println!("   5. ✅ first - Short-circuit search");
485    println!("   6. ✅ any - Existence check (short-circuit)");
486    println!("   7. ✅ count - Count items");
487    println!("   8. ✅ sum_by - Sum aggregation");
488    println!("   9. ✅ avg_by - Average aggregation");
489    println!("   10. ✅ min_by_float - Minimum value");
490    println!("   11. ✅ max_by_float - Maximum value");
491    println!("   12. ✅ find - Find with predicate (short-circuit)");
492    println!("   13. ✅ for_each - Iteration");
493    println!("   14. ✅ fold - Custom aggregation");
494    println!("   15. ✅ all_match - Validation (short-circuit)");
495    println!("   16. ✅ into_iter - For loop support");
496    println!("   17. ✅ map_items - Transformation\n");
497
498    println!("✅ Arc<RwLock<T>> Benefits:");
499    println!("   • Thread-safe shared access");
500    println!("   • Interior mutability");
501    println!("   • Multiple readers, single writer");
502    println!("   • Reference counting (Arc)");
503    println!("   • Can be queried after extracting data\n");
504
505    println!("✅ HashMap<K, Arc<RwLock<V>>> Benefits:");
506    println!("   • Fast key-based lookup");
507    println!("   • Thread-safe value access");
508    println!("   • Can query all values");
509    println!("   • Can filter by key patterns");
510    println!("   • Perfect for shared state/caches\n");
511
512    println!("🎯 Use Cases:");
513    println!("   • Shared product catalogs");
514    println!("   • User session stores");
515    println!("   • Configuration caches");
516    println!("   • Real-time inventory systems");
517    println!("   • Multi-threaded data processing");
518    println!("   • Web server state management\n");
519
520    println!("✓ Arc<RwLock<T>> HashMap with all lazy operations demo complete!\n");
521}
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));
Examples found in repository?
examples/arc_rwlock_hashmap.rs (lines 272-274)
59fn main() {
60    println!("\n╔══════════════════════════════════════════════════════════════════╗");
61    println!("║  Arc<RwLock<T>> HashMap Lazy Query Demo                         ║");
62    println!("║  Thread-safe shared data with lazy evaluation                   ║");
63    println!("╚══════════════════════════════════════════════════════════════════╝\n");
64
65    let product_map = create_sample_data();
66    println!("Created product catalog:");
67    println!("  Total products: {}", product_map.len());
68    println!("  Keys: {:?}\n", product_map.keys().take(3).collect::<Vec<_>>());
69
70    // Extract products for querying
71    let products = extract_products(&product_map);
72    println!("Extracted {} products from Arc<RwLock<Product>>\n", products.len());
73
74    // ============================================================================
75    // LAZY OPERATION 1: where_ - Lazy Filtering
76    // ============================================================================
77    println!("═══════════════════════════════════════════════════════════════");
78    println!("Lazy Operation 1: where_ (filtering)");
79    println!("═══════════════════════════════════════════════════════════════\n");
80
81    println!("Building filtered query (nothing executes yet)...");
82    let electronics_query = LazyQuery::new(&products)
83        .where_(Product::category_r(), |cat| cat == "Electronics")
84        .where_(Product::active_r(), |&active| active)
85        .where_(Product::stock_r(), |&stock| stock > 20);
86
87    println!("  ✅ Query built (deferred execution)\n");
88
89    println!("Collecting results (executes now)...");
90    let electronics: Vec<_> = electronics_query.collect();
91    println!("  Found {} electronics in stock", electronics.len());
92    for p in &electronics {
93        println!("    • {}: {} in stock", p.name, p.stock);
94    }
95
96    // ============================================================================
97    // LAZY OPERATION 2: select_lazy - Lazy Projection
98    // ============================================================================
99    println!("\n═══════════════════════════════════════════════════════════════");
100    println!("Lazy Operation 2: select_lazy (projection)");
101    println!("═══════════════════════════════════════════════════════════════\n");
102
103    println!("Selecting product names (lazy)...");
104    let names: Vec<String> = LazyQuery::new(&products)
105        .where_(Product::category_r(), |cat| cat == "Furniture")
106        .select_lazy(Product::name_r())
107        .collect();
108
109    println!("  Furniture names ({}):", names.len());
110    for name in &names {
111        println!("    • {}", name);
112    }
113
114    // ============================================================================
115    // LAZY OPERATION 3: take_lazy - Early Termination
116    // ============================================================================
117    println!("\n═══════════════════════════════════════════════════════════════");
118    println!("Lazy Operation 3: take_lazy (early termination)");
119    println!("═══════════════════════════════════════════════════════════════\n");
120
121    println!("Getting first 3 electronics...");
122    let first_3: Vec<_> = LazyQuery::new(&products)
123        .where_(Product::category_r(), |cat| cat == "Electronics")
124        .take_lazy(3)
125        .collect();
126
127    println!("  First 3 electronics:");
128    for (i, p) in first_3.iter().enumerate() {
129        println!("    {}. {} - ${:.2}", i + 1, p.name, p.price);
130    }
131    println!("  ✅ Stopped after finding 3 items!");
132
133    // ============================================================================
134    // LAZY OPERATION 4: skip_lazy - Pagination
135    // ============================================================================
136    println!("\n═══════════════════════════════════════════════════════════════");
137    println!("Lazy Operation 4: skip_lazy (pagination)");
138    println!("═══════════════════════════════════════════════════════════════\n");
139
140    println!("Getting page 2 (skip 3, take 3)...");
141    let page_2: Vec<_> = LazyQuery::new(&products)
142        .where_(Product::active_r(), |&active| active)
143        .skip_lazy(3)
144        .take_lazy(3)
145        .collect();
146
147    println!("  Page 2 items:");
148    for (i, p) in page_2.iter().enumerate() {
149        println!("    {}. {}", i + 4, p.name);
150    }
151
152    // ============================================================================
153    // LAZY OPERATION 5: first - Short-Circuit Search
154    // ============================================================================
155    println!("\n═══════════════════════════════════════════════════════════════");
156    println!("Lazy Operation 5: first (short-circuit)");
157    println!("═══════════════════════════════════════════════════════════════\n");
158
159    println!("Finding first expensive item (>$1000)...");
160    let expensive = LazyQuery::new(&products)
161        .where_(Product::price_r(), |&price| price > 1000.0)
162        .first();
163
164    match expensive {
165        Some(p) => println!("  Found: {} - ${:.2}", p.name, p.price),
166        None => println!("  Not found"),
167    }
168    println!("  ✅ Stopped at first match!");
169
170    // ============================================================================
171    // LAZY OPERATION 6: any - Existence Check
172    // ============================================================================
173    println!("\n═══════════════════════════════════════════════════════════════");
174    println!("Lazy Operation 6: any (existence check)");
175    println!("═══════════════════════════════════════════════════════════════\n");
176
177    println!("Checking if any furniture exists...");
178    let has_furniture = LazyQuery::new(&products)
179        .where_(Product::category_r(), |cat| cat == "Furniture")
180        .any();
181
182    println!("  Has furniture: {}", has_furniture);
183    println!("  ✅ Stopped immediately after finding first match!");
184
185    // ============================================================================
186    // LAZY OPERATION 7: count - Count Matching Items
187    // ============================================================================
188    println!("\n═══════════════════════════════════════════════════════════════");
189    println!("Lazy Operation 7: count");
190    println!("═══════════════════════════════════════════════════════════════\n");
191
192    let electronics_count = LazyQuery::new(&products)
193        .where_(Product::category_r(), |cat| cat == "Electronics")
194        .count();
195
196    println!("  Electronics count: {}", electronics_count);
197
198    // ============================================================================
199    // LAZY OPERATION 8: sum_by - Aggregation
200    // ============================================================================
201    println!("\n═══════════════════════════════════════════════════════════════");
202    println!("Lazy Operation 8: sum_by (aggregation)");
203    println!("═══════════════════════════════════════════════════════════════\n");
204
205    let total_value: f64 = LazyQuery::new(&products)
206        .where_(Product::category_r(), |cat| cat == "Electronics")
207        .sum_by(Product::price_r());
208
209    println!("  Total electronics value: ${:.2}", total_value);
210
211    // ============================================================================
212    // LAZY OPERATION 9: avg_by - Average
213    // ============================================================================
214    println!("\n═══════════════════════════════════════════════════════════════");
215    println!("Lazy Operation 9: avg_by");
216    println!("═══════════════════════════════════════════════════════════════\n");
217
218    let avg_price = LazyQuery::new(&products)
219        .where_(Product::category_r(), |cat| cat == "Furniture")
220        .avg_by(Product::price_r())
221        .unwrap_or(0.0);
222
223    println!("  Average furniture price: ${:.2}", avg_price);
224
225    // ============================================================================
226    // LAZY OPERATION 10: min_by_float / max_by_float
227    // ============================================================================
228    println!("\n═══════════════════════════════════════════════════════════════");
229    println!("Lazy Operation 10: min_by_float / max_by_float");
230    println!("═══════════════════════════════════════════════════════════════\n");
231
232    let min_price = LazyQuery::new(&products)
233        .where_(Product::active_r(), |&active| active)
234        .min_by_float(Product::price_r())
235        .unwrap_or(0.0);
236
237    let max_price = LazyQuery::new(&products)
238        .where_(Product::active_r(), |&active| active)
239        .max_by_float(Product::price_r())
240        .unwrap_or(0.0);
241
242    println!("  Price range for active products:");
243    println!("    Min: ${:.2}", min_price);
244    println!("    Max: ${:.2}", max_price);
245
246    // ============================================================================
247    // LAZY OPERATION 11: find - Find with Predicate
248    // ============================================================================
249    println!("\n═══════════════════════════════════════════════════════════════");
250    println!("Lazy Operation 11: find (with predicate)");
251    println!("═══════════════════════════════════════════════════════════════\n");
252
253    let high_rated = LazyQuery::new(&products)
254        .where_(Product::category_r(), |cat| cat == "Electronics")
255        .find(|item| item.rating > 4.7);
256
257    if let Some(product) = high_rated {
258        println!("  First highly-rated electronic:");
259        println!("    {}: Rating {:.1}", product.name, product.rating);
260    }
261
262    // ============================================================================
263    // LAZY OPERATION 12: for_each - Iteration
264    // ============================================================================
265    println!("\n═══════════════════════════════════════════════════════════════");
266    println!("Lazy Operation 12: for_each (iteration)");
267    println!("═══════════════════════════════════════════════════════════════\n");
268
269    println!("  Low stock alerts:");
270    LazyQuery::new(&products)
271        .where_(Product::stock_r(), |&stock| stock < 20)
272        .for_each(|product| {
273            println!("    ⚠️  {}: Only {} in stock", product.name, product.stock);
274        });
275
276    // ============================================================================
277    // LAZY OPERATION 13: fold - Custom Aggregation
278    // ============================================================================
279    println!("\n═══════════════════════════════════════════════════════════════");
280    println!("Lazy Operation 14: fold (custom aggregation)");
281    println!("═══════════════════════════════════════════════════════════════\n");
282
283    let total_inventory_value = LazyQuery::new(&products)
284        .where_(Product::active_r(), |&active| active)
285        .fold(0.0, |acc, product| {
286            acc + (product.price * product.stock as f64)
287        });
288
289    println!("  Total inventory value: ${:.2}", total_inventory_value);
290
291    // ============================================================================
292    // LAZY OPERATION 14: all_match - Validation
293    // ============================================================================
294    println!("\n═══════════════════════════════════════════════════════════════");
295    println!("Lazy Operation 15: all_match (validation)");
296    println!("═══════════════════════════════════════════════════════════════\n");
297
298    let all_priced = LazyQuery::new(&products)
299        .all_match(|item| item.price > 0.0);
300
301    println!("  All products have valid prices: {}", all_priced);
302
303    // ============================================================================
304    // LAZY OPERATION 15: into_iter - For Loop
305    // ============================================================================
306    println!("\n═══════════════════════════════════════════════════════════════");
307    println!("Lazy Operation 16: into_iter (for loop)");
308    println!("═══════════════════════════════════════════════════════════════\n");
309
310    println!("  High-value products (>$300):");
311    for product in LazyQuery::new(&products)
312        .where_(Product::price_r(), |&p| p > 300.0)
313        .take_lazy(5)
314    {
315        println!("    • {}: ${:.2}", product.name, product.price);
316    }
317
318    // ============================================================================
319    // LAZY OPERATION 16: map_items - Transform
320    // ============================================================================
321    println!("\n═══════════════════════════════════════════════════════════════");
322    println!("Lazy Operation 17: map_items (transformation)");
323    println!("═══════════════════════════════════════════════════════════════\n");
324
325    let price_tags: Vec<String> = LazyQuery::new(&products)
326        .where_(Product::category_r(), |cat| cat == "Electronics")
327        .map_items(|p| format!("{}: ${:.2}", p.name, p.price))
328        .take(5)
329        .collect();
330
331    println!("  Electronics price tags:");
332    for tag in &price_tags {
333        println!("    • {}", tag);
334    }
335
336    // ============================================================================
337    // COMPLEX EXAMPLE: Multi-Stage Lazy Pipeline
338    // ============================================================================
339    println!("\n═══════════════════════════════════════════════════════════════");
340    println!("Complex Example: Multi-stage lazy pipeline");
341    println!("═══════════════════════════════════════════════════════════════\n");
342
343    println!("Building complex query:");
344    println!("  1. Filter by category (Electronics)");
345    println!("  2. Filter by price range ($50-$500)");
346    println!("  3. Filter by rating (>4.5)");
347    println!("  4. Select names");
348    println!("  5. Take first 3");
349    println!();
350
351    let results: Vec<String> = LazyQuery::new(&products)
352        .where_(Product::category_r(), |cat| cat == "Electronics")
353        .where_(Product::price_r(), |&p| p >= 50.0 && p <= 500.0)
354        .where_(Product::rating_r(), |&r| r > 4.5)
355        .select_lazy(Product::name_r())
356        .take(3)
357        .collect();
358
359    println!("  Results:");
360    for (i, name) in results.iter().enumerate() {
361        println!("    {}. {}", i + 1, name);
362    }
363    println!("  ✅ All operations fused and executed lazily!");
364
365    // ============================================================================
366    // THREAD-SAFE UPDATES WITH RWLOCK
367    // ============================================================================
368    println!("\n═══════════════════════════════════════════════════════════════");
369    println!("Bonus: Thread-safe updates with RwLock");
370    println!("═══════════════════════════════════════════════════════════════\n");
371
372    // Update a product through the Arc<RwLock>
373    if let Some(product_arc) = product_map.get("PROD-002") {
374        println!("Updating PROD-002 stock...");
375        
376        // Write lock for mutation
377        if let Ok(mut product) = product_arc.write() {
378            let old_stock = product.stock;
379            product.stock = 25;
380            println!("  Stock updated: {} → {}", old_stock, product.stock);
381        }
382    }
383
384    // Query again to see the update
385    let updated_products = extract_products(&product_map);
386    let mouse = LazyQuery::new(&updated_products)
387        .find(|p| p.id == 2);
388
389    if let Some(product) = mouse {
390        println!("  Verified update: {} now has {} in stock", product.name, product.stock);
391    }
392
393    // ============================================================================
394    // PRACTICAL EXAMPLE: Price Analysis by Category
395    // ============================================================================
396    println!("\n═══════════════════════════════════════════════════════════════");
397    println!("Practical Example: Price analysis by category");
398    println!("═══════════════════════════════════════════════════════════════\n");
399
400    let categories = vec!["Electronics", "Furniture"];
401
402    for category in categories {
403        println!("  {} Statistics:", category);
404        
405        // Filter products by category first
406        let cat_products: Vec<Product> = products.iter()
407            .filter(|p| p.category == category)
408            .cloned()
409            .collect();
410
411        let count = LazyQuery::new(&cat_products).count();
412        let total = LazyQuery::new(&cat_products).sum_by(Product::price_r());
413        let avg = LazyQuery::new(&cat_products).avg_by(Product::price_r()).unwrap_or(0.0);
414        let min = LazyQuery::new(&cat_products).min_by_float(Product::price_r()).unwrap_or(0.0);
415        let max = LazyQuery::new(&cat_products).max_by_float(Product::price_r()).unwrap_or(0.0);
416
417        println!("    Count: {}", count);
418        println!("    Total: ${:.2}", total);
419        println!("    Average: ${:.2}", avg);
420        println!("    Range: ${:.2} - ${:.2}\n", min, max);
421    }
422
423    // ============================================================================
424    // COMBINING WITH HASHMAP OPERATIONS
425    // ============================================================================
426    println!("═══════════════════════════════════════════════════════════════");
427    println!("HashMap Integration: Query by key patterns");
428    println!("═══════════════════════════════════════════════════════════════\n");
429
430    // Filter HashMap by key pattern
431    let electronics_keys: Vec<String> = product_map
432        .iter()
433        .filter(|(_key, value)| {
434            // Read the value to check category
435            if let Ok(guard) = value.read() {
436                guard.category == "Electronics"
437            } else {
438                false
439            }
440        })
441        .map(|(key, _value)| key.clone())
442        .collect();
443
444    println!("  Electronics product IDs:");
445    for key in electronics_keys.iter().take(5) {
446        println!("    • {}", key);
447    }
448
449    // ============================================================================
450    // PERFORMANCE DEMONSTRATION
451    // ============================================================================
452    println!("\n═══════════════════════════════════════════════════════════════");
453    println!("Performance: Lazy vs Eager comparison");
454    println!("═══════════════════════════════════════════════════════════════\n");
455
456    println!("Scenario: Find first product with rating > 4.7 from {} products\n", products.len());
457
458    println!("  Eager approach (hypothetical):");
459    println!("    - Filter all {} products", products.len());
460    println!("    - Collect filtered results");
461    println!("    - Take first item");
462    println!("    - Wasted work: Check all items\n");
463
464    println!("  Lazy approach (actual):");
465    let _first_rated = LazyQuery::new(&products)
466        .where_(Product::rating_r(), |&r| r > 4.7)
467        .first();
468    println!("    - Starts checking products");
469    println!("    - Stops at first match");
470    println!("    - ✅ Early termination - checks ~3-5 items only!");
471
472    // ============================================================================
473    // Summary
474    // ============================================================================
475    println!("\n╔══════════════════════════════════════════════════════════════════╗");
476    println!("║  Summary: All Lazy Operations Demonstrated                      ║");
477    println!("╚══════════════════════════════════════════════════════════════════╝\n");
478
479    println!("✅ Lazy Query Operations:");
480    println!("   1. ✅ where_ - Lazy filtering");
481    println!("   2. ✅ select_lazy - Lazy projection");
482    println!("   3. ✅ take_lazy - Early termination");
483    println!("   4. ✅ skip_lazy - Pagination");
484    println!("   5. ✅ first - Short-circuit search");
485    println!("   6. ✅ any - Existence check (short-circuit)");
486    println!("   7. ✅ count - Count items");
487    println!("   8. ✅ sum_by - Sum aggregation");
488    println!("   9. ✅ avg_by - Average aggregation");
489    println!("   10. ✅ min_by_float - Minimum value");
490    println!("   11. ✅ max_by_float - Maximum value");
491    println!("   12. ✅ find - Find with predicate (short-circuit)");
492    println!("   13. ✅ for_each - Iteration");
493    println!("   14. ✅ fold - Custom aggregation");
494    println!("   15. ✅ all_match - Validation (short-circuit)");
495    println!("   16. ✅ into_iter - For loop support");
496    println!("   17. ✅ map_items - Transformation\n");
497
498    println!("✅ Arc<RwLock<T>> Benefits:");
499    println!("   • Thread-safe shared access");
500    println!("   • Interior mutability");
501    println!("   • Multiple readers, single writer");
502    println!("   • Reference counting (Arc)");
503    println!("   • Can be queried after extracting data\n");
504
505    println!("✅ HashMap<K, Arc<RwLock<V>>> Benefits:");
506    println!("   • Fast key-based lookup");
507    println!("   • Thread-safe value access");
508    println!("   • Can query all values");
509    println!("   • Can filter by key patterns");
510    println!("   • Perfect for shared state/caches\n");
511
512    println!("🎯 Use Cases:");
513    println!("   • Shared product catalogs");
514    println!("   • User session stores");
515    println!("   • Configuration caches");
516    println!("   • Real-time inventory systems");
517    println!("   • Multi-threaded data processing");
518    println!("   • Web server state management\n");
519
520    println!("✓ Arc<RwLock<T>> HashMap with all lazy operations demo complete!\n");
521}
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);
Examples found in repository?
examples/arc_rwlock_hashmap.rs (lines 285-287)
59fn main() {
60    println!("\n╔══════════════════════════════════════════════════════════════════╗");
61    println!("║  Arc<RwLock<T>> HashMap Lazy Query Demo                         ║");
62    println!("║  Thread-safe shared data with lazy evaluation                   ║");
63    println!("╚══════════════════════════════════════════════════════════════════╝\n");
64
65    let product_map = create_sample_data();
66    println!("Created product catalog:");
67    println!("  Total products: {}", product_map.len());
68    println!("  Keys: {:?}\n", product_map.keys().take(3).collect::<Vec<_>>());
69
70    // Extract products for querying
71    let products = extract_products(&product_map);
72    println!("Extracted {} products from Arc<RwLock<Product>>\n", products.len());
73
74    // ============================================================================
75    // LAZY OPERATION 1: where_ - Lazy Filtering
76    // ============================================================================
77    println!("═══════════════════════════════════════════════════════════════");
78    println!("Lazy Operation 1: where_ (filtering)");
79    println!("═══════════════════════════════════════════════════════════════\n");
80
81    println!("Building filtered query (nothing executes yet)...");
82    let electronics_query = LazyQuery::new(&products)
83        .where_(Product::category_r(), |cat| cat == "Electronics")
84        .where_(Product::active_r(), |&active| active)
85        .where_(Product::stock_r(), |&stock| stock > 20);
86
87    println!("  ✅ Query built (deferred execution)\n");
88
89    println!("Collecting results (executes now)...");
90    let electronics: Vec<_> = electronics_query.collect();
91    println!("  Found {} electronics in stock", electronics.len());
92    for p in &electronics {
93        println!("    • {}: {} in stock", p.name, p.stock);
94    }
95
96    // ============================================================================
97    // LAZY OPERATION 2: select_lazy - Lazy Projection
98    // ============================================================================
99    println!("\n═══════════════════════════════════════════════════════════════");
100    println!("Lazy Operation 2: select_lazy (projection)");
101    println!("═══════════════════════════════════════════════════════════════\n");
102
103    println!("Selecting product names (lazy)...");
104    let names: Vec<String> = LazyQuery::new(&products)
105        .where_(Product::category_r(), |cat| cat == "Furniture")
106        .select_lazy(Product::name_r())
107        .collect();
108
109    println!("  Furniture names ({}):", names.len());
110    for name in &names {
111        println!("    • {}", name);
112    }
113
114    // ============================================================================
115    // LAZY OPERATION 3: take_lazy - Early Termination
116    // ============================================================================
117    println!("\n═══════════════════════════════════════════════════════════════");
118    println!("Lazy Operation 3: take_lazy (early termination)");
119    println!("═══════════════════════════════════════════════════════════════\n");
120
121    println!("Getting first 3 electronics...");
122    let first_3: Vec<_> = LazyQuery::new(&products)
123        .where_(Product::category_r(), |cat| cat == "Electronics")
124        .take_lazy(3)
125        .collect();
126
127    println!("  First 3 electronics:");
128    for (i, p) in first_3.iter().enumerate() {
129        println!("    {}. {} - ${:.2}", i + 1, p.name, p.price);
130    }
131    println!("  ✅ Stopped after finding 3 items!");
132
133    // ============================================================================
134    // LAZY OPERATION 4: skip_lazy - Pagination
135    // ============================================================================
136    println!("\n═══════════════════════════════════════════════════════════════");
137    println!("Lazy Operation 4: skip_lazy (pagination)");
138    println!("═══════════════════════════════════════════════════════════════\n");
139
140    println!("Getting page 2 (skip 3, take 3)...");
141    let page_2: Vec<_> = LazyQuery::new(&products)
142        .where_(Product::active_r(), |&active| active)
143        .skip_lazy(3)
144        .take_lazy(3)
145        .collect();
146
147    println!("  Page 2 items:");
148    for (i, p) in page_2.iter().enumerate() {
149        println!("    {}. {}", i + 4, p.name);
150    }
151
152    // ============================================================================
153    // LAZY OPERATION 5: first - Short-Circuit Search
154    // ============================================================================
155    println!("\n═══════════════════════════════════════════════════════════════");
156    println!("Lazy Operation 5: first (short-circuit)");
157    println!("═══════════════════════════════════════════════════════════════\n");
158
159    println!("Finding first expensive item (>$1000)...");
160    let expensive = LazyQuery::new(&products)
161        .where_(Product::price_r(), |&price| price > 1000.0)
162        .first();
163
164    match expensive {
165        Some(p) => println!("  Found: {} - ${:.2}", p.name, p.price),
166        None => println!("  Not found"),
167    }
168    println!("  ✅ Stopped at first match!");
169
170    // ============================================================================
171    // LAZY OPERATION 6: any - Existence Check
172    // ============================================================================
173    println!("\n═══════════════════════════════════════════════════════════════");
174    println!("Lazy Operation 6: any (existence check)");
175    println!("═══════════════════════════════════════════════════════════════\n");
176
177    println!("Checking if any furniture exists...");
178    let has_furniture = LazyQuery::new(&products)
179        .where_(Product::category_r(), |cat| cat == "Furniture")
180        .any();
181
182    println!("  Has furniture: {}", has_furniture);
183    println!("  ✅ Stopped immediately after finding first match!");
184
185    // ============================================================================
186    // LAZY OPERATION 7: count - Count Matching Items
187    // ============================================================================
188    println!("\n═══════════════════════════════════════════════════════════════");
189    println!("Lazy Operation 7: count");
190    println!("═══════════════════════════════════════════════════════════════\n");
191
192    let electronics_count = LazyQuery::new(&products)
193        .where_(Product::category_r(), |cat| cat == "Electronics")
194        .count();
195
196    println!("  Electronics count: {}", electronics_count);
197
198    // ============================================================================
199    // LAZY OPERATION 8: sum_by - Aggregation
200    // ============================================================================
201    println!("\n═══════════════════════════════════════════════════════════════");
202    println!("Lazy Operation 8: sum_by (aggregation)");
203    println!("═══════════════════════════════════════════════════════════════\n");
204
205    let total_value: f64 = LazyQuery::new(&products)
206        .where_(Product::category_r(), |cat| cat == "Electronics")
207        .sum_by(Product::price_r());
208
209    println!("  Total electronics value: ${:.2}", total_value);
210
211    // ============================================================================
212    // LAZY OPERATION 9: avg_by - Average
213    // ============================================================================
214    println!("\n═══════════════════════════════════════════════════════════════");
215    println!("Lazy Operation 9: avg_by");
216    println!("═══════════════════════════════════════════════════════════════\n");
217
218    let avg_price = LazyQuery::new(&products)
219        .where_(Product::category_r(), |cat| cat == "Furniture")
220        .avg_by(Product::price_r())
221        .unwrap_or(0.0);
222
223    println!("  Average furniture price: ${:.2}", avg_price);
224
225    // ============================================================================
226    // LAZY OPERATION 10: min_by_float / max_by_float
227    // ============================================================================
228    println!("\n═══════════════════════════════════════════════════════════════");
229    println!("Lazy Operation 10: min_by_float / max_by_float");
230    println!("═══════════════════════════════════════════════════════════════\n");
231
232    let min_price = LazyQuery::new(&products)
233        .where_(Product::active_r(), |&active| active)
234        .min_by_float(Product::price_r())
235        .unwrap_or(0.0);
236
237    let max_price = LazyQuery::new(&products)
238        .where_(Product::active_r(), |&active| active)
239        .max_by_float(Product::price_r())
240        .unwrap_or(0.0);
241
242    println!("  Price range for active products:");
243    println!("    Min: ${:.2}", min_price);
244    println!("    Max: ${:.2}", max_price);
245
246    // ============================================================================
247    // LAZY OPERATION 11: find - Find with Predicate
248    // ============================================================================
249    println!("\n═══════════════════════════════════════════════════════════════");
250    println!("Lazy Operation 11: find (with predicate)");
251    println!("═══════════════════════════════════════════════════════════════\n");
252
253    let high_rated = LazyQuery::new(&products)
254        .where_(Product::category_r(), |cat| cat == "Electronics")
255        .find(|item| item.rating > 4.7);
256
257    if let Some(product) = high_rated {
258        println!("  First highly-rated electronic:");
259        println!("    {}: Rating {:.1}", product.name, product.rating);
260    }
261
262    // ============================================================================
263    // LAZY OPERATION 12: for_each - Iteration
264    // ============================================================================
265    println!("\n═══════════════════════════════════════════════════════════════");
266    println!("Lazy Operation 12: for_each (iteration)");
267    println!("═══════════════════════════════════════════════════════════════\n");
268
269    println!("  Low stock alerts:");
270    LazyQuery::new(&products)
271        .where_(Product::stock_r(), |&stock| stock < 20)
272        .for_each(|product| {
273            println!("    ⚠️  {}: Only {} in stock", product.name, product.stock);
274        });
275
276    // ============================================================================
277    // LAZY OPERATION 13: fold - Custom Aggregation
278    // ============================================================================
279    println!("\n═══════════════════════════════════════════════════════════════");
280    println!("Lazy Operation 14: fold (custom aggregation)");
281    println!("═══════════════════════════════════════════════════════════════\n");
282
283    let total_inventory_value = LazyQuery::new(&products)
284        .where_(Product::active_r(), |&active| active)
285        .fold(0.0, |acc, product| {
286            acc + (product.price * product.stock as f64)
287        });
288
289    println!("  Total inventory value: ${:.2}", total_inventory_value);
290
291    // ============================================================================
292    // LAZY OPERATION 14: all_match - Validation
293    // ============================================================================
294    println!("\n═══════════════════════════════════════════════════════════════");
295    println!("Lazy Operation 15: all_match (validation)");
296    println!("═══════════════════════════════════════════════════════════════\n");
297
298    let all_priced = LazyQuery::new(&products)
299        .all_match(|item| item.price > 0.0);
300
301    println!("  All products have valid prices: {}", all_priced);
302
303    // ============================================================================
304    // LAZY OPERATION 15: into_iter - For Loop
305    // ============================================================================
306    println!("\n═══════════════════════════════════════════════════════════════");
307    println!("Lazy Operation 16: into_iter (for loop)");
308    println!("═══════════════════════════════════════════════════════════════\n");
309
310    println!("  High-value products (>$300):");
311    for product in LazyQuery::new(&products)
312        .where_(Product::price_r(), |&p| p > 300.0)
313        .take_lazy(5)
314    {
315        println!("    • {}: ${:.2}", product.name, product.price);
316    }
317
318    // ============================================================================
319    // LAZY OPERATION 16: map_items - Transform
320    // ============================================================================
321    println!("\n═══════════════════════════════════════════════════════════════");
322    println!("Lazy Operation 17: map_items (transformation)");
323    println!("═══════════════════════════════════════════════════════════════\n");
324
325    let price_tags: Vec<String> = LazyQuery::new(&products)
326        .where_(Product::category_r(), |cat| cat == "Electronics")
327        .map_items(|p| format!("{}: ${:.2}", p.name, p.price))
328        .take(5)
329        .collect();
330
331    println!("  Electronics price tags:");
332    for tag in &price_tags {
333        println!("    • {}", tag);
334    }
335
336    // ============================================================================
337    // COMPLEX EXAMPLE: Multi-Stage Lazy Pipeline
338    // ============================================================================
339    println!("\n═══════════════════════════════════════════════════════════════");
340    println!("Complex Example: Multi-stage lazy pipeline");
341    println!("═══════════════════════════════════════════════════════════════\n");
342
343    println!("Building complex query:");
344    println!("  1. Filter by category (Electronics)");
345    println!("  2. Filter by price range ($50-$500)");
346    println!("  3. Filter by rating (>4.5)");
347    println!("  4. Select names");
348    println!("  5. Take first 3");
349    println!();
350
351    let results: Vec<String> = LazyQuery::new(&products)
352        .where_(Product::category_r(), |cat| cat == "Electronics")
353        .where_(Product::price_r(), |&p| p >= 50.0 && p <= 500.0)
354        .where_(Product::rating_r(), |&r| r > 4.5)
355        .select_lazy(Product::name_r())
356        .take(3)
357        .collect();
358
359    println!("  Results:");
360    for (i, name) in results.iter().enumerate() {
361        println!("    {}. {}", i + 1, name);
362    }
363    println!("  ✅ All operations fused and executed lazily!");
364
365    // ============================================================================
366    // THREAD-SAFE UPDATES WITH RWLOCK
367    // ============================================================================
368    println!("\n═══════════════════════════════════════════════════════════════");
369    println!("Bonus: Thread-safe updates with RwLock");
370    println!("═══════════════════════════════════════════════════════════════\n");
371
372    // Update a product through the Arc<RwLock>
373    if let Some(product_arc) = product_map.get("PROD-002") {
374        println!("Updating PROD-002 stock...");
375        
376        // Write lock for mutation
377        if let Ok(mut product) = product_arc.write() {
378            let old_stock = product.stock;
379            product.stock = 25;
380            println!("  Stock updated: {} → {}", old_stock, product.stock);
381        }
382    }
383
384    // Query again to see the update
385    let updated_products = extract_products(&product_map);
386    let mouse = LazyQuery::new(&updated_products)
387        .find(|p| p.id == 2);
388
389    if let Some(product) = mouse {
390        println!("  Verified update: {} now has {} in stock", product.name, product.stock);
391    }
392
393    // ============================================================================
394    // PRACTICAL EXAMPLE: Price Analysis by Category
395    // ============================================================================
396    println!("\n═══════════════════════════════════════════════════════════════");
397    println!("Practical Example: Price analysis by category");
398    println!("═══════════════════════════════════════════════════════════════\n");
399
400    let categories = vec!["Electronics", "Furniture"];
401
402    for category in categories {
403        println!("  {} Statistics:", category);
404        
405        // Filter products by category first
406        let cat_products: Vec<Product> = products.iter()
407            .filter(|p| p.category == category)
408            .cloned()
409            .collect();
410
411        let count = LazyQuery::new(&cat_products).count();
412        let total = LazyQuery::new(&cat_products).sum_by(Product::price_r());
413        let avg = LazyQuery::new(&cat_products).avg_by(Product::price_r()).unwrap_or(0.0);
414        let min = LazyQuery::new(&cat_products).min_by_float(Product::price_r()).unwrap_or(0.0);
415        let max = LazyQuery::new(&cat_products).max_by_float(Product::price_r()).unwrap_or(0.0);
416
417        println!("    Count: {}", count);
418        println!("    Total: ${:.2}", total);
419        println!("    Average: ${:.2}", avg);
420        println!("    Range: ${:.2} - ${:.2}\n", min, max);
421    }
422
423    // ============================================================================
424    // COMBINING WITH HASHMAP OPERATIONS
425    // ============================================================================
426    println!("═══════════════════════════════════════════════════════════════");
427    println!("HashMap Integration: Query by key patterns");
428    println!("═══════════════════════════════════════════════════════════════\n");
429
430    // Filter HashMap by key pattern
431    let electronics_keys: Vec<String> = product_map
432        .iter()
433        .filter(|(_key, value)| {
434            // Read the value to check category
435            if let Ok(guard) = value.read() {
436                guard.category == "Electronics"
437            } else {
438                false
439            }
440        })
441        .map(|(key, _value)| key.clone())
442        .collect();
443
444    println!("  Electronics product IDs:");
445    for key in electronics_keys.iter().take(5) {
446        println!("    • {}", key);
447    }
448
449    // ============================================================================
450    // PERFORMANCE DEMONSTRATION
451    // ============================================================================
452    println!("\n═══════════════════════════════════════════════════════════════");
453    println!("Performance: Lazy vs Eager comparison");
454    println!("═══════════════════════════════════════════════════════════════\n");
455
456    println!("Scenario: Find first product with rating > 4.7 from {} products\n", products.len());
457
458    println!("  Eager approach (hypothetical):");
459    println!("    - Filter all {} products", products.len());
460    println!("    - Collect filtered results");
461    println!("    - Take first item");
462    println!("    - Wasted work: Check all items\n");
463
464    println!("  Lazy approach (actual):");
465    let _first_rated = LazyQuery::new(&products)
466        .where_(Product::rating_r(), |&r| r > 4.7)
467        .first();
468    println!("    - Starts checking products");
469    println!("    - Stops at first match");
470    println!("    - ✅ Early termination - checks ~3-5 items only!");
471
472    // ============================================================================
473    // Summary
474    // ============================================================================
475    println!("\n╔══════════════════════════════════════════════════════════════════╗");
476    println!("║  Summary: All Lazy Operations Demonstrated                      ║");
477    println!("╚══════════════════════════════════════════════════════════════════╝\n");
478
479    println!("✅ Lazy Query Operations:");
480    println!("   1. ✅ where_ - Lazy filtering");
481    println!("   2. ✅ select_lazy - Lazy projection");
482    println!("   3. ✅ take_lazy - Early termination");
483    println!("   4. ✅ skip_lazy - Pagination");
484    println!("   5. ✅ first - Short-circuit search");
485    println!("   6. ✅ any - Existence check (short-circuit)");
486    println!("   7. ✅ count - Count items");
487    println!("   8. ✅ sum_by - Sum aggregation");
488    println!("   9. ✅ avg_by - Average aggregation");
489    println!("   10. ✅ min_by_float - Minimum value");
490    println!("   11. ✅ max_by_float - Maximum value");
491    println!("   12. ✅ find - Find with predicate (short-circuit)");
492    println!("   13. ✅ for_each - Iteration");
493    println!("   14. ✅ fold - Custom aggregation");
494    println!("   15. ✅ all_match - Validation (short-circuit)");
495    println!("   16. ✅ into_iter - For loop support");
496    println!("   17. ✅ map_items - Transformation\n");
497
498    println!("✅ Arc<RwLock<T>> Benefits:");
499    println!("   • Thread-safe shared access");
500    println!("   • Interior mutability");
501    println!("   • Multiple readers, single writer");
502    println!("   • Reference counting (Arc)");
503    println!("   • Can be queried after extracting data\n");
504
505    println!("✅ HashMap<K, Arc<RwLock<V>>> Benefits:");
506    println!("   • Fast key-based lookup");
507    println!("   • Thread-safe value access");
508    println!("   • Can query all values");
509    println!("   • Can filter by key patterns");
510    println!("   • Perfect for shared state/caches\n");
511
512    println!("🎯 Use Cases:");
513    println!("   • Shared product catalogs");
514    println!("   • User session stores");
515    println!("   • Configuration caches");
516    println!("   • Real-time inventory systems");
517    println!("   • Multi-threaded data processing");
518    println!("   • Web server state management\n");
519
520    println!("✓ Arc<RwLock<T>> HashMap with all lazy operations demo complete!\n");
521}
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);
Examples found in repository?
examples/derive_and_ext.rs (line 150)
13fn main() {
14    println!("Derive Macros and Extension Traits Example");
15    println!("===========================================\n");
16
17    let products = vec![
18        Product {
19            id: 1,
20            name: "Laptop".to_string(),
21            price: 999.99,
22            category: "Electronics".to_string(),
23            stock: 5,
24        },
25        Product {
26            id: 2,
27            name: "Mouse".to_string(),
28            price: 29.99,
29            category: "Electronics".to_string(),
30            stock: 50,
31        },
32        Product {
33            id: 3,
34            name: "Keyboard".to_string(),
35            price: 79.99,
36            category: "Electronics".to_string(),
37            stock: 30,
38        },
39        Product {
40            id: 4,
41            name: "Monitor".to_string(),
42            price: 299.99,
43            category: "Electronics".to_string(),
44            stock: 12,
45        },
46        Product {
47            id: 5,
48            name: "Desk Chair".to_string(),
49            price: 199.99,
50            category: "Furniture".to_string(),
51            stock: 8,
52        },
53    ];
54
55    println!("1. Using Extension Trait - Direct .query() on Vec");
56    println!("   Query: products.query().where_(price > 100).all()");
57    
58    let query = products
59        .query()
60        .where_(Product::price_r(), |&p| p > 100.0);
61    let expensive = query.all();
62    
63    println!("   Found {} expensive products:", expensive.len());
64    for product in &expensive {
65        println!("   - {} (${:.2})", product.name, product.price);
66    }
67    println!();
68
69    println!("2. Using Extension Trait - Direct .lazy_query() on Vec");
70    println!("   Query: products.lazy_query().where_(stock < 10).collect()");
71    
72    let low_stock: Vec<_> = products
73        .lazy_query()
74        .where_(Product::stock_r(), |&s| s < 10)
75        .collect();
76    
77    println!("   Found {} low stock products:", low_stock.len());
78    for product in &low_stock {
79        println!("   - {} (stock: {})", product.name, product.stock);
80    }
81    println!();
82
83    println!("3. Using Extension Trait - Chained Operations");
84    println!("   Query: products.lazy_query().where_(category == Electronics).take(2).select(name).collect()");
85    
86    let names: Vec<String> = products
87        .lazy_query()
88        .where_(Product::category_r(), |cat| cat == "Electronics")
89        .take_lazy(2)
90        .select_lazy(Product::name_r())
91        .collect();
92    
93    println!("   First 2 electronics:");
94    for name in &names {
95        println!("   - {}", name);
96    }
97    println!();
98
99    println!("4. Using QueryBuilder Derive - Static Methods");
100    println!("   Query: Product::query(&products).where_(price > 50).count()");
101    
102    let query4 = Product::query(&products)
103        .where_(Product::price_r(), |&p| p > 50.0);
104    let count = query4.count();
105    
106    println!("   Products over $50: {}", count);
107    println!();
108
109    println!("5. Using QueryBuilder Derive - Lazy Static Methods");
110    println!("   Query: Product::lazy_query(&products).first()");
111    
112    if let Some(first) = Product::lazy_query(&products).first() {
113        println!("   First product: {} (${:.2})", first.name, first.price);
114    }
115    println!();
116
117    println!("6. Complex Chain with Extension Trait");
118    println!("   Query: products.lazy_query()");
119    println!("          .where_(category == Electronics)");
120    println!("          .where_(price < 500)");
121    println!("          .map(|p| format!(\"{{}} - ${{:.2}}\", p.name, p.price))");
122    println!("          .collect()");
123    
124    let formatted: Vec<String> = products
125        .lazy_query()
126        .where_(Product::category_r(), |cat| cat == "Electronics")
127        .where_(Product::price_r(), |&p| p < 500.0)
128        .map_items(|p| format!("{} - ${:.2}", p.name, p.price))
129        .collect();
130    
131    println!("   Affordable electronics:");
132    for item in &formatted {
133        println!("   - {}", item);
134    }
135    println!();
136
137    println!("7. Aggregation with Extension Trait");
138    println!("   Query: products.lazy_query().sum_by(Product::stock())");
139    
140    let total_stock = products
141        .lazy_query()
142        .sum_by(Product::stock_r());
143    
144    println!("   Total stock across all products: {}", total_stock);
145    println!();
146
147    println!("8. Find with Extension Trait");
148    println!("   Query: products.lazy_query().find(|p| p.name.contains(\"Chair\"))");
149    
150    if let Some(chair) = products.lazy_query().find(|p| p.name.contains("Chair")) {
151        println!("   Found: {} in {}", chair.name, chair.category);
152    }
153    println!();
154
155    println!("9. Early Termination with Extension Trait");
156    println!("   Query: products.lazy_query().where_(price > 1000).any()");
157    
158    let has_luxury = products
159        .lazy_query()
160        .where_(Product::price_r(), |&p| p > 1000.0)
161        .any();
162    
163    println!("   Has products over $1000: {}", has_luxury);
164    println!();
165
166    println!("10. Slice Extension Trait");
167    println!("    Query: (&products[..]).lazy_query().count()");
168    
169    let slice_count = (&products[..])
170        .lazy_query()
171        .count();
172    
173    println!("    Count from slice: {}", slice_count);
174    println!();
175
176    println!("Summary:");
177    println!("--------");
178    println!("✓ Extension trait QueryExt adds .query() and .lazy_query() to containers");
179    println!("✓ Derive macro QueryBuilder adds static methods Product::query() and Product::lazy_query()");
180    println!("✓ Both approaches provide the same query functionality");
181    println!("✓ Extension trait is more ergonomic: products.query() vs Query::new(&products)");
182    println!("✓ All iterator optimizations (fusion, early termination) still apply");
183}
More examples
Hide additional examples
examples/arc_rwlock_hashmap.rs (line 255)
59fn main() {
60    println!("\n╔══════════════════════════════════════════════════════════════════╗");
61    println!("║  Arc<RwLock<T>> HashMap Lazy Query Demo                         ║");
62    println!("║  Thread-safe shared data with lazy evaluation                   ║");
63    println!("╚══════════════════════════════════════════════════════════════════╝\n");
64
65    let product_map = create_sample_data();
66    println!("Created product catalog:");
67    println!("  Total products: {}", product_map.len());
68    println!("  Keys: {:?}\n", product_map.keys().take(3).collect::<Vec<_>>());
69
70    // Extract products for querying
71    let products = extract_products(&product_map);
72    println!("Extracted {} products from Arc<RwLock<Product>>\n", products.len());
73
74    // ============================================================================
75    // LAZY OPERATION 1: where_ - Lazy Filtering
76    // ============================================================================
77    println!("═══════════════════════════════════════════════════════════════");
78    println!("Lazy Operation 1: where_ (filtering)");
79    println!("═══════════════════════════════════════════════════════════════\n");
80
81    println!("Building filtered query (nothing executes yet)...");
82    let electronics_query = LazyQuery::new(&products)
83        .where_(Product::category_r(), |cat| cat == "Electronics")
84        .where_(Product::active_r(), |&active| active)
85        .where_(Product::stock_r(), |&stock| stock > 20);
86
87    println!("  ✅ Query built (deferred execution)\n");
88
89    println!("Collecting results (executes now)...");
90    let electronics: Vec<_> = electronics_query.collect();
91    println!("  Found {} electronics in stock", electronics.len());
92    for p in &electronics {
93        println!("    • {}: {} in stock", p.name, p.stock);
94    }
95
96    // ============================================================================
97    // LAZY OPERATION 2: select_lazy - Lazy Projection
98    // ============================================================================
99    println!("\n═══════════════════════════════════════════════════════════════");
100    println!("Lazy Operation 2: select_lazy (projection)");
101    println!("═══════════════════════════════════════════════════════════════\n");
102
103    println!("Selecting product names (lazy)...");
104    let names: Vec<String> = LazyQuery::new(&products)
105        .where_(Product::category_r(), |cat| cat == "Furniture")
106        .select_lazy(Product::name_r())
107        .collect();
108
109    println!("  Furniture names ({}):", names.len());
110    for name in &names {
111        println!("    • {}", name);
112    }
113
114    // ============================================================================
115    // LAZY OPERATION 3: take_lazy - Early Termination
116    // ============================================================================
117    println!("\n═══════════════════════════════════════════════════════════════");
118    println!("Lazy Operation 3: take_lazy (early termination)");
119    println!("═══════════════════════════════════════════════════════════════\n");
120
121    println!("Getting first 3 electronics...");
122    let first_3: Vec<_> = LazyQuery::new(&products)
123        .where_(Product::category_r(), |cat| cat == "Electronics")
124        .take_lazy(3)
125        .collect();
126
127    println!("  First 3 electronics:");
128    for (i, p) in first_3.iter().enumerate() {
129        println!("    {}. {} - ${:.2}", i + 1, p.name, p.price);
130    }
131    println!("  ✅ Stopped after finding 3 items!");
132
133    // ============================================================================
134    // LAZY OPERATION 4: skip_lazy - Pagination
135    // ============================================================================
136    println!("\n═══════════════════════════════════════════════════════════════");
137    println!("Lazy Operation 4: skip_lazy (pagination)");
138    println!("═══════════════════════════════════════════════════════════════\n");
139
140    println!("Getting page 2 (skip 3, take 3)...");
141    let page_2: Vec<_> = LazyQuery::new(&products)
142        .where_(Product::active_r(), |&active| active)
143        .skip_lazy(3)
144        .take_lazy(3)
145        .collect();
146
147    println!("  Page 2 items:");
148    for (i, p) in page_2.iter().enumerate() {
149        println!("    {}. {}", i + 4, p.name);
150    }
151
152    // ============================================================================
153    // LAZY OPERATION 5: first - Short-Circuit Search
154    // ============================================================================
155    println!("\n═══════════════════════════════════════════════════════════════");
156    println!("Lazy Operation 5: first (short-circuit)");
157    println!("═══════════════════════════════════════════════════════════════\n");
158
159    println!("Finding first expensive item (>$1000)...");
160    let expensive = LazyQuery::new(&products)
161        .where_(Product::price_r(), |&price| price > 1000.0)
162        .first();
163
164    match expensive {
165        Some(p) => println!("  Found: {} - ${:.2}", p.name, p.price),
166        None => println!("  Not found"),
167    }
168    println!("  ✅ Stopped at first match!");
169
170    // ============================================================================
171    // LAZY OPERATION 6: any - Existence Check
172    // ============================================================================
173    println!("\n═══════════════════════════════════════════════════════════════");
174    println!("Lazy Operation 6: any (existence check)");
175    println!("═══════════════════════════════════════════════════════════════\n");
176
177    println!("Checking if any furniture exists...");
178    let has_furniture = LazyQuery::new(&products)
179        .where_(Product::category_r(), |cat| cat == "Furniture")
180        .any();
181
182    println!("  Has furniture: {}", has_furniture);
183    println!("  ✅ Stopped immediately after finding first match!");
184
185    // ============================================================================
186    // LAZY OPERATION 7: count - Count Matching Items
187    // ============================================================================
188    println!("\n═══════════════════════════════════════════════════════════════");
189    println!("Lazy Operation 7: count");
190    println!("═══════════════════════════════════════════════════════════════\n");
191
192    let electronics_count = LazyQuery::new(&products)
193        .where_(Product::category_r(), |cat| cat == "Electronics")
194        .count();
195
196    println!("  Electronics count: {}", electronics_count);
197
198    // ============================================================================
199    // LAZY OPERATION 8: sum_by - Aggregation
200    // ============================================================================
201    println!("\n═══════════════════════════════════════════════════════════════");
202    println!("Lazy Operation 8: sum_by (aggregation)");
203    println!("═══════════════════════════════════════════════════════════════\n");
204
205    let total_value: f64 = LazyQuery::new(&products)
206        .where_(Product::category_r(), |cat| cat == "Electronics")
207        .sum_by(Product::price_r());
208
209    println!("  Total electronics value: ${:.2}", total_value);
210
211    // ============================================================================
212    // LAZY OPERATION 9: avg_by - Average
213    // ============================================================================
214    println!("\n═══════════════════════════════════════════════════════════════");
215    println!("Lazy Operation 9: avg_by");
216    println!("═══════════════════════════════════════════════════════════════\n");
217
218    let avg_price = LazyQuery::new(&products)
219        .where_(Product::category_r(), |cat| cat == "Furniture")
220        .avg_by(Product::price_r())
221        .unwrap_or(0.0);
222
223    println!("  Average furniture price: ${:.2}", avg_price);
224
225    // ============================================================================
226    // LAZY OPERATION 10: min_by_float / max_by_float
227    // ============================================================================
228    println!("\n═══════════════════════════════════════════════════════════════");
229    println!("Lazy Operation 10: min_by_float / max_by_float");
230    println!("═══════════════════════════════════════════════════════════════\n");
231
232    let min_price = LazyQuery::new(&products)
233        .where_(Product::active_r(), |&active| active)
234        .min_by_float(Product::price_r())
235        .unwrap_or(0.0);
236
237    let max_price = LazyQuery::new(&products)
238        .where_(Product::active_r(), |&active| active)
239        .max_by_float(Product::price_r())
240        .unwrap_or(0.0);
241
242    println!("  Price range for active products:");
243    println!("    Min: ${:.2}", min_price);
244    println!("    Max: ${:.2}", max_price);
245
246    // ============================================================================
247    // LAZY OPERATION 11: find - Find with Predicate
248    // ============================================================================
249    println!("\n═══════════════════════════════════════════════════════════════");
250    println!("Lazy Operation 11: find (with predicate)");
251    println!("═══════════════════════════════════════════════════════════════\n");
252
253    let high_rated = LazyQuery::new(&products)
254        .where_(Product::category_r(), |cat| cat == "Electronics")
255        .find(|item| item.rating > 4.7);
256
257    if let Some(product) = high_rated {
258        println!("  First highly-rated electronic:");
259        println!("    {}: Rating {:.1}", product.name, product.rating);
260    }
261
262    // ============================================================================
263    // LAZY OPERATION 12: for_each - Iteration
264    // ============================================================================
265    println!("\n═══════════════════════════════════════════════════════════════");
266    println!("Lazy Operation 12: for_each (iteration)");
267    println!("═══════════════════════════════════════════════════════════════\n");
268
269    println!("  Low stock alerts:");
270    LazyQuery::new(&products)
271        .where_(Product::stock_r(), |&stock| stock < 20)
272        .for_each(|product| {
273            println!("    ⚠️  {}: Only {} in stock", product.name, product.stock);
274        });
275
276    // ============================================================================
277    // LAZY OPERATION 13: fold - Custom Aggregation
278    // ============================================================================
279    println!("\n═══════════════════════════════════════════════════════════════");
280    println!("Lazy Operation 14: fold (custom aggregation)");
281    println!("═══════════════════════════════════════════════════════════════\n");
282
283    let total_inventory_value = LazyQuery::new(&products)
284        .where_(Product::active_r(), |&active| active)
285        .fold(0.0, |acc, product| {
286            acc + (product.price * product.stock as f64)
287        });
288
289    println!("  Total inventory value: ${:.2}", total_inventory_value);
290
291    // ============================================================================
292    // LAZY OPERATION 14: all_match - Validation
293    // ============================================================================
294    println!("\n═══════════════════════════════════════════════════════════════");
295    println!("Lazy Operation 15: all_match (validation)");
296    println!("═══════════════════════════════════════════════════════════════\n");
297
298    let all_priced = LazyQuery::new(&products)
299        .all_match(|item| item.price > 0.0);
300
301    println!("  All products have valid prices: {}", all_priced);
302
303    // ============================================================================
304    // LAZY OPERATION 15: into_iter - For Loop
305    // ============================================================================
306    println!("\n═══════════════════════════════════════════════════════════════");
307    println!("Lazy Operation 16: into_iter (for loop)");
308    println!("═══════════════════════════════════════════════════════════════\n");
309
310    println!("  High-value products (>$300):");
311    for product in LazyQuery::new(&products)
312        .where_(Product::price_r(), |&p| p > 300.0)
313        .take_lazy(5)
314    {
315        println!("    • {}: ${:.2}", product.name, product.price);
316    }
317
318    // ============================================================================
319    // LAZY OPERATION 16: map_items - Transform
320    // ============================================================================
321    println!("\n═══════════════════════════════════════════════════════════════");
322    println!("Lazy Operation 17: map_items (transformation)");
323    println!("═══════════════════════════════════════════════════════════════\n");
324
325    let price_tags: Vec<String> = LazyQuery::new(&products)
326        .where_(Product::category_r(), |cat| cat == "Electronics")
327        .map_items(|p| format!("{}: ${:.2}", p.name, p.price))
328        .take(5)
329        .collect();
330
331    println!("  Electronics price tags:");
332    for tag in &price_tags {
333        println!("    • {}", tag);
334    }
335
336    // ============================================================================
337    // COMPLEX EXAMPLE: Multi-Stage Lazy Pipeline
338    // ============================================================================
339    println!("\n═══════════════════════════════════════════════════════════════");
340    println!("Complex Example: Multi-stage lazy pipeline");
341    println!("═══════════════════════════════════════════════════════════════\n");
342
343    println!("Building complex query:");
344    println!("  1. Filter by category (Electronics)");
345    println!("  2. Filter by price range ($50-$500)");
346    println!("  3. Filter by rating (>4.5)");
347    println!("  4. Select names");
348    println!("  5. Take first 3");
349    println!();
350
351    let results: Vec<String> = LazyQuery::new(&products)
352        .where_(Product::category_r(), |cat| cat == "Electronics")
353        .where_(Product::price_r(), |&p| p >= 50.0 && p <= 500.0)
354        .where_(Product::rating_r(), |&r| r > 4.5)
355        .select_lazy(Product::name_r())
356        .take(3)
357        .collect();
358
359    println!("  Results:");
360    for (i, name) in results.iter().enumerate() {
361        println!("    {}. {}", i + 1, name);
362    }
363    println!("  ✅ All operations fused and executed lazily!");
364
365    // ============================================================================
366    // THREAD-SAFE UPDATES WITH RWLOCK
367    // ============================================================================
368    println!("\n═══════════════════════════════════════════════════════════════");
369    println!("Bonus: Thread-safe updates with RwLock");
370    println!("═══════════════════════════════════════════════════════════════\n");
371
372    // Update a product through the Arc<RwLock>
373    if let Some(product_arc) = product_map.get("PROD-002") {
374        println!("Updating PROD-002 stock...");
375        
376        // Write lock for mutation
377        if let Ok(mut product) = product_arc.write() {
378            let old_stock = product.stock;
379            product.stock = 25;
380            println!("  Stock updated: {} → {}", old_stock, product.stock);
381        }
382    }
383
384    // Query again to see the update
385    let updated_products = extract_products(&product_map);
386    let mouse = LazyQuery::new(&updated_products)
387        .find(|p| p.id == 2);
388
389    if let Some(product) = mouse {
390        println!("  Verified update: {} now has {} in stock", product.name, product.stock);
391    }
392
393    // ============================================================================
394    // PRACTICAL EXAMPLE: Price Analysis by Category
395    // ============================================================================
396    println!("\n═══════════════════════════════════════════════════════════════");
397    println!("Practical Example: Price analysis by category");
398    println!("═══════════════════════════════════════════════════════════════\n");
399
400    let categories = vec!["Electronics", "Furniture"];
401
402    for category in categories {
403        println!("  {} Statistics:", category);
404        
405        // Filter products by category first
406        let cat_products: Vec<Product> = products.iter()
407            .filter(|p| p.category == category)
408            .cloned()
409            .collect();
410
411        let count = LazyQuery::new(&cat_products).count();
412        let total = LazyQuery::new(&cat_products).sum_by(Product::price_r());
413        let avg = LazyQuery::new(&cat_products).avg_by(Product::price_r()).unwrap_or(0.0);
414        let min = LazyQuery::new(&cat_products).min_by_float(Product::price_r()).unwrap_or(0.0);
415        let max = LazyQuery::new(&cat_products).max_by_float(Product::price_r()).unwrap_or(0.0);
416
417        println!("    Count: {}", count);
418        println!("    Total: ${:.2}", total);
419        println!("    Average: ${:.2}", avg);
420        println!("    Range: ${:.2} - ${:.2}\n", min, max);
421    }
422
423    // ============================================================================
424    // COMBINING WITH HASHMAP OPERATIONS
425    // ============================================================================
426    println!("═══════════════════════════════════════════════════════════════");
427    println!("HashMap Integration: Query by key patterns");
428    println!("═══════════════════════════════════════════════════════════════\n");
429
430    // Filter HashMap by key pattern
431    let electronics_keys: Vec<String> = product_map
432        .iter()
433        .filter(|(_key, value)| {
434            // Read the value to check category
435            if let Ok(guard) = value.read() {
436                guard.category == "Electronics"
437            } else {
438                false
439            }
440        })
441        .map(|(key, _value)| key.clone())
442        .collect();
443
444    println!("  Electronics product IDs:");
445    for key in electronics_keys.iter().take(5) {
446        println!("    • {}", key);
447    }
448
449    // ============================================================================
450    // PERFORMANCE DEMONSTRATION
451    // ============================================================================
452    println!("\n═══════════════════════════════════════════════════════════════");
453    println!("Performance: Lazy vs Eager comparison");
454    println!("═══════════════════════════════════════════════════════════════\n");
455
456    println!("Scenario: Find first product with rating > 4.7 from {} products\n", products.len());
457
458    println!("  Eager approach (hypothetical):");
459    println!("    - Filter all {} products", products.len());
460    println!("    - Collect filtered results");
461    println!("    - Take first item");
462    println!("    - Wasted work: Check all items\n");
463
464    println!("  Lazy approach (actual):");
465    let _first_rated = LazyQuery::new(&products)
466        .where_(Product::rating_r(), |&r| r > 4.7)
467        .first();
468    println!("    - Starts checking products");
469    println!("    - Stops at first match");
470    println!("    - ✅ Early termination - checks ~3-5 items only!");
471
472    // ============================================================================
473    // Summary
474    // ============================================================================
475    println!("\n╔══════════════════════════════════════════════════════════════════╗");
476    println!("║  Summary: All Lazy Operations Demonstrated                      ║");
477    println!("╚══════════════════════════════════════════════════════════════════╝\n");
478
479    println!("✅ Lazy Query Operations:");
480    println!("   1. ✅ where_ - Lazy filtering");
481    println!("   2. ✅ select_lazy - Lazy projection");
482    println!("   3. ✅ take_lazy - Early termination");
483    println!("   4. ✅ skip_lazy - Pagination");
484    println!("   5. ✅ first - Short-circuit search");
485    println!("   6. ✅ any - Existence check (short-circuit)");
486    println!("   7. ✅ count - Count items");
487    println!("   8. ✅ sum_by - Sum aggregation");
488    println!("   9. ✅ avg_by - Average aggregation");
489    println!("   10. ✅ min_by_float - Minimum value");
490    println!("   11. ✅ max_by_float - Maximum value");
491    println!("   12. ✅ find - Find with predicate (short-circuit)");
492    println!("   13. ✅ for_each - Iteration");
493    println!("   14. ✅ fold - Custom aggregation");
494    println!("   15. ✅ all_match - Validation (short-circuit)");
495    println!("   16. ✅ into_iter - For loop support");
496    println!("   17. ✅ map_items - Transformation\n");
497
498    println!("✅ Arc<RwLock<T>> Benefits:");
499    println!("   • Thread-safe shared access");
500    println!("   • Interior mutability");
501    println!("   • Multiple readers, single writer");
502    println!("   • Reference counting (Arc)");
503    println!("   • Can be queried after extracting data\n");
504
505    println!("✅ HashMap<K, Arc<RwLock<V>>> Benefits:");
506    println!("   • Fast key-based lookup");
507    println!("   • Thread-safe value access");
508    println!("   • Can query all values");
509    println!("   • Can filter by key patterns");
510    println!("   • Perfect for shared state/caches\n");
511
512    println!("🎯 Use Cases:");
513    println!("   • Shared product catalogs");
514    println!("   • User session stores");
515    println!("   • Configuration caches");
516    println!("   • Real-time inventory systems");
517    println!("   • Multi-threaded data processing");
518    println!("   • Web server state management\n");
519
520    println!("✓ Arc<RwLock<T>> HashMap with all lazy operations demo complete!\n");
521}
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);
Examples found in repository?
examples/arc_rwlock_hashmap.rs (line 299)
59fn main() {
60    println!("\n╔══════════════════════════════════════════════════════════════════╗");
61    println!("║  Arc<RwLock<T>> HashMap Lazy Query Demo                         ║");
62    println!("║  Thread-safe shared data with lazy evaluation                   ║");
63    println!("╚══════════════════════════════════════════════════════════════════╝\n");
64
65    let product_map = create_sample_data();
66    println!("Created product catalog:");
67    println!("  Total products: {}", product_map.len());
68    println!("  Keys: {:?}\n", product_map.keys().take(3).collect::<Vec<_>>());
69
70    // Extract products for querying
71    let products = extract_products(&product_map);
72    println!("Extracted {} products from Arc<RwLock<Product>>\n", products.len());
73
74    // ============================================================================
75    // LAZY OPERATION 1: where_ - Lazy Filtering
76    // ============================================================================
77    println!("═══════════════════════════════════════════════════════════════");
78    println!("Lazy Operation 1: where_ (filtering)");
79    println!("═══════════════════════════════════════════════════════════════\n");
80
81    println!("Building filtered query (nothing executes yet)...");
82    let electronics_query = LazyQuery::new(&products)
83        .where_(Product::category_r(), |cat| cat == "Electronics")
84        .where_(Product::active_r(), |&active| active)
85        .where_(Product::stock_r(), |&stock| stock > 20);
86
87    println!("  ✅ Query built (deferred execution)\n");
88
89    println!("Collecting results (executes now)...");
90    let electronics: Vec<_> = electronics_query.collect();
91    println!("  Found {} electronics in stock", electronics.len());
92    for p in &electronics {
93        println!("    • {}: {} in stock", p.name, p.stock);
94    }
95
96    // ============================================================================
97    // LAZY OPERATION 2: select_lazy - Lazy Projection
98    // ============================================================================
99    println!("\n═══════════════════════════════════════════════════════════════");
100    println!("Lazy Operation 2: select_lazy (projection)");
101    println!("═══════════════════════════════════════════════════════════════\n");
102
103    println!("Selecting product names (lazy)...");
104    let names: Vec<String> = LazyQuery::new(&products)
105        .where_(Product::category_r(), |cat| cat == "Furniture")
106        .select_lazy(Product::name_r())
107        .collect();
108
109    println!("  Furniture names ({}):", names.len());
110    for name in &names {
111        println!("    • {}", name);
112    }
113
114    // ============================================================================
115    // LAZY OPERATION 3: take_lazy - Early Termination
116    // ============================================================================
117    println!("\n═══════════════════════════════════════════════════════════════");
118    println!("Lazy Operation 3: take_lazy (early termination)");
119    println!("═══════════════════════════════════════════════════════════════\n");
120
121    println!("Getting first 3 electronics...");
122    let first_3: Vec<_> = LazyQuery::new(&products)
123        .where_(Product::category_r(), |cat| cat == "Electronics")
124        .take_lazy(3)
125        .collect();
126
127    println!("  First 3 electronics:");
128    for (i, p) in first_3.iter().enumerate() {
129        println!("    {}. {} - ${:.2}", i + 1, p.name, p.price);
130    }
131    println!("  ✅ Stopped after finding 3 items!");
132
133    // ============================================================================
134    // LAZY OPERATION 4: skip_lazy - Pagination
135    // ============================================================================
136    println!("\n═══════════════════════════════════════════════════════════════");
137    println!("Lazy Operation 4: skip_lazy (pagination)");
138    println!("═══════════════════════════════════════════════════════════════\n");
139
140    println!("Getting page 2 (skip 3, take 3)...");
141    let page_2: Vec<_> = LazyQuery::new(&products)
142        .where_(Product::active_r(), |&active| active)
143        .skip_lazy(3)
144        .take_lazy(3)
145        .collect();
146
147    println!("  Page 2 items:");
148    for (i, p) in page_2.iter().enumerate() {
149        println!("    {}. {}", i + 4, p.name);
150    }
151
152    // ============================================================================
153    // LAZY OPERATION 5: first - Short-Circuit Search
154    // ============================================================================
155    println!("\n═══════════════════════════════════════════════════════════════");
156    println!("Lazy Operation 5: first (short-circuit)");
157    println!("═══════════════════════════════════════════════════════════════\n");
158
159    println!("Finding first expensive item (>$1000)...");
160    let expensive = LazyQuery::new(&products)
161        .where_(Product::price_r(), |&price| price > 1000.0)
162        .first();
163
164    match expensive {
165        Some(p) => println!("  Found: {} - ${:.2}", p.name, p.price),
166        None => println!("  Not found"),
167    }
168    println!("  ✅ Stopped at first match!");
169
170    // ============================================================================
171    // LAZY OPERATION 6: any - Existence Check
172    // ============================================================================
173    println!("\n═══════════════════════════════════════════════════════════════");
174    println!("Lazy Operation 6: any (existence check)");
175    println!("═══════════════════════════════════════════════════════════════\n");
176
177    println!("Checking if any furniture exists...");
178    let has_furniture = LazyQuery::new(&products)
179        .where_(Product::category_r(), |cat| cat == "Furniture")
180        .any();
181
182    println!("  Has furniture: {}", has_furniture);
183    println!("  ✅ Stopped immediately after finding first match!");
184
185    // ============================================================================
186    // LAZY OPERATION 7: count - Count Matching Items
187    // ============================================================================
188    println!("\n═══════════════════════════════════════════════════════════════");
189    println!("Lazy Operation 7: count");
190    println!("═══════════════════════════════════════════════════════════════\n");
191
192    let electronics_count = LazyQuery::new(&products)
193        .where_(Product::category_r(), |cat| cat == "Electronics")
194        .count();
195
196    println!("  Electronics count: {}", electronics_count);
197
198    // ============================================================================
199    // LAZY OPERATION 8: sum_by - Aggregation
200    // ============================================================================
201    println!("\n═══════════════════════════════════════════════════════════════");
202    println!("Lazy Operation 8: sum_by (aggregation)");
203    println!("═══════════════════════════════════════════════════════════════\n");
204
205    let total_value: f64 = LazyQuery::new(&products)
206        .where_(Product::category_r(), |cat| cat == "Electronics")
207        .sum_by(Product::price_r());
208
209    println!("  Total electronics value: ${:.2}", total_value);
210
211    // ============================================================================
212    // LAZY OPERATION 9: avg_by - Average
213    // ============================================================================
214    println!("\n═══════════════════════════════════════════════════════════════");
215    println!("Lazy Operation 9: avg_by");
216    println!("═══════════════════════════════════════════════════════════════\n");
217
218    let avg_price = LazyQuery::new(&products)
219        .where_(Product::category_r(), |cat| cat == "Furniture")
220        .avg_by(Product::price_r())
221        .unwrap_or(0.0);
222
223    println!("  Average furniture price: ${:.2}", avg_price);
224
225    // ============================================================================
226    // LAZY OPERATION 10: min_by_float / max_by_float
227    // ============================================================================
228    println!("\n═══════════════════════════════════════════════════════════════");
229    println!("Lazy Operation 10: min_by_float / max_by_float");
230    println!("═══════════════════════════════════════════════════════════════\n");
231
232    let min_price = LazyQuery::new(&products)
233        .where_(Product::active_r(), |&active| active)
234        .min_by_float(Product::price_r())
235        .unwrap_or(0.0);
236
237    let max_price = LazyQuery::new(&products)
238        .where_(Product::active_r(), |&active| active)
239        .max_by_float(Product::price_r())
240        .unwrap_or(0.0);
241
242    println!("  Price range for active products:");
243    println!("    Min: ${:.2}", min_price);
244    println!("    Max: ${:.2}", max_price);
245
246    // ============================================================================
247    // LAZY OPERATION 11: find - Find with Predicate
248    // ============================================================================
249    println!("\n═══════════════════════════════════════════════════════════════");
250    println!("Lazy Operation 11: find (with predicate)");
251    println!("═══════════════════════════════════════════════════════════════\n");
252
253    let high_rated = LazyQuery::new(&products)
254        .where_(Product::category_r(), |cat| cat == "Electronics")
255        .find(|item| item.rating > 4.7);
256
257    if let Some(product) = high_rated {
258        println!("  First highly-rated electronic:");
259        println!("    {}: Rating {:.1}", product.name, product.rating);
260    }
261
262    // ============================================================================
263    // LAZY OPERATION 12: for_each - Iteration
264    // ============================================================================
265    println!("\n═══════════════════════════════════════════════════════════════");
266    println!("Lazy Operation 12: for_each (iteration)");
267    println!("═══════════════════════════════════════════════════════════════\n");
268
269    println!("  Low stock alerts:");
270    LazyQuery::new(&products)
271        .where_(Product::stock_r(), |&stock| stock < 20)
272        .for_each(|product| {
273            println!("    ⚠️  {}: Only {} in stock", product.name, product.stock);
274        });
275
276    // ============================================================================
277    // LAZY OPERATION 13: fold - Custom Aggregation
278    // ============================================================================
279    println!("\n═══════════════════════════════════════════════════════════════");
280    println!("Lazy Operation 14: fold (custom aggregation)");
281    println!("═══════════════════════════════════════════════════════════════\n");
282
283    let total_inventory_value = LazyQuery::new(&products)
284        .where_(Product::active_r(), |&active| active)
285        .fold(0.0, |acc, product| {
286            acc + (product.price * product.stock as f64)
287        });
288
289    println!("  Total inventory value: ${:.2}", total_inventory_value);
290
291    // ============================================================================
292    // LAZY OPERATION 14: all_match - Validation
293    // ============================================================================
294    println!("\n═══════════════════════════════════════════════════════════════");
295    println!("Lazy Operation 15: all_match (validation)");
296    println!("═══════════════════════════════════════════════════════════════\n");
297
298    let all_priced = LazyQuery::new(&products)
299        .all_match(|item| item.price > 0.0);
300
301    println!("  All products have valid prices: {}", all_priced);
302
303    // ============================================================================
304    // LAZY OPERATION 15: into_iter - For Loop
305    // ============================================================================
306    println!("\n═══════════════════════════════════════════════════════════════");
307    println!("Lazy Operation 16: into_iter (for loop)");
308    println!("═══════════════════════════════════════════════════════════════\n");
309
310    println!("  High-value products (>$300):");
311    for product in LazyQuery::new(&products)
312        .where_(Product::price_r(), |&p| p > 300.0)
313        .take_lazy(5)
314    {
315        println!("    • {}: ${:.2}", product.name, product.price);
316    }
317
318    // ============================================================================
319    // LAZY OPERATION 16: map_items - Transform
320    // ============================================================================
321    println!("\n═══════════════════════════════════════════════════════════════");
322    println!("Lazy Operation 17: map_items (transformation)");
323    println!("═══════════════════════════════════════════════════════════════\n");
324
325    let price_tags: Vec<String> = LazyQuery::new(&products)
326        .where_(Product::category_r(), |cat| cat == "Electronics")
327        .map_items(|p| format!("{}: ${:.2}", p.name, p.price))
328        .take(5)
329        .collect();
330
331    println!("  Electronics price tags:");
332    for tag in &price_tags {
333        println!("    • {}", tag);
334    }
335
336    // ============================================================================
337    // COMPLEX EXAMPLE: Multi-Stage Lazy Pipeline
338    // ============================================================================
339    println!("\n═══════════════════════════════════════════════════════════════");
340    println!("Complex Example: Multi-stage lazy pipeline");
341    println!("═══════════════════════════════════════════════════════════════\n");
342
343    println!("Building complex query:");
344    println!("  1. Filter by category (Electronics)");
345    println!("  2. Filter by price range ($50-$500)");
346    println!("  3. Filter by rating (>4.5)");
347    println!("  4. Select names");
348    println!("  5. Take first 3");
349    println!();
350
351    let results: Vec<String> = LazyQuery::new(&products)
352        .where_(Product::category_r(), |cat| cat == "Electronics")
353        .where_(Product::price_r(), |&p| p >= 50.0 && p <= 500.0)
354        .where_(Product::rating_r(), |&r| r > 4.5)
355        .select_lazy(Product::name_r())
356        .take(3)
357        .collect();
358
359    println!("  Results:");
360    for (i, name) in results.iter().enumerate() {
361        println!("    {}. {}", i + 1, name);
362    }
363    println!("  ✅ All operations fused and executed lazily!");
364
365    // ============================================================================
366    // THREAD-SAFE UPDATES WITH RWLOCK
367    // ============================================================================
368    println!("\n═══════════════════════════════════════════════════════════════");
369    println!("Bonus: Thread-safe updates with RwLock");
370    println!("═══════════════════════════════════════════════════════════════\n");
371
372    // Update a product through the Arc<RwLock>
373    if let Some(product_arc) = product_map.get("PROD-002") {
374        println!("Updating PROD-002 stock...");
375        
376        // Write lock for mutation
377        if let Ok(mut product) = product_arc.write() {
378            let old_stock = product.stock;
379            product.stock = 25;
380            println!("  Stock updated: {} → {}", old_stock, product.stock);
381        }
382    }
383
384    // Query again to see the update
385    let updated_products = extract_products(&product_map);
386    let mouse = LazyQuery::new(&updated_products)
387        .find(|p| p.id == 2);
388
389    if let Some(product) = mouse {
390        println!("  Verified update: {} now has {} in stock", product.name, product.stock);
391    }
392
393    // ============================================================================
394    // PRACTICAL EXAMPLE: Price Analysis by Category
395    // ============================================================================
396    println!("\n═══════════════════════════════════════════════════════════════");
397    println!("Practical Example: Price analysis by category");
398    println!("═══════════════════════════════════════════════════════════════\n");
399
400    let categories = vec!["Electronics", "Furniture"];
401
402    for category in categories {
403        println!("  {} Statistics:", category);
404        
405        // Filter products by category first
406        let cat_products: Vec<Product> = products.iter()
407            .filter(|p| p.category == category)
408            .cloned()
409            .collect();
410
411        let count = LazyQuery::new(&cat_products).count();
412        let total = LazyQuery::new(&cat_products).sum_by(Product::price_r());
413        let avg = LazyQuery::new(&cat_products).avg_by(Product::price_r()).unwrap_or(0.0);
414        let min = LazyQuery::new(&cat_products).min_by_float(Product::price_r()).unwrap_or(0.0);
415        let max = LazyQuery::new(&cat_products).max_by_float(Product::price_r()).unwrap_or(0.0);
416
417        println!("    Count: {}", count);
418        println!("    Total: ${:.2}", total);
419        println!("    Average: ${:.2}", avg);
420        println!("    Range: ${:.2} - ${:.2}\n", min, max);
421    }
422
423    // ============================================================================
424    // COMBINING WITH HASHMAP OPERATIONS
425    // ============================================================================
426    println!("═══════════════════════════════════════════════════════════════");
427    println!("HashMap Integration: Query by key patterns");
428    println!("═══════════════════════════════════════════════════════════════\n");
429
430    // Filter HashMap by key pattern
431    let electronics_keys: Vec<String> = product_map
432        .iter()
433        .filter(|(_key, value)| {
434            // Read the value to check category
435            if let Ok(guard) = value.read() {
436                guard.category == "Electronics"
437            } else {
438                false
439            }
440        })
441        .map(|(key, _value)| key.clone())
442        .collect();
443
444    println!("  Electronics product IDs:");
445    for key in electronics_keys.iter().take(5) {
446        println!("    • {}", key);
447    }
448
449    // ============================================================================
450    // PERFORMANCE DEMONSTRATION
451    // ============================================================================
452    println!("\n═══════════════════════════════════════════════════════════════");
453    println!("Performance: Lazy vs Eager comparison");
454    println!("═══════════════════════════════════════════════════════════════\n");
455
456    println!("Scenario: Find first product with rating > 4.7 from {} products\n", products.len());
457
458    println!("  Eager approach (hypothetical):");
459    println!("    - Filter all {} products", products.len());
460    println!("    - Collect filtered results");
461    println!("    - Take first item");
462    println!("    - Wasted work: Check all items\n");
463
464    println!("  Lazy approach (actual):");
465    let _first_rated = LazyQuery::new(&products)
466        .where_(Product::rating_r(), |&r| r > 4.7)
467        .first();
468    println!("    - Starts checking products");
469    println!("    - Stops at first match");
470    println!("    - ✅ Early termination - checks ~3-5 items only!");
471
472    // ============================================================================
473    // Summary
474    // ============================================================================
475    println!("\n╔══════════════════════════════════════════════════════════════════╗");
476    println!("║  Summary: All Lazy Operations Demonstrated                      ║");
477    println!("╚══════════════════════════════════════════════════════════════════╝\n");
478
479    println!("✅ Lazy Query Operations:");
480    println!("   1. ✅ where_ - Lazy filtering");
481    println!("   2. ✅ select_lazy - Lazy projection");
482    println!("   3. ✅ take_lazy - Early termination");
483    println!("   4. ✅ skip_lazy - Pagination");
484    println!("   5. ✅ first - Short-circuit search");
485    println!("   6. ✅ any - Existence check (short-circuit)");
486    println!("   7. ✅ count - Count items");
487    println!("   8. ✅ sum_by - Sum aggregation");
488    println!("   9. ✅ avg_by - Average aggregation");
489    println!("   10. ✅ min_by_float - Minimum value");
490    println!("   11. ✅ max_by_float - Maximum value");
491    println!("   12. ✅ find - Find with predicate (short-circuit)");
492    println!("   13. ✅ for_each - Iteration");
493    println!("   14. ✅ fold - Custom aggregation");
494    println!("   15. ✅ all_match - Validation (short-circuit)");
495    println!("   16. ✅ into_iter - For loop support");
496    println!("   17. ✅ map_items - Transformation\n");
497
498    println!("✅ Arc<RwLock<T>> Benefits:");
499    println!("   • Thread-safe shared access");
500    println!("   • Interior mutability");
501    println!("   • Multiple readers, single writer");
502    println!("   • Reference counting (Arc)");
503    println!("   • Can be queried after extracting data\n");
504
505    println!("✅ HashMap<K, Arc<RwLock<V>>> Benefits:");
506    println!("   • Fast key-based lookup");
507    println!("   • Thread-safe value access");
508    println!("   • Can query all values");
509    println!("   • Can filter by key patterns");
510    println!("   • Perfect for shared state/caches\n");
511
512    println!("🎯 Use Cases:");
513    println!("   • Shared product catalogs");
514    println!("   • User session stores");
515    println!("   • Configuration caches");
516    println!("   • Real-time inventory systems");
517    println!("   • Multi-threaded data processing");
518    println!("   • Web server state management\n");
519
520    println!("✓ Arc<RwLock<T>> HashMap with all lazy operations demo complete!\n");
521}
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, I> LazyQuery<'a, T, I>
where T: 'static, 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());
Examples found in repository?
examples/individual_crates.rs (line 116)
27fn main() {
28    println!("Individual Crates Example");
29    println!("=========================\n");
30    println!("Using rust-queries-core + rust-queries-derive directly\n");
31
32    let products = vec![
33        Product {
34            id: 1,
35            name: "Laptop".to_string(),
36            price: 999.99,
37            category: "Electronics".to_string(),
38            stock: 5,
39        },
40        Product {
41            id: 2,
42            name: "Mouse".to_string(),
43            price: 29.99,
44            category: "Electronics".to_string(),
45            stock: 50,
46        },
47        Product {
48            id: 3,
49            name: "Keyboard".to_string(),
50            price: 79.99,
51            category: "Electronics".to_string(),
52            stock: 30,
53        },
54        Product {
55            id: 4,
56            name: "Monitor".to_string(),
57            price: 299.99,
58            category: "Electronics".to_string(),
59            stock: 12,
60        },
61        Product {
62            id: 5,
63            name: "Desk Chair".to_string(),
64            price: 199.99,
65            category: "Furniture".to_string(),
66            stock: 8,
67        },
68    ];
69
70    println!("1. QueryExt from rust_queries_core");
71    println!("   products.query().where_(price > 100).all()");
72    
73    let query = products
74        .query()  // From QueryExt trait
75        .where_(Product::price_r(), |&p| p > 100.0);
76    let expensive = query.all();
77    
78    println!("   Found {} expensive products:", expensive.len());
79    for product in expensive {
80        println!("   - {} (${:.2})", product.name, product.price);
81    }
82    println!();
83
84    println!("2. QueryBuilder from rust_queries_derive");
85    println!("   Product::query(&products).where_(stock < 10).all()");
86    
87    let query2 = Product::query(&products)  // From QueryBuilder derive
88        .where_(Product::stock_r(), |&s| s < 10);
89    let low_stock = query2.all();
90    
91    println!("   Found {} low stock products:", low_stock.len());
92    for product in low_stock {
93        println!("   - {} (stock: {})", product.name, product.stock);
94    }
95    println!();
96
97    println!("3. LazyQuery from rust_queries_core");
98    println!("   products.lazy_query().where_(...).collect()");
99    
100    let electronics: Vec<_> = products
101        .lazy_query()  // From QueryExt trait
102        .where_(Product::category_r(), |cat| cat == "Electronics")
103        .collect();
104    
105    println!("   Found {} electronics:", electronics.len());
106    for product in electronics {
107        println!("   - {}", product.name);
108    }
109    println!();
110
111    println!("4. Aggregations with LazyQuery");
112    println!("   products.lazy_query().sum_by(Product::price_r())");
113    
114    let total_value: f64 = products
115        .lazy_query()
116        .sum_by(Product::price_r());
117    
118    println!("   Total inventory value: ${:.2}", total_value);
119    println!();
120
121    println!("5. Early termination with lazy queries");
122    println!("   products.lazy_query().where_(...).first()");
123    
124    if let Some(first_cheap) = products
125        .lazy_query()
126        .where_(Product::price_r(), |&p| p < 50.0)
127        .first()
128    {
129        println!("   First cheap product: {} (${:.2})", first_cheap.name, first_cheap.price);
130    }
131    println!();
132
133    println!("6. Using Query (eager) from rust_queries_core");
134    println!("   Query::new(&products).where_(...).count()");
135    
136    let query3 = Query::new(&products)  // Traditional approach
137        .where_(Product::price_r(), |&p| p > 50.0);
138    let count = query3.count();
139    
140    println!("   Products over $50: {}", count);
141    println!();
142
143    println!("Summary:");
144    println!("--------");
145    println!("✓ rust_queries_core provides: Query, LazyQuery, QueryExt");
146    println!("✓ rust_queries_derive provides: #[derive(QueryBuilder)]");
147    println!("✓ key_paths_derive provides: #[derive(Keypaths)]");
148    println!("✓ All features work with individual crates!");
149}
More examples
Hide additional examples
examples/derive_and_ext.rs (line 142)
13fn main() {
14    println!("Derive Macros and Extension Traits Example");
15    println!("===========================================\n");
16
17    let products = vec![
18        Product {
19            id: 1,
20            name: "Laptop".to_string(),
21            price: 999.99,
22            category: "Electronics".to_string(),
23            stock: 5,
24        },
25        Product {
26            id: 2,
27            name: "Mouse".to_string(),
28            price: 29.99,
29            category: "Electronics".to_string(),
30            stock: 50,
31        },
32        Product {
33            id: 3,
34            name: "Keyboard".to_string(),
35            price: 79.99,
36            category: "Electronics".to_string(),
37            stock: 30,
38        },
39        Product {
40            id: 4,
41            name: "Monitor".to_string(),
42            price: 299.99,
43            category: "Electronics".to_string(),
44            stock: 12,
45        },
46        Product {
47            id: 5,
48            name: "Desk Chair".to_string(),
49            price: 199.99,
50            category: "Furniture".to_string(),
51            stock: 8,
52        },
53    ];
54
55    println!("1. Using Extension Trait - Direct .query() on Vec");
56    println!("   Query: products.query().where_(price > 100).all()");
57    
58    let query = products
59        .query()
60        .where_(Product::price_r(), |&p| p > 100.0);
61    let expensive = query.all();
62    
63    println!("   Found {} expensive products:", expensive.len());
64    for product in &expensive {
65        println!("   - {} (${:.2})", product.name, product.price);
66    }
67    println!();
68
69    println!("2. Using Extension Trait - Direct .lazy_query() on Vec");
70    println!("   Query: products.lazy_query().where_(stock < 10).collect()");
71    
72    let low_stock: Vec<_> = products
73        .lazy_query()
74        .where_(Product::stock_r(), |&s| s < 10)
75        .collect();
76    
77    println!("   Found {} low stock products:", low_stock.len());
78    for product in &low_stock {
79        println!("   - {} (stock: {})", product.name, product.stock);
80    }
81    println!();
82
83    println!("3. Using Extension Trait - Chained Operations");
84    println!("   Query: products.lazy_query().where_(category == Electronics).take(2).select(name).collect()");
85    
86    let names: Vec<String> = products
87        .lazy_query()
88        .where_(Product::category_r(), |cat| cat == "Electronics")
89        .take_lazy(2)
90        .select_lazy(Product::name_r())
91        .collect();
92    
93    println!("   First 2 electronics:");
94    for name in &names {
95        println!("   - {}", name);
96    }
97    println!();
98
99    println!("4. Using QueryBuilder Derive - Static Methods");
100    println!("   Query: Product::query(&products).where_(price > 50).count()");
101    
102    let query4 = Product::query(&products)
103        .where_(Product::price_r(), |&p| p > 50.0);
104    let count = query4.count();
105    
106    println!("   Products over $50: {}", count);
107    println!();
108
109    println!("5. Using QueryBuilder Derive - Lazy Static Methods");
110    println!("   Query: Product::lazy_query(&products).first()");
111    
112    if let Some(first) = Product::lazy_query(&products).first() {
113        println!("   First product: {} (${:.2})", first.name, first.price);
114    }
115    println!();
116
117    println!("6. Complex Chain with Extension Trait");
118    println!("   Query: products.lazy_query()");
119    println!("          .where_(category == Electronics)");
120    println!("          .where_(price < 500)");
121    println!("          .map(|p| format!(\"{{}} - ${{:.2}}\", p.name, p.price))");
122    println!("          .collect()");
123    
124    let formatted: Vec<String> = products
125        .lazy_query()
126        .where_(Product::category_r(), |cat| cat == "Electronics")
127        .where_(Product::price_r(), |&p| p < 500.0)
128        .map_items(|p| format!("{} - ${:.2}", p.name, p.price))
129        .collect();
130    
131    println!("   Affordable electronics:");
132    for item in &formatted {
133        println!("   - {}", item);
134    }
135    println!();
136
137    println!("7. Aggregation with Extension Trait");
138    println!("   Query: products.lazy_query().sum_by(Product::stock())");
139    
140    let total_stock = products
141        .lazy_query()
142        .sum_by(Product::stock_r());
143    
144    println!("   Total stock across all products: {}", total_stock);
145    println!();
146
147    println!("8. Find with Extension Trait");
148    println!("   Query: products.lazy_query().find(|p| p.name.contains(\"Chair\"))");
149    
150    if let Some(chair) = products.lazy_query().find(|p| p.name.contains("Chair")) {
151        println!("   Found: {} in {}", chair.name, chair.category);
152    }
153    println!();
154
155    println!("9. Early Termination with Extension Trait");
156    println!("   Query: products.lazy_query().where_(price > 1000).any()");
157    
158    let has_luxury = products
159        .lazy_query()
160        .where_(Product::price_r(), |&p| p > 1000.0)
161        .any();
162    
163    println!("   Has products over $1000: {}", has_luxury);
164    println!();
165
166    println!("10. Slice Extension Trait");
167    println!("    Query: (&products[..]).lazy_query().count()");
168    
169    let slice_count = (&products[..])
170        .lazy_query()
171        .count();
172    
173    println!("    Count from slice: {}", slice_count);
174    println!();
175
176    println!("Summary:");
177    println!("--------");
178    println!("✓ Extension trait QueryExt adds .query() and .lazy_query() to containers");
179    println!("✓ Derive macro QueryBuilder adds static methods Product::query() and Product::lazy_query()");
180    println!("✓ Both approaches provide the same query functionality");
181    println!("✓ Extension trait is more ergonomic: products.query() vs Query::new(&products)");
182    println!("✓ All iterator optimizations (fusion, early termination) still apply");
183}
examples/arc_rwlock_hashmap.rs (line 207)
59fn main() {
60    println!("\n╔══════════════════════════════════════════════════════════════════╗");
61    println!("║  Arc<RwLock<T>> HashMap Lazy Query Demo                         ║");
62    println!("║  Thread-safe shared data with lazy evaluation                   ║");
63    println!("╚══════════════════════════════════════════════════════════════════╝\n");
64
65    let product_map = create_sample_data();
66    println!("Created product catalog:");
67    println!("  Total products: {}", product_map.len());
68    println!("  Keys: {:?}\n", product_map.keys().take(3).collect::<Vec<_>>());
69
70    // Extract products for querying
71    let products = extract_products(&product_map);
72    println!("Extracted {} products from Arc<RwLock<Product>>\n", products.len());
73
74    // ============================================================================
75    // LAZY OPERATION 1: where_ - Lazy Filtering
76    // ============================================================================
77    println!("═══════════════════════════════════════════════════════════════");
78    println!("Lazy Operation 1: where_ (filtering)");
79    println!("═══════════════════════════════════════════════════════════════\n");
80
81    println!("Building filtered query (nothing executes yet)...");
82    let electronics_query = LazyQuery::new(&products)
83        .where_(Product::category_r(), |cat| cat == "Electronics")
84        .where_(Product::active_r(), |&active| active)
85        .where_(Product::stock_r(), |&stock| stock > 20);
86
87    println!("  ✅ Query built (deferred execution)\n");
88
89    println!("Collecting results (executes now)...");
90    let electronics: Vec<_> = electronics_query.collect();
91    println!("  Found {} electronics in stock", electronics.len());
92    for p in &electronics {
93        println!("    • {}: {} in stock", p.name, p.stock);
94    }
95
96    // ============================================================================
97    // LAZY OPERATION 2: select_lazy - Lazy Projection
98    // ============================================================================
99    println!("\n═══════════════════════════════════════════════════════════════");
100    println!("Lazy Operation 2: select_lazy (projection)");
101    println!("═══════════════════════════════════════════════════════════════\n");
102
103    println!("Selecting product names (lazy)...");
104    let names: Vec<String> = LazyQuery::new(&products)
105        .where_(Product::category_r(), |cat| cat == "Furniture")
106        .select_lazy(Product::name_r())
107        .collect();
108
109    println!("  Furniture names ({}):", names.len());
110    for name in &names {
111        println!("    • {}", name);
112    }
113
114    // ============================================================================
115    // LAZY OPERATION 3: take_lazy - Early Termination
116    // ============================================================================
117    println!("\n═══════════════════════════════════════════════════════════════");
118    println!("Lazy Operation 3: take_lazy (early termination)");
119    println!("═══════════════════════════════════════════════════════════════\n");
120
121    println!("Getting first 3 electronics...");
122    let first_3: Vec<_> = LazyQuery::new(&products)
123        .where_(Product::category_r(), |cat| cat == "Electronics")
124        .take_lazy(3)
125        .collect();
126
127    println!("  First 3 electronics:");
128    for (i, p) in first_3.iter().enumerate() {
129        println!("    {}. {} - ${:.2}", i + 1, p.name, p.price);
130    }
131    println!("  ✅ Stopped after finding 3 items!");
132
133    // ============================================================================
134    // LAZY OPERATION 4: skip_lazy - Pagination
135    // ============================================================================
136    println!("\n═══════════════════════════════════════════════════════════════");
137    println!("Lazy Operation 4: skip_lazy (pagination)");
138    println!("═══════════════════════════════════════════════════════════════\n");
139
140    println!("Getting page 2 (skip 3, take 3)...");
141    let page_2: Vec<_> = LazyQuery::new(&products)
142        .where_(Product::active_r(), |&active| active)
143        .skip_lazy(3)
144        .take_lazy(3)
145        .collect();
146
147    println!("  Page 2 items:");
148    for (i, p) in page_2.iter().enumerate() {
149        println!("    {}. {}", i + 4, p.name);
150    }
151
152    // ============================================================================
153    // LAZY OPERATION 5: first - Short-Circuit Search
154    // ============================================================================
155    println!("\n═══════════════════════════════════════════════════════════════");
156    println!("Lazy Operation 5: first (short-circuit)");
157    println!("═══════════════════════════════════════════════════════════════\n");
158
159    println!("Finding first expensive item (>$1000)...");
160    let expensive = LazyQuery::new(&products)
161        .where_(Product::price_r(), |&price| price > 1000.0)
162        .first();
163
164    match expensive {
165        Some(p) => println!("  Found: {} - ${:.2}", p.name, p.price),
166        None => println!("  Not found"),
167    }
168    println!("  ✅ Stopped at first match!");
169
170    // ============================================================================
171    // LAZY OPERATION 6: any - Existence Check
172    // ============================================================================
173    println!("\n═══════════════════════════════════════════════════════════════");
174    println!("Lazy Operation 6: any (existence check)");
175    println!("═══════════════════════════════════════════════════════════════\n");
176
177    println!("Checking if any furniture exists...");
178    let has_furniture = LazyQuery::new(&products)
179        .where_(Product::category_r(), |cat| cat == "Furniture")
180        .any();
181
182    println!("  Has furniture: {}", has_furniture);
183    println!("  ✅ Stopped immediately after finding first match!");
184
185    // ============================================================================
186    // LAZY OPERATION 7: count - Count Matching Items
187    // ============================================================================
188    println!("\n═══════════════════════════════════════════════════════════════");
189    println!("Lazy Operation 7: count");
190    println!("═══════════════════════════════════════════════════════════════\n");
191
192    let electronics_count = LazyQuery::new(&products)
193        .where_(Product::category_r(), |cat| cat == "Electronics")
194        .count();
195
196    println!("  Electronics count: {}", electronics_count);
197
198    // ============================================================================
199    // LAZY OPERATION 8: sum_by - Aggregation
200    // ============================================================================
201    println!("\n═══════════════════════════════════════════════════════════════");
202    println!("Lazy Operation 8: sum_by (aggregation)");
203    println!("═══════════════════════════════════════════════════════════════\n");
204
205    let total_value: f64 = LazyQuery::new(&products)
206        .where_(Product::category_r(), |cat| cat == "Electronics")
207        .sum_by(Product::price_r());
208
209    println!("  Total electronics value: ${:.2}", total_value);
210
211    // ============================================================================
212    // LAZY OPERATION 9: avg_by - Average
213    // ============================================================================
214    println!("\n═══════════════════════════════════════════════════════════════");
215    println!("Lazy Operation 9: avg_by");
216    println!("═══════════════════════════════════════════════════════════════\n");
217
218    let avg_price = LazyQuery::new(&products)
219        .where_(Product::category_r(), |cat| cat == "Furniture")
220        .avg_by(Product::price_r())
221        .unwrap_or(0.0);
222
223    println!("  Average furniture price: ${:.2}", avg_price);
224
225    // ============================================================================
226    // LAZY OPERATION 10: min_by_float / max_by_float
227    // ============================================================================
228    println!("\n═══════════════════════════════════════════════════════════════");
229    println!("Lazy Operation 10: min_by_float / max_by_float");
230    println!("═══════════════════════════════════════════════════════════════\n");
231
232    let min_price = LazyQuery::new(&products)
233        .where_(Product::active_r(), |&active| active)
234        .min_by_float(Product::price_r())
235        .unwrap_or(0.0);
236
237    let max_price = LazyQuery::new(&products)
238        .where_(Product::active_r(), |&active| active)
239        .max_by_float(Product::price_r())
240        .unwrap_or(0.0);
241
242    println!("  Price range for active products:");
243    println!("    Min: ${:.2}", min_price);
244    println!("    Max: ${:.2}", max_price);
245
246    // ============================================================================
247    // LAZY OPERATION 11: find - Find with Predicate
248    // ============================================================================
249    println!("\n═══════════════════════════════════════════════════════════════");
250    println!("Lazy Operation 11: find (with predicate)");
251    println!("═══════════════════════════════════════════════════════════════\n");
252
253    let high_rated = LazyQuery::new(&products)
254        .where_(Product::category_r(), |cat| cat == "Electronics")
255        .find(|item| item.rating > 4.7);
256
257    if let Some(product) = high_rated {
258        println!("  First highly-rated electronic:");
259        println!("    {}: Rating {:.1}", product.name, product.rating);
260    }
261
262    // ============================================================================
263    // LAZY OPERATION 12: for_each - Iteration
264    // ============================================================================
265    println!("\n═══════════════════════════════════════════════════════════════");
266    println!("Lazy Operation 12: for_each (iteration)");
267    println!("═══════════════════════════════════════════════════════════════\n");
268
269    println!("  Low stock alerts:");
270    LazyQuery::new(&products)
271        .where_(Product::stock_r(), |&stock| stock < 20)
272        .for_each(|product| {
273            println!("    ⚠️  {}: Only {} in stock", product.name, product.stock);
274        });
275
276    // ============================================================================
277    // LAZY OPERATION 13: fold - Custom Aggregation
278    // ============================================================================
279    println!("\n═══════════════════════════════════════════════════════════════");
280    println!("Lazy Operation 14: fold (custom aggregation)");
281    println!("═══════════════════════════════════════════════════════════════\n");
282
283    let total_inventory_value = LazyQuery::new(&products)
284        .where_(Product::active_r(), |&active| active)
285        .fold(0.0, |acc, product| {
286            acc + (product.price * product.stock as f64)
287        });
288
289    println!("  Total inventory value: ${:.2}", total_inventory_value);
290
291    // ============================================================================
292    // LAZY OPERATION 14: all_match - Validation
293    // ============================================================================
294    println!("\n═══════════════════════════════════════════════════════════════");
295    println!("Lazy Operation 15: all_match (validation)");
296    println!("═══════════════════════════════════════════════════════════════\n");
297
298    let all_priced = LazyQuery::new(&products)
299        .all_match(|item| item.price > 0.0);
300
301    println!("  All products have valid prices: {}", all_priced);
302
303    // ============================================================================
304    // LAZY OPERATION 15: into_iter - For Loop
305    // ============================================================================
306    println!("\n═══════════════════════════════════════════════════════════════");
307    println!("Lazy Operation 16: into_iter (for loop)");
308    println!("═══════════════════════════════════════════════════════════════\n");
309
310    println!("  High-value products (>$300):");
311    for product in LazyQuery::new(&products)
312        .where_(Product::price_r(), |&p| p > 300.0)
313        .take_lazy(5)
314    {
315        println!("    • {}: ${:.2}", product.name, product.price);
316    }
317
318    // ============================================================================
319    // LAZY OPERATION 16: map_items - Transform
320    // ============================================================================
321    println!("\n═══════════════════════════════════════════════════════════════");
322    println!("Lazy Operation 17: map_items (transformation)");
323    println!("═══════════════════════════════════════════════════════════════\n");
324
325    let price_tags: Vec<String> = LazyQuery::new(&products)
326        .where_(Product::category_r(), |cat| cat == "Electronics")
327        .map_items(|p| format!("{}: ${:.2}", p.name, p.price))
328        .take(5)
329        .collect();
330
331    println!("  Electronics price tags:");
332    for tag in &price_tags {
333        println!("    • {}", tag);
334    }
335
336    // ============================================================================
337    // COMPLEX EXAMPLE: Multi-Stage Lazy Pipeline
338    // ============================================================================
339    println!("\n═══════════════════════════════════════════════════════════════");
340    println!("Complex Example: Multi-stage lazy pipeline");
341    println!("═══════════════════════════════════════════════════════════════\n");
342
343    println!("Building complex query:");
344    println!("  1. Filter by category (Electronics)");
345    println!("  2. Filter by price range ($50-$500)");
346    println!("  3. Filter by rating (>4.5)");
347    println!("  4. Select names");
348    println!("  5. Take first 3");
349    println!();
350
351    let results: Vec<String> = LazyQuery::new(&products)
352        .where_(Product::category_r(), |cat| cat == "Electronics")
353        .where_(Product::price_r(), |&p| p >= 50.0 && p <= 500.0)
354        .where_(Product::rating_r(), |&r| r > 4.5)
355        .select_lazy(Product::name_r())
356        .take(3)
357        .collect();
358
359    println!("  Results:");
360    for (i, name) in results.iter().enumerate() {
361        println!("    {}. {}", i + 1, name);
362    }
363    println!("  ✅ All operations fused and executed lazily!");
364
365    // ============================================================================
366    // THREAD-SAFE UPDATES WITH RWLOCK
367    // ============================================================================
368    println!("\n═══════════════════════════════════════════════════════════════");
369    println!("Bonus: Thread-safe updates with RwLock");
370    println!("═══════════════════════════════════════════════════════════════\n");
371
372    // Update a product through the Arc<RwLock>
373    if let Some(product_arc) = product_map.get("PROD-002") {
374        println!("Updating PROD-002 stock...");
375        
376        // Write lock for mutation
377        if let Ok(mut product) = product_arc.write() {
378            let old_stock = product.stock;
379            product.stock = 25;
380            println!("  Stock updated: {} → {}", old_stock, product.stock);
381        }
382    }
383
384    // Query again to see the update
385    let updated_products = extract_products(&product_map);
386    let mouse = LazyQuery::new(&updated_products)
387        .find(|p| p.id == 2);
388
389    if let Some(product) = mouse {
390        println!("  Verified update: {} now has {} in stock", product.name, product.stock);
391    }
392
393    // ============================================================================
394    // PRACTICAL EXAMPLE: Price Analysis by Category
395    // ============================================================================
396    println!("\n═══════════════════════════════════════════════════════════════");
397    println!("Practical Example: Price analysis by category");
398    println!("═══════════════════════════════════════════════════════════════\n");
399
400    let categories = vec!["Electronics", "Furniture"];
401
402    for category in categories {
403        println!("  {} Statistics:", category);
404        
405        // Filter products by category first
406        let cat_products: Vec<Product> = products.iter()
407            .filter(|p| p.category == category)
408            .cloned()
409            .collect();
410
411        let count = LazyQuery::new(&cat_products).count();
412        let total = LazyQuery::new(&cat_products).sum_by(Product::price_r());
413        let avg = LazyQuery::new(&cat_products).avg_by(Product::price_r()).unwrap_or(0.0);
414        let min = LazyQuery::new(&cat_products).min_by_float(Product::price_r()).unwrap_or(0.0);
415        let max = LazyQuery::new(&cat_products).max_by_float(Product::price_r()).unwrap_or(0.0);
416
417        println!("    Count: {}", count);
418        println!("    Total: ${:.2}", total);
419        println!("    Average: ${:.2}", avg);
420        println!("    Range: ${:.2} - ${:.2}\n", min, max);
421    }
422
423    // ============================================================================
424    // COMBINING WITH HASHMAP OPERATIONS
425    // ============================================================================
426    println!("═══════════════════════════════════════════════════════════════");
427    println!("HashMap Integration: Query by key patterns");
428    println!("═══════════════════════════════════════════════════════════════\n");
429
430    // Filter HashMap by key pattern
431    let electronics_keys: Vec<String> = product_map
432        .iter()
433        .filter(|(_key, value)| {
434            // Read the value to check category
435            if let Ok(guard) = value.read() {
436                guard.category == "Electronics"
437            } else {
438                false
439            }
440        })
441        .map(|(key, _value)| key.clone())
442        .collect();
443
444    println!("  Electronics product IDs:");
445    for key in electronics_keys.iter().take(5) {
446        println!("    • {}", key);
447    }
448
449    // ============================================================================
450    // PERFORMANCE DEMONSTRATION
451    // ============================================================================
452    println!("\n═══════════════════════════════════════════════════════════════");
453    println!("Performance: Lazy vs Eager comparison");
454    println!("═══════════════════════════════════════════════════════════════\n");
455
456    println!("Scenario: Find first product with rating > 4.7 from {} products\n", products.len());
457
458    println!("  Eager approach (hypothetical):");
459    println!("    - Filter all {} products", products.len());
460    println!("    - Collect filtered results");
461    println!("    - Take first item");
462    println!("    - Wasted work: Check all items\n");
463
464    println!("  Lazy approach (actual):");
465    let _first_rated = LazyQuery::new(&products)
466        .where_(Product::rating_r(), |&r| r > 4.7)
467        .first();
468    println!("    - Starts checking products");
469    println!("    - Stops at first match");
470    println!("    - ✅ Early termination - checks ~3-5 items only!");
471
472    // ============================================================================
473    // Summary
474    // ============================================================================
475    println!("\n╔══════════════════════════════════════════════════════════════════╗");
476    println!("║  Summary: All Lazy Operations Demonstrated                      ║");
477    println!("╚══════════════════════════════════════════════════════════════════╝\n");
478
479    println!("✅ Lazy Query Operations:");
480    println!("   1. ✅ where_ - Lazy filtering");
481    println!("   2. ✅ select_lazy - Lazy projection");
482    println!("   3. ✅ take_lazy - Early termination");
483    println!("   4. ✅ skip_lazy - Pagination");
484    println!("   5. ✅ first - Short-circuit search");
485    println!("   6. ✅ any - Existence check (short-circuit)");
486    println!("   7. ✅ count - Count items");
487    println!("   8. ✅ sum_by - Sum aggregation");
488    println!("   9. ✅ avg_by - Average aggregation");
489    println!("   10. ✅ min_by_float - Minimum value");
490    println!("   11. ✅ max_by_float - Maximum value");
491    println!("   12. ✅ find - Find with predicate (short-circuit)");
492    println!("   13. ✅ for_each - Iteration");
493    println!("   14. ✅ fold - Custom aggregation");
494    println!("   15. ✅ all_match - Validation (short-circuit)");
495    println!("   16. ✅ into_iter - For loop support");
496    println!("   17. ✅ map_items - Transformation\n");
497
498    println!("✅ Arc<RwLock<T>> Benefits:");
499    println!("   • Thread-safe shared access");
500    println!("   • Interior mutability");
501    println!("   • Multiple readers, single writer");
502    println!("   • Reference counting (Arc)");
503    println!("   • Can be queried after extracting data\n");
504
505    println!("✅ HashMap<K, Arc<RwLock<V>>> Benefits:");
506    println!("   • Fast key-based lookup");
507    println!("   • Thread-safe value access");
508    println!("   • Can query all values");
509    println!("   • Can filter by key patterns");
510    println!("   • Perfect for shared state/caches\n");
511
512    println!("🎯 Use Cases:");
513    println!("   • Shared product catalogs");
514    println!("   • User session stores");
515    println!("   • Configuration caches");
516    println!("   • Real-time inventory systems");
517    println!("   • Multi-threaded data processing");
518    println!("   • Web server state management\n");
519
520    println!("✓ Arc<RwLock<T>> HashMap with all lazy operations demo complete!\n");
521}
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());
Examples found in repository?
examples/arc_rwlock_hashmap.rs (line 220)
59fn main() {
60    println!("\n╔══════════════════════════════════════════════════════════════════╗");
61    println!("║  Arc<RwLock<T>> HashMap Lazy Query Demo                         ║");
62    println!("║  Thread-safe shared data with lazy evaluation                   ║");
63    println!("╚══════════════════════════════════════════════════════════════════╝\n");
64
65    let product_map = create_sample_data();
66    println!("Created product catalog:");
67    println!("  Total products: {}", product_map.len());
68    println!("  Keys: {:?}\n", product_map.keys().take(3).collect::<Vec<_>>());
69
70    // Extract products for querying
71    let products = extract_products(&product_map);
72    println!("Extracted {} products from Arc<RwLock<Product>>\n", products.len());
73
74    // ============================================================================
75    // LAZY OPERATION 1: where_ - Lazy Filtering
76    // ============================================================================
77    println!("═══════════════════════════════════════════════════════════════");
78    println!("Lazy Operation 1: where_ (filtering)");
79    println!("═══════════════════════════════════════════════════════════════\n");
80
81    println!("Building filtered query (nothing executes yet)...");
82    let electronics_query = LazyQuery::new(&products)
83        .where_(Product::category_r(), |cat| cat == "Electronics")
84        .where_(Product::active_r(), |&active| active)
85        .where_(Product::stock_r(), |&stock| stock > 20);
86
87    println!("  ✅ Query built (deferred execution)\n");
88
89    println!("Collecting results (executes now)...");
90    let electronics: Vec<_> = electronics_query.collect();
91    println!("  Found {} electronics in stock", electronics.len());
92    for p in &electronics {
93        println!("    • {}: {} in stock", p.name, p.stock);
94    }
95
96    // ============================================================================
97    // LAZY OPERATION 2: select_lazy - Lazy Projection
98    // ============================================================================
99    println!("\n═══════════════════════════════════════════════════════════════");
100    println!("Lazy Operation 2: select_lazy (projection)");
101    println!("═══════════════════════════════════════════════════════════════\n");
102
103    println!("Selecting product names (lazy)...");
104    let names: Vec<String> = LazyQuery::new(&products)
105        .where_(Product::category_r(), |cat| cat == "Furniture")
106        .select_lazy(Product::name_r())
107        .collect();
108
109    println!("  Furniture names ({}):", names.len());
110    for name in &names {
111        println!("    • {}", name);
112    }
113
114    // ============================================================================
115    // LAZY OPERATION 3: take_lazy - Early Termination
116    // ============================================================================
117    println!("\n═══════════════════════════════════════════════════════════════");
118    println!("Lazy Operation 3: take_lazy (early termination)");
119    println!("═══════════════════════════════════════════════════════════════\n");
120
121    println!("Getting first 3 electronics...");
122    let first_3: Vec<_> = LazyQuery::new(&products)
123        .where_(Product::category_r(), |cat| cat == "Electronics")
124        .take_lazy(3)
125        .collect();
126
127    println!("  First 3 electronics:");
128    for (i, p) in first_3.iter().enumerate() {
129        println!("    {}. {} - ${:.2}", i + 1, p.name, p.price);
130    }
131    println!("  ✅ Stopped after finding 3 items!");
132
133    // ============================================================================
134    // LAZY OPERATION 4: skip_lazy - Pagination
135    // ============================================================================
136    println!("\n═══════════════════════════════════════════════════════════════");
137    println!("Lazy Operation 4: skip_lazy (pagination)");
138    println!("═══════════════════════════════════════════════════════════════\n");
139
140    println!("Getting page 2 (skip 3, take 3)...");
141    let page_2: Vec<_> = LazyQuery::new(&products)
142        .where_(Product::active_r(), |&active| active)
143        .skip_lazy(3)
144        .take_lazy(3)
145        .collect();
146
147    println!("  Page 2 items:");
148    for (i, p) in page_2.iter().enumerate() {
149        println!("    {}. {}", i + 4, p.name);
150    }
151
152    // ============================================================================
153    // LAZY OPERATION 5: first - Short-Circuit Search
154    // ============================================================================
155    println!("\n═══════════════════════════════════════════════════════════════");
156    println!("Lazy Operation 5: first (short-circuit)");
157    println!("═══════════════════════════════════════════════════════════════\n");
158
159    println!("Finding first expensive item (>$1000)...");
160    let expensive = LazyQuery::new(&products)
161        .where_(Product::price_r(), |&price| price > 1000.0)
162        .first();
163
164    match expensive {
165        Some(p) => println!("  Found: {} - ${:.2}", p.name, p.price),
166        None => println!("  Not found"),
167    }
168    println!("  ✅ Stopped at first match!");
169
170    // ============================================================================
171    // LAZY OPERATION 6: any - Existence Check
172    // ============================================================================
173    println!("\n═══════════════════════════════════════════════════════════════");
174    println!("Lazy Operation 6: any (existence check)");
175    println!("═══════════════════════════════════════════════════════════════\n");
176
177    println!("Checking if any furniture exists...");
178    let has_furniture = LazyQuery::new(&products)
179        .where_(Product::category_r(), |cat| cat == "Furniture")
180        .any();
181
182    println!("  Has furniture: {}", has_furniture);
183    println!("  ✅ Stopped immediately after finding first match!");
184
185    // ============================================================================
186    // LAZY OPERATION 7: count - Count Matching Items
187    // ============================================================================
188    println!("\n═══════════════════════════════════════════════════════════════");
189    println!("Lazy Operation 7: count");
190    println!("═══════════════════════════════════════════════════════════════\n");
191
192    let electronics_count = LazyQuery::new(&products)
193        .where_(Product::category_r(), |cat| cat == "Electronics")
194        .count();
195
196    println!("  Electronics count: {}", electronics_count);
197
198    // ============================================================================
199    // LAZY OPERATION 8: sum_by - Aggregation
200    // ============================================================================
201    println!("\n═══════════════════════════════════════════════════════════════");
202    println!("Lazy Operation 8: sum_by (aggregation)");
203    println!("═══════════════════════════════════════════════════════════════\n");
204
205    let total_value: f64 = LazyQuery::new(&products)
206        .where_(Product::category_r(), |cat| cat == "Electronics")
207        .sum_by(Product::price_r());
208
209    println!("  Total electronics value: ${:.2}", total_value);
210
211    // ============================================================================
212    // LAZY OPERATION 9: avg_by - Average
213    // ============================================================================
214    println!("\n═══════════════════════════════════════════════════════════════");
215    println!("Lazy Operation 9: avg_by");
216    println!("═══════════════════════════════════════════════════════════════\n");
217
218    let avg_price = LazyQuery::new(&products)
219        .where_(Product::category_r(), |cat| cat == "Furniture")
220        .avg_by(Product::price_r())
221        .unwrap_or(0.0);
222
223    println!("  Average furniture price: ${:.2}", avg_price);
224
225    // ============================================================================
226    // LAZY OPERATION 10: min_by_float / max_by_float
227    // ============================================================================
228    println!("\n═══════════════════════════════════════════════════════════════");
229    println!("Lazy Operation 10: min_by_float / max_by_float");
230    println!("═══════════════════════════════════════════════════════════════\n");
231
232    let min_price = LazyQuery::new(&products)
233        .where_(Product::active_r(), |&active| active)
234        .min_by_float(Product::price_r())
235        .unwrap_or(0.0);
236
237    let max_price = LazyQuery::new(&products)
238        .where_(Product::active_r(), |&active| active)
239        .max_by_float(Product::price_r())
240        .unwrap_or(0.0);
241
242    println!("  Price range for active products:");
243    println!("    Min: ${:.2}", min_price);
244    println!("    Max: ${:.2}", max_price);
245
246    // ============================================================================
247    // LAZY OPERATION 11: find - Find with Predicate
248    // ============================================================================
249    println!("\n═══════════════════════════════════════════════════════════════");
250    println!("Lazy Operation 11: find (with predicate)");
251    println!("═══════════════════════════════════════════════════════════════\n");
252
253    let high_rated = LazyQuery::new(&products)
254        .where_(Product::category_r(), |cat| cat == "Electronics")
255        .find(|item| item.rating > 4.7);
256
257    if let Some(product) = high_rated {
258        println!("  First highly-rated electronic:");
259        println!("    {}: Rating {:.1}", product.name, product.rating);
260    }
261
262    // ============================================================================
263    // LAZY OPERATION 12: for_each - Iteration
264    // ============================================================================
265    println!("\n═══════════════════════════════════════════════════════════════");
266    println!("Lazy Operation 12: for_each (iteration)");
267    println!("═══════════════════════════════════════════════════════════════\n");
268
269    println!("  Low stock alerts:");
270    LazyQuery::new(&products)
271        .where_(Product::stock_r(), |&stock| stock < 20)
272        .for_each(|product| {
273            println!("    ⚠️  {}: Only {} in stock", product.name, product.stock);
274        });
275
276    // ============================================================================
277    // LAZY OPERATION 13: fold - Custom Aggregation
278    // ============================================================================
279    println!("\n═══════════════════════════════════════════════════════════════");
280    println!("Lazy Operation 14: fold (custom aggregation)");
281    println!("═══════════════════════════════════════════════════════════════\n");
282
283    let total_inventory_value = LazyQuery::new(&products)
284        .where_(Product::active_r(), |&active| active)
285        .fold(0.0, |acc, product| {
286            acc + (product.price * product.stock as f64)
287        });
288
289    println!("  Total inventory value: ${:.2}", total_inventory_value);
290
291    // ============================================================================
292    // LAZY OPERATION 14: all_match - Validation
293    // ============================================================================
294    println!("\n═══════════════════════════════════════════════════════════════");
295    println!("Lazy Operation 15: all_match (validation)");
296    println!("═══════════════════════════════════════════════════════════════\n");
297
298    let all_priced = LazyQuery::new(&products)
299        .all_match(|item| item.price > 0.0);
300
301    println!("  All products have valid prices: {}", all_priced);
302
303    // ============================================================================
304    // LAZY OPERATION 15: into_iter - For Loop
305    // ============================================================================
306    println!("\n═══════════════════════════════════════════════════════════════");
307    println!("Lazy Operation 16: into_iter (for loop)");
308    println!("═══════════════════════════════════════════════════════════════\n");
309
310    println!("  High-value products (>$300):");
311    for product in LazyQuery::new(&products)
312        .where_(Product::price_r(), |&p| p > 300.0)
313        .take_lazy(5)
314    {
315        println!("    • {}: ${:.2}", product.name, product.price);
316    }
317
318    // ============================================================================
319    // LAZY OPERATION 16: map_items - Transform
320    // ============================================================================
321    println!("\n═══════════════════════════════════════════════════════════════");
322    println!("Lazy Operation 17: map_items (transformation)");
323    println!("═══════════════════════════════════════════════════════════════\n");
324
325    let price_tags: Vec<String> = LazyQuery::new(&products)
326        .where_(Product::category_r(), |cat| cat == "Electronics")
327        .map_items(|p| format!("{}: ${:.2}", p.name, p.price))
328        .take(5)
329        .collect();
330
331    println!("  Electronics price tags:");
332    for tag in &price_tags {
333        println!("    • {}", tag);
334    }
335
336    // ============================================================================
337    // COMPLEX EXAMPLE: Multi-Stage Lazy Pipeline
338    // ============================================================================
339    println!("\n═══════════════════════════════════════════════════════════════");
340    println!("Complex Example: Multi-stage lazy pipeline");
341    println!("═══════════════════════════════════════════════════════════════\n");
342
343    println!("Building complex query:");
344    println!("  1. Filter by category (Electronics)");
345    println!("  2. Filter by price range ($50-$500)");
346    println!("  3. Filter by rating (>4.5)");
347    println!("  4. Select names");
348    println!("  5. Take first 3");
349    println!();
350
351    let results: Vec<String> = LazyQuery::new(&products)
352        .where_(Product::category_r(), |cat| cat == "Electronics")
353        .where_(Product::price_r(), |&p| p >= 50.0 && p <= 500.0)
354        .where_(Product::rating_r(), |&r| r > 4.5)
355        .select_lazy(Product::name_r())
356        .take(3)
357        .collect();
358
359    println!("  Results:");
360    for (i, name) in results.iter().enumerate() {
361        println!("    {}. {}", i + 1, name);
362    }
363    println!("  ✅ All operations fused and executed lazily!");
364
365    // ============================================================================
366    // THREAD-SAFE UPDATES WITH RWLOCK
367    // ============================================================================
368    println!("\n═══════════════════════════════════════════════════════════════");
369    println!("Bonus: Thread-safe updates with RwLock");
370    println!("═══════════════════════════════════════════════════════════════\n");
371
372    // Update a product through the Arc<RwLock>
373    if let Some(product_arc) = product_map.get("PROD-002") {
374        println!("Updating PROD-002 stock...");
375        
376        // Write lock for mutation
377        if let Ok(mut product) = product_arc.write() {
378            let old_stock = product.stock;
379            product.stock = 25;
380            println!("  Stock updated: {} → {}", old_stock, product.stock);
381        }
382    }
383
384    // Query again to see the update
385    let updated_products = extract_products(&product_map);
386    let mouse = LazyQuery::new(&updated_products)
387        .find(|p| p.id == 2);
388
389    if let Some(product) = mouse {
390        println!("  Verified update: {} now has {} in stock", product.name, product.stock);
391    }
392
393    // ============================================================================
394    // PRACTICAL EXAMPLE: Price Analysis by Category
395    // ============================================================================
396    println!("\n═══════════════════════════════════════════════════════════════");
397    println!("Practical Example: Price analysis by category");
398    println!("═══════════════════════════════════════════════════════════════\n");
399
400    let categories = vec!["Electronics", "Furniture"];
401
402    for category in categories {
403        println!("  {} Statistics:", category);
404        
405        // Filter products by category first
406        let cat_products: Vec<Product> = products.iter()
407            .filter(|p| p.category == category)
408            .cloned()
409            .collect();
410
411        let count = LazyQuery::new(&cat_products).count();
412        let total = LazyQuery::new(&cat_products).sum_by(Product::price_r());
413        let avg = LazyQuery::new(&cat_products).avg_by(Product::price_r()).unwrap_or(0.0);
414        let min = LazyQuery::new(&cat_products).min_by_float(Product::price_r()).unwrap_or(0.0);
415        let max = LazyQuery::new(&cat_products).max_by_float(Product::price_r()).unwrap_or(0.0);
416
417        println!("    Count: {}", count);
418        println!("    Total: ${:.2}", total);
419        println!("    Average: ${:.2}", avg);
420        println!("    Range: ${:.2} - ${:.2}\n", min, max);
421    }
422
423    // ============================================================================
424    // COMBINING WITH HASHMAP OPERATIONS
425    // ============================================================================
426    println!("═══════════════════════════════════════════════════════════════");
427    println!("HashMap Integration: Query by key patterns");
428    println!("═══════════════════════════════════════════════════════════════\n");
429
430    // Filter HashMap by key pattern
431    let electronics_keys: Vec<String> = product_map
432        .iter()
433        .filter(|(_key, value)| {
434            // Read the value to check category
435            if let Ok(guard) = value.read() {
436                guard.category == "Electronics"
437            } else {
438                false
439            }
440        })
441        .map(|(key, _value)| key.clone())
442        .collect();
443
444    println!("  Electronics product IDs:");
445    for key in electronics_keys.iter().take(5) {
446        println!("    • {}", key);
447    }
448
449    // ============================================================================
450    // PERFORMANCE DEMONSTRATION
451    // ============================================================================
452    println!("\n═══════════════════════════════════════════════════════════════");
453    println!("Performance: Lazy vs Eager comparison");
454    println!("═══════════════════════════════════════════════════════════════\n");
455
456    println!("Scenario: Find first product with rating > 4.7 from {} products\n", products.len());
457
458    println!("  Eager approach (hypothetical):");
459    println!("    - Filter all {} products", products.len());
460    println!("    - Collect filtered results");
461    println!("    - Take first item");
462    println!("    - Wasted work: Check all items\n");
463
464    println!("  Lazy approach (actual):");
465    let _first_rated = LazyQuery::new(&products)
466        .where_(Product::rating_r(), |&r| r > 4.7)
467        .first();
468    println!("    - Starts checking products");
469    println!("    - Stops at first match");
470    println!("    - ✅ Early termination - checks ~3-5 items only!");
471
472    // ============================================================================
473    // Summary
474    // ============================================================================
475    println!("\n╔══════════════════════════════════════════════════════════════════╗");
476    println!("║  Summary: All Lazy Operations Demonstrated                      ║");
477    println!("╚══════════════════════════════════════════════════════════════════╝\n");
478
479    println!("✅ Lazy Query Operations:");
480    println!("   1. ✅ where_ - Lazy filtering");
481    println!("   2. ✅ select_lazy - Lazy projection");
482    println!("   3. ✅ take_lazy - Early termination");
483    println!("   4. ✅ skip_lazy - Pagination");
484    println!("   5. ✅ first - Short-circuit search");
485    println!("   6. ✅ any - Existence check (short-circuit)");
486    println!("   7. ✅ count - Count items");
487    println!("   8. ✅ sum_by - Sum aggregation");
488    println!("   9. ✅ avg_by - Average aggregation");
489    println!("   10. ✅ min_by_float - Minimum value");
490    println!("   11. ✅ max_by_float - Maximum value");
491    println!("   12. ✅ find - Find with predicate (short-circuit)");
492    println!("   13. ✅ for_each - Iteration");
493    println!("   14. ✅ fold - Custom aggregation");
494    println!("   15. ✅ all_match - Validation (short-circuit)");
495    println!("   16. ✅ into_iter - For loop support");
496    println!("   17. ✅ map_items - Transformation\n");
497
498    println!("✅ Arc<RwLock<T>> Benefits:");
499    println!("   • Thread-safe shared access");
500    println!("   • Interior mutability");
501    println!("   • Multiple readers, single writer");
502    println!("   • Reference counting (Arc)");
503    println!("   • Can be queried after extracting data\n");
504
505    println!("✅ HashMap<K, Arc<RwLock<V>>> Benefits:");
506    println!("   • Fast key-based lookup");
507    println!("   • Thread-safe value access");
508    println!("   • Can query all values");
509    println!("   • Can filter by key patterns");
510    println!("   • Perfect for shared state/caches\n");
511
512    println!("🎯 Use Cases:");
513    println!("   • Shared product catalogs");
514    println!("   • User session stores");
515    println!("   • Configuration caches");
516    println!("   • Real-time inventory systems");
517    println!("   • Multi-threaded data processing");
518    println!("   • Web server state management\n");
519
520    println!("✓ Arc<RwLock<T>> HashMap with all lazy operations demo complete!\n");
521}
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).

Examples found in repository?
examples/arc_rwlock_hashmap.rs (line 234)
59fn main() {
60    println!("\n╔══════════════════════════════════════════════════════════════════╗");
61    println!("║  Arc<RwLock<T>> HashMap Lazy Query Demo                         ║");
62    println!("║  Thread-safe shared data with lazy evaluation                   ║");
63    println!("╚══════════════════════════════════════════════════════════════════╝\n");
64
65    let product_map = create_sample_data();
66    println!("Created product catalog:");
67    println!("  Total products: {}", product_map.len());
68    println!("  Keys: {:?}\n", product_map.keys().take(3).collect::<Vec<_>>());
69
70    // Extract products for querying
71    let products = extract_products(&product_map);
72    println!("Extracted {} products from Arc<RwLock<Product>>\n", products.len());
73
74    // ============================================================================
75    // LAZY OPERATION 1: where_ - Lazy Filtering
76    // ============================================================================
77    println!("═══════════════════════════════════════════════════════════════");
78    println!("Lazy Operation 1: where_ (filtering)");
79    println!("═══════════════════════════════════════════════════════════════\n");
80
81    println!("Building filtered query (nothing executes yet)...");
82    let electronics_query = LazyQuery::new(&products)
83        .where_(Product::category_r(), |cat| cat == "Electronics")
84        .where_(Product::active_r(), |&active| active)
85        .where_(Product::stock_r(), |&stock| stock > 20);
86
87    println!("  ✅ Query built (deferred execution)\n");
88
89    println!("Collecting results (executes now)...");
90    let electronics: Vec<_> = electronics_query.collect();
91    println!("  Found {} electronics in stock", electronics.len());
92    for p in &electronics {
93        println!("    • {}: {} in stock", p.name, p.stock);
94    }
95
96    // ============================================================================
97    // LAZY OPERATION 2: select_lazy - Lazy Projection
98    // ============================================================================
99    println!("\n═══════════════════════════════════════════════════════════════");
100    println!("Lazy Operation 2: select_lazy (projection)");
101    println!("═══════════════════════════════════════════════════════════════\n");
102
103    println!("Selecting product names (lazy)...");
104    let names: Vec<String> = LazyQuery::new(&products)
105        .where_(Product::category_r(), |cat| cat == "Furniture")
106        .select_lazy(Product::name_r())
107        .collect();
108
109    println!("  Furniture names ({}):", names.len());
110    for name in &names {
111        println!("    • {}", name);
112    }
113
114    // ============================================================================
115    // LAZY OPERATION 3: take_lazy - Early Termination
116    // ============================================================================
117    println!("\n═══════════════════════════════════════════════════════════════");
118    println!("Lazy Operation 3: take_lazy (early termination)");
119    println!("═══════════════════════════════════════════════════════════════\n");
120
121    println!("Getting first 3 electronics...");
122    let first_3: Vec<_> = LazyQuery::new(&products)
123        .where_(Product::category_r(), |cat| cat == "Electronics")
124        .take_lazy(3)
125        .collect();
126
127    println!("  First 3 electronics:");
128    for (i, p) in first_3.iter().enumerate() {
129        println!("    {}. {} - ${:.2}", i + 1, p.name, p.price);
130    }
131    println!("  ✅ Stopped after finding 3 items!");
132
133    // ============================================================================
134    // LAZY OPERATION 4: skip_lazy - Pagination
135    // ============================================================================
136    println!("\n═══════════════════════════════════════════════════════════════");
137    println!("Lazy Operation 4: skip_lazy (pagination)");
138    println!("═══════════════════════════════════════════════════════════════\n");
139
140    println!("Getting page 2 (skip 3, take 3)...");
141    let page_2: Vec<_> = LazyQuery::new(&products)
142        .where_(Product::active_r(), |&active| active)
143        .skip_lazy(3)
144        .take_lazy(3)
145        .collect();
146
147    println!("  Page 2 items:");
148    for (i, p) in page_2.iter().enumerate() {
149        println!("    {}. {}", i + 4, p.name);
150    }
151
152    // ============================================================================
153    // LAZY OPERATION 5: first - Short-Circuit Search
154    // ============================================================================
155    println!("\n═══════════════════════════════════════════════════════════════");
156    println!("Lazy Operation 5: first (short-circuit)");
157    println!("═══════════════════════════════════════════════════════════════\n");
158
159    println!("Finding first expensive item (>$1000)...");
160    let expensive = LazyQuery::new(&products)
161        .where_(Product::price_r(), |&price| price > 1000.0)
162        .first();
163
164    match expensive {
165        Some(p) => println!("  Found: {} - ${:.2}", p.name, p.price),
166        None => println!("  Not found"),
167    }
168    println!("  ✅ Stopped at first match!");
169
170    // ============================================================================
171    // LAZY OPERATION 6: any - Existence Check
172    // ============================================================================
173    println!("\n═══════════════════════════════════════════════════════════════");
174    println!("Lazy Operation 6: any (existence check)");
175    println!("═══════════════════════════════════════════════════════════════\n");
176
177    println!("Checking if any furniture exists...");
178    let has_furniture = LazyQuery::new(&products)
179        .where_(Product::category_r(), |cat| cat == "Furniture")
180        .any();
181
182    println!("  Has furniture: {}", has_furniture);
183    println!("  ✅ Stopped immediately after finding first match!");
184
185    // ============================================================================
186    // LAZY OPERATION 7: count - Count Matching Items
187    // ============================================================================
188    println!("\n═══════════════════════════════════════════════════════════════");
189    println!("Lazy Operation 7: count");
190    println!("═══════════════════════════════════════════════════════════════\n");
191
192    let electronics_count = LazyQuery::new(&products)
193        .where_(Product::category_r(), |cat| cat == "Electronics")
194        .count();
195
196    println!("  Electronics count: {}", electronics_count);
197
198    // ============================================================================
199    // LAZY OPERATION 8: sum_by - Aggregation
200    // ============================================================================
201    println!("\n═══════════════════════════════════════════════════════════════");
202    println!("Lazy Operation 8: sum_by (aggregation)");
203    println!("═══════════════════════════════════════════════════════════════\n");
204
205    let total_value: f64 = LazyQuery::new(&products)
206        .where_(Product::category_r(), |cat| cat == "Electronics")
207        .sum_by(Product::price_r());
208
209    println!("  Total electronics value: ${:.2}", total_value);
210
211    // ============================================================================
212    // LAZY OPERATION 9: avg_by - Average
213    // ============================================================================
214    println!("\n═══════════════════════════════════════════════════════════════");
215    println!("Lazy Operation 9: avg_by");
216    println!("═══════════════════════════════════════════════════════════════\n");
217
218    let avg_price = LazyQuery::new(&products)
219        .where_(Product::category_r(), |cat| cat == "Furniture")
220        .avg_by(Product::price_r())
221        .unwrap_or(0.0);
222
223    println!("  Average furniture price: ${:.2}", avg_price);
224
225    // ============================================================================
226    // LAZY OPERATION 10: min_by_float / max_by_float
227    // ============================================================================
228    println!("\n═══════════════════════════════════════════════════════════════");
229    println!("Lazy Operation 10: min_by_float / max_by_float");
230    println!("═══════════════════════════════════════════════════════════════\n");
231
232    let min_price = LazyQuery::new(&products)
233        .where_(Product::active_r(), |&active| active)
234        .min_by_float(Product::price_r())
235        .unwrap_or(0.0);
236
237    let max_price = LazyQuery::new(&products)
238        .where_(Product::active_r(), |&active| active)
239        .max_by_float(Product::price_r())
240        .unwrap_or(0.0);
241
242    println!("  Price range for active products:");
243    println!("    Min: ${:.2}", min_price);
244    println!("    Max: ${:.2}", max_price);
245
246    // ============================================================================
247    // LAZY OPERATION 11: find - Find with Predicate
248    // ============================================================================
249    println!("\n═══════════════════════════════════════════════════════════════");
250    println!("Lazy Operation 11: find (with predicate)");
251    println!("═══════════════════════════════════════════════════════════════\n");
252
253    let high_rated = LazyQuery::new(&products)
254        .where_(Product::category_r(), |cat| cat == "Electronics")
255        .find(|item| item.rating > 4.7);
256
257    if let Some(product) = high_rated {
258        println!("  First highly-rated electronic:");
259        println!("    {}: Rating {:.1}", product.name, product.rating);
260    }
261
262    // ============================================================================
263    // LAZY OPERATION 12: for_each - Iteration
264    // ============================================================================
265    println!("\n═══════════════════════════════════════════════════════════════");
266    println!("Lazy Operation 12: for_each (iteration)");
267    println!("═══════════════════════════════════════════════════════════════\n");
268
269    println!("  Low stock alerts:");
270    LazyQuery::new(&products)
271        .where_(Product::stock_r(), |&stock| stock < 20)
272        .for_each(|product| {
273            println!("    ⚠️  {}: Only {} in stock", product.name, product.stock);
274        });
275
276    // ============================================================================
277    // LAZY OPERATION 13: fold - Custom Aggregation
278    // ============================================================================
279    println!("\n═══════════════════════════════════════════════════════════════");
280    println!("Lazy Operation 14: fold (custom aggregation)");
281    println!("═══════════════════════════════════════════════════════════════\n");
282
283    let total_inventory_value = LazyQuery::new(&products)
284        .where_(Product::active_r(), |&active| active)
285        .fold(0.0, |acc, product| {
286            acc + (product.price * product.stock as f64)
287        });
288
289    println!("  Total inventory value: ${:.2}", total_inventory_value);
290
291    // ============================================================================
292    // LAZY OPERATION 14: all_match - Validation
293    // ============================================================================
294    println!("\n═══════════════════════════════════════════════════════════════");
295    println!("Lazy Operation 15: all_match (validation)");
296    println!("═══════════════════════════════════════════════════════════════\n");
297
298    let all_priced = LazyQuery::new(&products)
299        .all_match(|item| item.price > 0.0);
300
301    println!("  All products have valid prices: {}", all_priced);
302
303    // ============================================================================
304    // LAZY OPERATION 15: into_iter - For Loop
305    // ============================================================================
306    println!("\n═══════════════════════════════════════════════════════════════");
307    println!("Lazy Operation 16: into_iter (for loop)");
308    println!("═══════════════════════════════════════════════════════════════\n");
309
310    println!("  High-value products (>$300):");
311    for product in LazyQuery::new(&products)
312        .where_(Product::price_r(), |&p| p > 300.0)
313        .take_lazy(5)
314    {
315        println!("    • {}: ${:.2}", product.name, product.price);
316    }
317
318    // ============================================================================
319    // LAZY OPERATION 16: map_items - Transform
320    // ============================================================================
321    println!("\n═══════════════════════════════════════════════════════════════");
322    println!("Lazy Operation 17: map_items (transformation)");
323    println!("═══════════════════════════════════════════════════════════════\n");
324
325    let price_tags: Vec<String> = LazyQuery::new(&products)
326        .where_(Product::category_r(), |cat| cat == "Electronics")
327        .map_items(|p| format!("{}: ${:.2}", p.name, p.price))
328        .take(5)
329        .collect();
330
331    println!("  Electronics price tags:");
332    for tag in &price_tags {
333        println!("    • {}", tag);
334    }
335
336    // ============================================================================
337    // COMPLEX EXAMPLE: Multi-Stage Lazy Pipeline
338    // ============================================================================
339    println!("\n═══════════════════════════════════════════════════════════════");
340    println!("Complex Example: Multi-stage lazy pipeline");
341    println!("═══════════════════════════════════════════════════════════════\n");
342
343    println!("Building complex query:");
344    println!("  1. Filter by category (Electronics)");
345    println!("  2. Filter by price range ($50-$500)");
346    println!("  3. Filter by rating (>4.5)");
347    println!("  4. Select names");
348    println!("  5. Take first 3");
349    println!();
350
351    let results: Vec<String> = LazyQuery::new(&products)
352        .where_(Product::category_r(), |cat| cat == "Electronics")
353        .where_(Product::price_r(), |&p| p >= 50.0 && p <= 500.0)
354        .where_(Product::rating_r(), |&r| r > 4.5)
355        .select_lazy(Product::name_r())
356        .take(3)
357        .collect();
358
359    println!("  Results:");
360    for (i, name) in results.iter().enumerate() {
361        println!("    {}. {}", i + 1, name);
362    }
363    println!("  ✅ All operations fused and executed lazily!");
364
365    // ============================================================================
366    // THREAD-SAFE UPDATES WITH RWLOCK
367    // ============================================================================
368    println!("\n═══════════════════════════════════════════════════════════════");
369    println!("Bonus: Thread-safe updates with RwLock");
370    println!("═══════════════════════════════════════════════════════════════\n");
371
372    // Update a product through the Arc<RwLock>
373    if let Some(product_arc) = product_map.get("PROD-002") {
374        println!("Updating PROD-002 stock...");
375        
376        // Write lock for mutation
377        if let Ok(mut product) = product_arc.write() {
378            let old_stock = product.stock;
379            product.stock = 25;
380            println!("  Stock updated: {} → {}", old_stock, product.stock);
381        }
382    }
383
384    // Query again to see the update
385    let updated_products = extract_products(&product_map);
386    let mouse = LazyQuery::new(&updated_products)
387        .find(|p| p.id == 2);
388
389    if let Some(product) = mouse {
390        println!("  Verified update: {} now has {} in stock", product.name, product.stock);
391    }
392
393    // ============================================================================
394    // PRACTICAL EXAMPLE: Price Analysis by Category
395    // ============================================================================
396    println!("\n═══════════════════════════════════════════════════════════════");
397    println!("Practical Example: Price analysis by category");
398    println!("═══════════════════════════════════════════════════════════════\n");
399
400    let categories = vec!["Electronics", "Furniture"];
401
402    for category in categories {
403        println!("  {} Statistics:", category);
404        
405        // Filter products by category first
406        let cat_products: Vec<Product> = products.iter()
407            .filter(|p| p.category == category)
408            .cloned()
409            .collect();
410
411        let count = LazyQuery::new(&cat_products).count();
412        let total = LazyQuery::new(&cat_products).sum_by(Product::price_r());
413        let avg = LazyQuery::new(&cat_products).avg_by(Product::price_r()).unwrap_or(0.0);
414        let min = LazyQuery::new(&cat_products).min_by_float(Product::price_r()).unwrap_or(0.0);
415        let max = LazyQuery::new(&cat_products).max_by_float(Product::price_r()).unwrap_or(0.0);
416
417        println!("    Count: {}", count);
418        println!("    Total: ${:.2}", total);
419        println!("    Average: ${:.2}", avg);
420        println!("    Range: ${:.2} - ${:.2}\n", min, max);
421    }
422
423    // ============================================================================
424    // COMBINING WITH HASHMAP OPERATIONS
425    // ============================================================================
426    println!("═══════════════════════════════════════════════════════════════");
427    println!("HashMap Integration: Query by key patterns");
428    println!("═══════════════════════════════════════════════════════════════\n");
429
430    // Filter HashMap by key pattern
431    let electronics_keys: Vec<String> = product_map
432        .iter()
433        .filter(|(_key, value)| {
434            // Read the value to check category
435            if let Ok(guard) = value.read() {
436                guard.category == "Electronics"
437            } else {
438                false
439            }
440        })
441        .map(|(key, _value)| key.clone())
442        .collect();
443
444    println!("  Electronics product IDs:");
445    for key in electronics_keys.iter().take(5) {
446        println!("    • {}", key);
447    }
448
449    // ============================================================================
450    // PERFORMANCE DEMONSTRATION
451    // ============================================================================
452    println!("\n═══════════════════════════════════════════════════════════════");
453    println!("Performance: Lazy vs Eager comparison");
454    println!("═══════════════════════════════════════════════════════════════\n");
455
456    println!("Scenario: Find first product with rating > 4.7 from {} products\n", products.len());
457
458    println!("  Eager approach (hypothetical):");
459    println!("    - Filter all {} products", products.len());
460    println!("    - Collect filtered results");
461    println!("    - Take first item");
462    println!("    - Wasted work: Check all items\n");
463
464    println!("  Lazy approach (actual):");
465    let _first_rated = LazyQuery::new(&products)
466        .where_(Product::rating_r(), |&r| r > 4.7)
467        .first();
468    println!("    - Starts checking products");
469    println!("    - Stops at first match");
470    println!("    - ✅ Early termination - checks ~3-5 items only!");
471
472    // ============================================================================
473    // Summary
474    // ============================================================================
475    println!("\n╔══════════════════════════════════════════════════════════════════╗");
476    println!("║  Summary: All Lazy Operations Demonstrated                      ║");
477    println!("╚══════════════════════════════════════════════════════════════════╝\n");
478
479    println!("✅ Lazy Query Operations:");
480    println!("   1. ✅ where_ - Lazy filtering");
481    println!("   2. ✅ select_lazy - Lazy projection");
482    println!("   3. ✅ take_lazy - Early termination");
483    println!("   4. ✅ skip_lazy - Pagination");
484    println!("   5. ✅ first - Short-circuit search");
485    println!("   6. ✅ any - Existence check (short-circuit)");
486    println!("   7. ✅ count - Count items");
487    println!("   8. ✅ sum_by - Sum aggregation");
488    println!("   9. ✅ avg_by - Average aggregation");
489    println!("   10. ✅ min_by_float - Minimum value");
490    println!("   11. ✅ max_by_float - Maximum value");
491    println!("   12. ✅ find - Find with predicate (short-circuit)");
492    println!("   13. ✅ for_each - Iteration");
493    println!("   14. ✅ fold - Custom aggregation");
494    println!("   15. ✅ all_match - Validation (short-circuit)");
495    println!("   16. ✅ into_iter - For loop support");
496    println!("   17. ✅ map_items - Transformation\n");
497
498    println!("✅ Arc<RwLock<T>> Benefits:");
499    println!("   • Thread-safe shared access");
500    println!("   • Interior mutability");
501    println!("   • Multiple readers, single writer");
502    println!("   • Reference counting (Arc)");
503    println!("   • Can be queried after extracting data\n");
504
505    println!("✅ HashMap<K, Arc<RwLock<V>>> Benefits:");
506    println!("   • Fast key-based lookup");
507    println!("   • Thread-safe value access");
508    println!("   • Can query all values");
509    println!("   • Can filter by key patterns");
510    println!("   • Perfect for shared state/caches\n");
511
512    println!("🎯 Use Cases:");
513    println!("   • Shared product catalogs");
514    println!("   • User session stores");
515    println!("   • Configuration caches");
516    println!("   • Real-time inventory systems");
517    println!("   • Multi-threaded data processing");
518    println!("   • Web server state management\n");
519
520    println!("✓ Arc<RwLock<T>> HashMap with all lazy operations demo complete!\n");
521}
Source

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

Finds maximum float value (terminal operation).

Examples found in repository?
examples/arc_rwlock_hashmap.rs (line 239)
59fn main() {
60    println!("\n╔══════════════════════════════════════════════════════════════════╗");
61    println!("║  Arc<RwLock<T>> HashMap Lazy Query Demo                         ║");
62    println!("║  Thread-safe shared data with lazy evaluation                   ║");
63    println!("╚══════════════════════════════════════════════════════════════════╝\n");
64
65    let product_map = create_sample_data();
66    println!("Created product catalog:");
67    println!("  Total products: {}", product_map.len());
68    println!("  Keys: {:?}\n", product_map.keys().take(3).collect::<Vec<_>>());
69
70    // Extract products for querying
71    let products = extract_products(&product_map);
72    println!("Extracted {} products from Arc<RwLock<Product>>\n", products.len());
73
74    // ============================================================================
75    // LAZY OPERATION 1: where_ - Lazy Filtering
76    // ============================================================================
77    println!("═══════════════════════════════════════════════════════════════");
78    println!("Lazy Operation 1: where_ (filtering)");
79    println!("═══════════════════════════════════════════════════════════════\n");
80
81    println!("Building filtered query (nothing executes yet)...");
82    let electronics_query = LazyQuery::new(&products)
83        .where_(Product::category_r(), |cat| cat == "Electronics")
84        .where_(Product::active_r(), |&active| active)
85        .where_(Product::stock_r(), |&stock| stock > 20);
86
87    println!("  ✅ Query built (deferred execution)\n");
88
89    println!("Collecting results (executes now)...");
90    let electronics: Vec<_> = electronics_query.collect();
91    println!("  Found {} electronics in stock", electronics.len());
92    for p in &electronics {
93        println!("    • {}: {} in stock", p.name, p.stock);
94    }
95
96    // ============================================================================
97    // LAZY OPERATION 2: select_lazy - Lazy Projection
98    // ============================================================================
99    println!("\n═══════════════════════════════════════════════════════════════");
100    println!("Lazy Operation 2: select_lazy (projection)");
101    println!("═══════════════════════════════════════════════════════════════\n");
102
103    println!("Selecting product names (lazy)...");
104    let names: Vec<String> = LazyQuery::new(&products)
105        .where_(Product::category_r(), |cat| cat == "Furniture")
106        .select_lazy(Product::name_r())
107        .collect();
108
109    println!("  Furniture names ({}):", names.len());
110    for name in &names {
111        println!("    • {}", name);
112    }
113
114    // ============================================================================
115    // LAZY OPERATION 3: take_lazy - Early Termination
116    // ============================================================================
117    println!("\n═══════════════════════════════════════════════════════════════");
118    println!("Lazy Operation 3: take_lazy (early termination)");
119    println!("═══════════════════════════════════════════════════════════════\n");
120
121    println!("Getting first 3 electronics...");
122    let first_3: Vec<_> = LazyQuery::new(&products)
123        .where_(Product::category_r(), |cat| cat == "Electronics")
124        .take_lazy(3)
125        .collect();
126
127    println!("  First 3 electronics:");
128    for (i, p) in first_3.iter().enumerate() {
129        println!("    {}. {} - ${:.2}", i + 1, p.name, p.price);
130    }
131    println!("  ✅ Stopped after finding 3 items!");
132
133    // ============================================================================
134    // LAZY OPERATION 4: skip_lazy - Pagination
135    // ============================================================================
136    println!("\n═══════════════════════════════════════════════════════════════");
137    println!("Lazy Operation 4: skip_lazy (pagination)");
138    println!("═══════════════════════════════════════════════════════════════\n");
139
140    println!("Getting page 2 (skip 3, take 3)...");
141    let page_2: Vec<_> = LazyQuery::new(&products)
142        .where_(Product::active_r(), |&active| active)
143        .skip_lazy(3)
144        .take_lazy(3)
145        .collect();
146
147    println!("  Page 2 items:");
148    for (i, p) in page_2.iter().enumerate() {
149        println!("    {}. {}", i + 4, p.name);
150    }
151
152    // ============================================================================
153    // LAZY OPERATION 5: first - Short-Circuit Search
154    // ============================================================================
155    println!("\n═══════════════════════════════════════════════════════════════");
156    println!("Lazy Operation 5: first (short-circuit)");
157    println!("═══════════════════════════════════════════════════════════════\n");
158
159    println!("Finding first expensive item (>$1000)...");
160    let expensive = LazyQuery::new(&products)
161        .where_(Product::price_r(), |&price| price > 1000.0)
162        .first();
163
164    match expensive {
165        Some(p) => println!("  Found: {} - ${:.2}", p.name, p.price),
166        None => println!("  Not found"),
167    }
168    println!("  ✅ Stopped at first match!");
169
170    // ============================================================================
171    // LAZY OPERATION 6: any - Existence Check
172    // ============================================================================
173    println!("\n═══════════════════════════════════════════════════════════════");
174    println!("Lazy Operation 6: any (existence check)");
175    println!("═══════════════════════════════════════════════════════════════\n");
176
177    println!("Checking if any furniture exists...");
178    let has_furniture = LazyQuery::new(&products)
179        .where_(Product::category_r(), |cat| cat == "Furniture")
180        .any();
181
182    println!("  Has furniture: {}", has_furniture);
183    println!("  ✅ Stopped immediately after finding first match!");
184
185    // ============================================================================
186    // LAZY OPERATION 7: count - Count Matching Items
187    // ============================================================================
188    println!("\n═══════════════════════════════════════════════════════════════");
189    println!("Lazy Operation 7: count");
190    println!("═══════════════════════════════════════════════════════════════\n");
191
192    let electronics_count = LazyQuery::new(&products)
193        .where_(Product::category_r(), |cat| cat == "Electronics")
194        .count();
195
196    println!("  Electronics count: {}", electronics_count);
197
198    // ============================================================================
199    // LAZY OPERATION 8: sum_by - Aggregation
200    // ============================================================================
201    println!("\n═══════════════════════════════════════════════════════════════");
202    println!("Lazy Operation 8: sum_by (aggregation)");
203    println!("═══════════════════════════════════════════════════════════════\n");
204
205    let total_value: f64 = LazyQuery::new(&products)
206        .where_(Product::category_r(), |cat| cat == "Electronics")
207        .sum_by(Product::price_r());
208
209    println!("  Total electronics value: ${:.2}", total_value);
210
211    // ============================================================================
212    // LAZY OPERATION 9: avg_by - Average
213    // ============================================================================
214    println!("\n═══════════════════════════════════════════════════════════════");
215    println!("Lazy Operation 9: avg_by");
216    println!("═══════════════════════════════════════════════════════════════\n");
217
218    let avg_price = LazyQuery::new(&products)
219        .where_(Product::category_r(), |cat| cat == "Furniture")
220        .avg_by(Product::price_r())
221        .unwrap_or(0.0);
222
223    println!("  Average furniture price: ${:.2}", avg_price);
224
225    // ============================================================================
226    // LAZY OPERATION 10: min_by_float / max_by_float
227    // ============================================================================
228    println!("\n═══════════════════════════════════════════════════════════════");
229    println!("Lazy Operation 10: min_by_float / max_by_float");
230    println!("═══════════════════════════════════════════════════════════════\n");
231
232    let min_price = LazyQuery::new(&products)
233        .where_(Product::active_r(), |&active| active)
234        .min_by_float(Product::price_r())
235        .unwrap_or(0.0);
236
237    let max_price = LazyQuery::new(&products)
238        .where_(Product::active_r(), |&active| active)
239        .max_by_float(Product::price_r())
240        .unwrap_or(0.0);
241
242    println!("  Price range for active products:");
243    println!("    Min: ${:.2}", min_price);
244    println!("    Max: ${:.2}", max_price);
245
246    // ============================================================================
247    // LAZY OPERATION 11: find - Find with Predicate
248    // ============================================================================
249    println!("\n═══════════════════════════════════════════════════════════════");
250    println!("Lazy Operation 11: find (with predicate)");
251    println!("═══════════════════════════════════════════════════════════════\n");
252
253    let high_rated = LazyQuery::new(&products)
254        .where_(Product::category_r(), |cat| cat == "Electronics")
255        .find(|item| item.rating > 4.7);
256
257    if let Some(product) = high_rated {
258        println!("  First highly-rated electronic:");
259        println!("    {}: Rating {:.1}", product.name, product.rating);
260    }
261
262    // ============================================================================
263    // LAZY OPERATION 12: for_each - Iteration
264    // ============================================================================
265    println!("\n═══════════════════════════════════════════════════════════════");
266    println!("Lazy Operation 12: for_each (iteration)");
267    println!("═══════════════════════════════════════════════════════════════\n");
268
269    println!("  Low stock alerts:");
270    LazyQuery::new(&products)
271        .where_(Product::stock_r(), |&stock| stock < 20)
272        .for_each(|product| {
273            println!("    ⚠️  {}: Only {} in stock", product.name, product.stock);
274        });
275
276    // ============================================================================
277    // LAZY OPERATION 13: fold - Custom Aggregation
278    // ============================================================================
279    println!("\n═══════════════════════════════════════════════════════════════");
280    println!("Lazy Operation 14: fold (custom aggregation)");
281    println!("═══════════════════════════════════════════════════════════════\n");
282
283    let total_inventory_value = LazyQuery::new(&products)
284        .where_(Product::active_r(), |&active| active)
285        .fold(0.0, |acc, product| {
286            acc + (product.price * product.stock as f64)
287        });
288
289    println!("  Total inventory value: ${:.2}", total_inventory_value);
290
291    // ============================================================================
292    // LAZY OPERATION 14: all_match - Validation
293    // ============================================================================
294    println!("\n═══════════════════════════════════════════════════════════════");
295    println!("Lazy Operation 15: all_match (validation)");
296    println!("═══════════════════════════════════════════════════════════════\n");
297
298    let all_priced = LazyQuery::new(&products)
299        .all_match(|item| item.price > 0.0);
300
301    println!("  All products have valid prices: {}", all_priced);
302
303    // ============================================================================
304    // LAZY OPERATION 15: into_iter - For Loop
305    // ============================================================================
306    println!("\n═══════════════════════════════════════════════════════════════");
307    println!("Lazy Operation 16: into_iter (for loop)");
308    println!("═══════════════════════════════════════════════════════════════\n");
309
310    println!("  High-value products (>$300):");
311    for product in LazyQuery::new(&products)
312        .where_(Product::price_r(), |&p| p > 300.0)
313        .take_lazy(5)
314    {
315        println!("    • {}: ${:.2}", product.name, product.price);
316    }
317
318    // ============================================================================
319    // LAZY OPERATION 16: map_items - Transform
320    // ============================================================================
321    println!("\n═══════════════════════════════════════════════════════════════");
322    println!("Lazy Operation 17: map_items (transformation)");
323    println!("═══════════════════════════════════════════════════════════════\n");
324
325    let price_tags: Vec<String> = LazyQuery::new(&products)
326        .where_(Product::category_r(), |cat| cat == "Electronics")
327        .map_items(|p| format!("{}: ${:.2}", p.name, p.price))
328        .take(5)
329        .collect();
330
331    println!("  Electronics price tags:");
332    for tag in &price_tags {
333        println!("    • {}", tag);
334    }
335
336    // ============================================================================
337    // COMPLEX EXAMPLE: Multi-Stage Lazy Pipeline
338    // ============================================================================
339    println!("\n═══════════════════════════════════════════════════════════════");
340    println!("Complex Example: Multi-stage lazy pipeline");
341    println!("═══════════════════════════════════════════════════════════════\n");
342
343    println!("Building complex query:");
344    println!("  1. Filter by category (Electronics)");
345    println!("  2. Filter by price range ($50-$500)");
346    println!("  3. Filter by rating (>4.5)");
347    println!("  4. Select names");
348    println!("  5. Take first 3");
349    println!();
350
351    let results: Vec<String> = LazyQuery::new(&products)
352        .where_(Product::category_r(), |cat| cat == "Electronics")
353        .where_(Product::price_r(), |&p| p >= 50.0 && p <= 500.0)
354        .where_(Product::rating_r(), |&r| r > 4.5)
355        .select_lazy(Product::name_r())
356        .take(3)
357        .collect();
358
359    println!("  Results:");
360    for (i, name) in results.iter().enumerate() {
361        println!("    {}. {}", i + 1, name);
362    }
363    println!("  ✅ All operations fused and executed lazily!");
364
365    // ============================================================================
366    // THREAD-SAFE UPDATES WITH RWLOCK
367    // ============================================================================
368    println!("\n═══════════════════════════════════════════════════════════════");
369    println!("Bonus: Thread-safe updates with RwLock");
370    println!("═══════════════════════════════════════════════════════════════\n");
371
372    // Update a product through the Arc<RwLock>
373    if let Some(product_arc) = product_map.get("PROD-002") {
374        println!("Updating PROD-002 stock...");
375        
376        // Write lock for mutation
377        if let Ok(mut product) = product_arc.write() {
378            let old_stock = product.stock;
379            product.stock = 25;
380            println!("  Stock updated: {} → {}", old_stock, product.stock);
381        }
382    }
383
384    // Query again to see the update
385    let updated_products = extract_products(&product_map);
386    let mouse = LazyQuery::new(&updated_products)
387        .find(|p| p.id == 2);
388
389    if let Some(product) = mouse {
390        println!("  Verified update: {} now has {} in stock", product.name, product.stock);
391    }
392
393    // ============================================================================
394    // PRACTICAL EXAMPLE: Price Analysis by Category
395    // ============================================================================
396    println!("\n═══════════════════════════════════════════════════════════════");
397    println!("Practical Example: Price analysis by category");
398    println!("═══════════════════════════════════════════════════════════════\n");
399
400    let categories = vec!["Electronics", "Furniture"];
401
402    for category in categories {
403        println!("  {} Statistics:", category);
404        
405        // Filter products by category first
406        let cat_products: Vec<Product> = products.iter()
407            .filter(|p| p.category == category)
408            .cloned()
409            .collect();
410
411        let count = LazyQuery::new(&cat_products).count();
412        let total = LazyQuery::new(&cat_products).sum_by(Product::price_r());
413        let avg = LazyQuery::new(&cat_products).avg_by(Product::price_r()).unwrap_or(0.0);
414        let min = LazyQuery::new(&cat_products).min_by_float(Product::price_r()).unwrap_or(0.0);
415        let max = LazyQuery::new(&cat_products).max_by_float(Product::price_r()).unwrap_or(0.0);
416
417        println!("    Count: {}", count);
418        println!("    Total: ${:.2}", total);
419        println!("    Average: ${:.2}", avg);
420        println!("    Range: ${:.2} - ${:.2}\n", min, max);
421    }
422
423    // ============================================================================
424    // COMBINING WITH HASHMAP OPERATIONS
425    // ============================================================================
426    println!("═══════════════════════════════════════════════════════════════");
427    println!("HashMap Integration: Query by key patterns");
428    println!("═══════════════════════════════════════════════════════════════\n");
429
430    // Filter HashMap by key pattern
431    let electronics_keys: Vec<String> = product_map
432        .iter()
433        .filter(|(_key, value)| {
434            // Read the value to check category
435            if let Ok(guard) = value.read() {
436                guard.category == "Electronics"
437            } else {
438                false
439            }
440        })
441        .map(|(key, _value)| key.clone())
442        .collect();
443
444    println!("  Electronics product IDs:");
445    for key in electronics_keys.iter().take(5) {
446        println!("    • {}", key);
447    }
448
449    // ============================================================================
450    // PERFORMANCE DEMONSTRATION
451    // ============================================================================
452    println!("\n═══════════════════════════════════════════════════════════════");
453    println!("Performance: Lazy vs Eager comparison");
454    println!("═══════════════════════════════════════════════════════════════\n");
455
456    println!("Scenario: Find first product with rating > 4.7 from {} products\n", products.len());
457
458    println!("  Eager approach (hypothetical):");
459    println!("    - Filter all {} products", products.len());
460    println!("    - Collect filtered results");
461    println!("    - Take first item");
462    println!("    - Wasted work: Check all items\n");
463
464    println!("  Lazy approach (actual):");
465    let _first_rated = LazyQuery::new(&products)
466        .where_(Product::rating_r(), |&r| r > 4.7)
467        .first();
468    println!("    - Starts checking products");
469    println!("    - Stops at first match");
470    println!("    - ✅ Early termination - checks ~3-5 items only!");
471
472    // ============================================================================
473    // Summary
474    // ============================================================================
475    println!("\n╔══════════════════════════════════════════════════════════════════╗");
476    println!("║  Summary: All Lazy Operations Demonstrated                      ║");
477    println!("╚══════════════════════════════════════════════════════════════════╝\n");
478
479    println!("✅ Lazy Query Operations:");
480    println!("   1. ✅ where_ - Lazy filtering");
481    println!("   2. ✅ select_lazy - Lazy projection");
482    println!("   3. ✅ take_lazy - Early termination");
483    println!("   4. ✅ skip_lazy - Pagination");
484    println!("   5. ✅ first - Short-circuit search");
485    println!("   6. ✅ any - Existence check (short-circuit)");
486    println!("   7. ✅ count - Count items");
487    println!("   8. ✅ sum_by - Sum aggregation");
488    println!("   9. ✅ avg_by - Average aggregation");
489    println!("   10. ✅ min_by_float - Minimum value");
490    println!("   11. ✅ max_by_float - Maximum value");
491    println!("   12. ✅ find - Find with predicate (short-circuit)");
492    println!("   13. ✅ for_each - Iteration");
493    println!("   14. ✅ fold - Custom aggregation");
494    println!("   15. ✅ all_match - Validation (short-circuit)");
495    println!("   16. ✅ into_iter - For loop support");
496    println!("   17. ✅ map_items - Transformation\n");
497
498    println!("✅ Arc<RwLock<T>> Benefits:");
499    println!("   • Thread-safe shared access");
500    println!("   • Interior mutability");
501    println!("   • Multiple readers, single writer");
502    println!("   • Reference counting (Arc)");
503    println!("   • Can be queried after extracting data\n");
504
505    println!("✅ HashMap<K, Arc<RwLock<V>>> Benefits:");
506    println!("   • Fast key-based lookup");
507    println!("   • Thread-safe value access");
508    println!("   • Can query all values");
509    println!("   • Can filter by key patterns");
510    println!("   • Perfect for shared state/caches\n");
511
512    println!("🎯 Use Cases:");
513    println!("   • Shared product catalogs");
514    println!("   • User session stores");
515    println!("   • Configuration caches");
516    println!("   • Real-time inventory systems");
517    println!("   • Multi-threaded data processing");
518    println!("   • Web server state management\n");
519
520    println!("✓ Arc<RwLock<T>> HashMap with all lazy operations demo complete!\n");
521}

Trait Implementations§

Source§

impl<'a, T, I> IntoIterator for LazyQuery<'a, T, I>
where T: 'static, 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) -> <LazyQuery<'a, T, I> as IntoIterator>::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.