glacier-web 0.5.0

A batteries-included web framework for Rust, inspired by Rails, Phoenix and Laravel.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
//! List methods, as Ruby's `Enumerable` and Elixir's `Enum` give: on any
//! `Vec`, slice or loaded `has_many`, without `.iter()` or `.collect()`.
//!
//! ```
//! use glacier::prelude::*;
//! let pages = vec![120, 340, 80];
//! assert_eq!(pages.map(|p| p * 2), vec![240, 680, 160]);
//! assert_eq!(pages.filter(|p| *p > 100), vec![120, 340]);
//! assert_eq!(pages.sum(|p| *p), 540);
//! assert_eq!(pages.find(|p| *p < 100), Some(&80));
//! ```
//!
//! In `.glacier`, an atom names a field: `books.map(:title)` is
//! `books.map(fn b -> b.title.clone() end)`.

use std::collections::HashMap;
use std::hash::Hash;

/// See the [module docs](self).
pub trait List<T> {
    /// Each item turned into something else: `books.map(fn b -> b.title end)`.
    fn map<'a, U>(&'a self, f: impl FnMut(&'a T) -> U) -> Vec<U>
    where
        T: 'a;
    /// Each item turned into something else, leaving out the `None`s, as
    /// Ruby's `filter_map`: `books.filter_map(:price)`, the prices that are
    /// set.
    fn filter_map<'a, U>(&'a self, f: impl FnMut(&'a T) -> Option<U>) -> Vec<U>
    where
        T: 'a;
    /// The items `keep` says yes to.
    fn filter(&self, keep: impl FnMut(&T) -> bool) -> Vec<T>
    where
        T: Clone;
    /// The items `keep` says yes to, borrowed rather than copied, for
    /// records that can't or needn't be cloned: `books.matching(:published)`.
    fn matching(&self, keep: impl FnMut(&T) -> bool) -> Vec<&T>;
    /// The items `drop` says no to.
    fn reject(&self, mut drop: impl FnMut(&T) -> bool) -> Vec<T>
    where
        T: Clone,
    {
        self.filter(|item| !drop(item))
    }
    /// The first item `matches` says yes to.
    fn find(&self, matches: impl FnMut(&T) -> bool) -> Option<&T>;
    /// Whether any item matches.
    fn any(&self, matches: impl FnMut(&T) -> bool) -> bool;
    /// Whether every item matches.
    fn all(&self, matches: impl FnMut(&T) -> bool) -> bool;
    /// How many items match.
    fn count_where(&self, matches: impl FnMut(&T) -> bool) -> usize;
    /// The sum of `f` over the items: `books.sum(fn b -> b.pages end)`
    /// (`books.sum(:pages)` in `.glacier`), as a query's `sum`.
    fn sum<N: std::iter::Sum<N>>(&self, f: impl FnMut(&T) -> N) -> N;
    /// The items sorted by `key`, in a new list (`sort_by` sorts in place).
    fn sorted_by<K: Ord>(&self, key: impl FnMut(&T) -> K) -> Vec<T>
    where
        T: Clone;
    /// The item with the least `key`.
    fn min_by_key<K: Ord>(&self, key: impl FnMut(&T) -> K) -> Option<&T>;
    /// The item with the greatest `key`.
    fn max_by_key<K: Ord>(&self, key: impl FnMut(&T) -> K) -> Option<&T>;
    /// The items in groups by `key`, the groups in the order their first
    /// items come.
    fn group_by<K: Eq + Hash + Clone>(&self, key: impl FnMut(&T) -> K) -> Vec<(K, Vec<T>)>
    where
        T: Clone;
    /// The items with each `key` once, the first of each kept.
    fn uniq_by<K: Eq + Hash>(&self, key: impl FnMut(&T) -> K) -> Vec<T>
    where
        T: Clone;
    /// Runs `f` for each item.
    fn each(&self, f: impl FnMut(&T));
    /// Each item turned into something else by a step that can fail: the
    /// list, or the first error (`rows.try_map(fn r -> r.get("id") end)?`).
    fn try_map<'a, U, E>(&'a self, f: impl FnMut(&'a T) -> Result<U, E>) -> Result<Vec<U>, E>
    where
        T: 'a;
    /// The first `Some` that `f` gives: `rows.find_map(fn r -> r.note end)`.
    fn find_map<'a, U>(&'a self, f: impl FnMut(&'a T) -> Option<U>) -> Option<U>
    where
        T: 'a;
    /// Where the first item `matches` says yes to is, from 0.
    fn position(&self, matches: impl FnMut(&T) -> bool) -> Option<usize>;
    /// Each item with where it is, from 0: `for (i, row) in rows.enumerate()`.
    fn enumerate(&self) -> Vec<(usize, &T)>;
    /// Each item paired with the one at the same place in `other`, as long
    /// as the shorter list.
    fn zip<'a, U>(&'a self, other: &'a [U]) -> Vec<(&'a T, &'a U)>;
    /// The items `keep` says yes to and the rest, as two lists:
    /// `(done, todo) = tasks.partition(:done)`.
    fn partition(&self, keep: impl FnMut(&T) -> bool) -> (Vec<T>, Vec<T>)
    where
        T: Clone;
    /// The items by `key`, for looking up: `books.index_by(:id)`. A later
    /// item with the same key replaces an earlier one.
    fn index_by<K: Eq + Hash>(&self, key: impl FnMut(&T) -> K) -> HashMap<K, T>
    where
        T: Clone;
    /// How many items have each `key`, in the order the keys first come:
    /// `orders.count_by(:status)`.
    fn count_by<K: Eq + Hash + Clone>(&self, key: impl FnMut(&T) -> K) -> Vec<(K, usize)>;
    /// The items in lists of `size` (the last may be shorter):
    /// `photos.chunked(3)` for rows of three.
    fn chunked(&self, size: usize) -> Vec<Vec<T>>
    where
        T: Clone;
    /// Each run of `size` items in a row: `[1, 2, 3].sliding(2)` is
    /// `[[1, 2], [2, 3]]`.
    fn sliding(&self, size: usize) -> Vec<Vec<T>>
    where
        T: Clone;
    /// The smallest value `f` gives, `None` for an empty list:
    /// `books.minimum(:pages)` (`min_by` gives the item).
    fn minimum<K: Ord>(&self, f: impl FnMut(&T) -> K) -> Option<K>;
    /// The largest value `f` gives: `books.maximum(:pages)`.
    fn maximum<K: Ord>(&self, f: impl FnMut(&T) -> K) -> Option<K>;
    /// The mean of what `f` gives, `None` for an empty list:
    /// `books.average(:pages)`.
    fn average<N: crate::values::ToF>(&self, f: impl FnMut(&T) -> N) -> Option<f64>;
    /// The items last to first, in a new list (`reverse` turns a list round
    /// in place).
    fn reversed(&self) -> Vec<T>
    where
        T: Clone;
}

/// `scores.compact()`: the values of a list of `Option`s, without the
/// `None`s, as Ruby's `compact`.
pub trait Compact<T> {
    fn compact(&self) -> Vec<T>;
}

impl<T: Clone> Compact<T> for [Option<T>] {
    fn compact(&self) -> Vec<T> {
        self.iter().flatten().cloned().collect()
    }
}

impl<T> List<T> for [T] {
    fn map<'a, U>(&'a self, f: impl FnMut(&'a T) -> U) -> Vec<U>
    where
        T: 'a,
    {
        self.iter().map(f).collect()
    }

    fn filter_map<'a, U>(&'a self, f: impl FnMut(&'a T) -> Option<U>) -> Vec<U>
    where
        T: 'a,
    {
        self.iter().filter_map(f).collect()
    }

    fn filter(&self, mut keep: impl FnMut(&T) -> bool) -> Vec<T>
    where
        T: Clone,
    {
        self.iter().filter(|item| keep(item)).cloned().collect()
    }

    fn matching(&self, mut keep: impl FnMut(&T) -> bool) -> Vec<&T> {
        self.iter().filter(|item| keep(item)).collect()
    }

    fn find(&self, mut matches: impl FnMut(&T) -> bool) -> Option<&T> {
        self.iter().find(|item| matches(item))
    }

    fn any(&self, matches: impl FnMut(&T) -> bool) -> bool {
        self.iter().any(matches)
    }

    fn all(&self, matches: impl FnMut(&T) -> bool) -> bool {
        self.iter().all(matches)
    }

    fn count_where(&self, mut matches: impl FnMut(&T) -> bool) -> usize {
        self.iter().filter(|item| matches(item)).count()
    }

    fn sum<N: std::iter::Sum<N>>(&self, f: impl FnMut(&T) -> N) -> N {
        self.iter().map(f).sum()
    }

    fn sorted_by<K: Ord>(&self, mut key: impl FnMut(&T) -> K) -> Vec<T>
    where
        T: Clone,
    {
        let mut sorted = self.to_vec();
        sorted.sort_by_key(|item| key(item));
        sorted
    }

    fn min_by_key<K: Ord>(&self, mut key: impl FnMut(&T) -> K) -> Option<&T> {
        self.iter().min_by_key(|item| key(item))
    }

    fn max_by_key<K: Ord>(&self, mut key: impl FnMut(&T) -> K) -> Option<&T> {
        self.iter().max_by_key(|item| key(item))
    }

    fn group_by<K: Eq + Hash + Clone>(&self, mut key: impl FnMut(&T) -> K) -> Vec<(K, Vec<T>)>
    where
        T: Clone,
    {
        let mut groups: Vec<(K, Vec<T>)> = Vec::new();
        let mut at: HashMap<K, usize> = HashMap::new();
        for item in self {
            let k = key(item);
            match at.get(&k) {
                Some(&i) => groups[i].1.push(item.clone()),
                None => {
                    at.insert(k.clone(), groups.len());
                    groups.push((k, vec![item.clone()]));
                }
            }
        }
        groups
    }

    fn uniq_by<K: Eq + Hash>(&self, mut key: impl FnMut(&T) -> K) -> Vec<T>
    where
        T: Clone,
    {
        let mut seen = std::collections::HashSet::new();
        self.iter()
            .filter(|item| seen.insert(key(item)))
            .cloned()
            .collect()
    }

    fn try_map<'a, U, E>(&'a self, f: impl FnMut(&'a T) -> Result<U, E>) -> Result<Vec<U>, E>
    where
        T: 'a,
    {
        self.iter().map(f).collect()
    }

    fn each(&self, f: impl FnMut(&T)) {
        self.iter().for_each(f);
    }

    fn find_map<'a, U>(&'a self, f: impl FnMut(&'a T) -> Option<U>) -> Option<U>
    where
        T: 'a,
    {
        self.iter().find_map(f)
    }

    fn position(&self, matches: impl FnMut(&T) -> bool) -> Option<usize> {
        self.iter().position(matches)
    }

    fn enumerate(&self) -> Vec<(usize, &T)> {
        self.iter().enumerate().collect()
    }

    fn zip<'a, U>(&'a self, other: &'a [U]) -> Vec<(&'a T, &'a U)> {
        self.iter().zip(other).collect()
    }

    fn reversed(&self) -> Vec<T>
    where
        T: Clone,
    {
        self.iter().rev().cloned().collect()
    }
    fn partition(&self, mut keep: impl FnMut(&T) -> bool) -> (Vec<T>, Vec<T>)
    where
        T: Clone,
    {
        let mut yes = Vec::new();
        let mut no = Vec::new();
        for item in self {
            if keep(item) {
                yes.push(item.clone());
            } else {
                no.push(item.clone());
            }
        }
        (yes, no)
    }

    fn index_by<K: Eq + Hash>(&self, mut key: impl FnMut(&T) -> K) -> HashMap<K, T>
    where
        T: Clone,
    {
        self.iter().map(|item| (key(item), item.clone())).collect()
    }

    fn count_by<K: Eq + Hash + Clone>(&self, mut key: impl FnMut(&T) -> K) -> Vec<(K, usize)> {
        let mut counts: Vec<(K, usize)> = Vec::new();
        let mut at: HashMap<K, usize> = HashMap::new();
        for item in self {
            let k = key(item);
            match at.get(&k) {
                Some(&i) => counts[i].1 += 1,
                None => {
                    at.insert(k.clone(), counts.len());
                    counts.push((k, 1));
                }
            }
        }
        counts
    }

    fn chunked(&self, size: usize) -> Vec<Vec<T>>
    where
        T: Clone,
    {
        self.chunks(size.max(1)).map(<[T]>::to_vec).collect()
    }

    fn sliding(&self, size: usize) -> Vec<Vec<T>>
    where
        T: Clone,
    {
        self.windows(size.max(1)).map(<[T]>::to_vec).collect()
    }

    fn minimum<K: Ord>(&self, f: impl FnMut(&T) -> K) -> Option<K> {
        self.iter().map(f).min()
    }

    fn maximum<K: Ord>(&self, f: impl FnMut(&T) -> K) -> Option<K> {
        self.iter().map(f).max()
    }

    fn average<N: crate::values::ToF>(&self, mut f: impl FnMut(&T) -> N) -> Option<f64> {
        if self.is_empty() {
            return None;
        }
        let total: f64 = self.iter().map(|item| f(item).to_f()).sum();
        Some(total / self.len() as f64)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn lists_read_as_ruby_and_elixir_do() {
        let words: &[&str] = &["pear", "fig", "apple", "plum"];
        assert_eq!(words.map(|w| w.len()), vec![4, 3, 5, 4]);
        assert_eq!(words.reject(|w| w.len() == 4), vec!["fig", "apple"]);
        assert_eq!(
            words.filter_map(|w| w.strip_prefix('p')),
            vec!["ear", "lum"]
        );
        assert!(words.any(|w| w.starts_with('a')));
        assert!(!words.all(|w| w.len() > 3));
        assert_eq!(words.count_where(|w| w.len() == 4), 2);
        assert_eq!(
            words.sorted_by(|w| w.len()),
            vec!["fig", "pear", "plum", "apple"]
        );
        assert_eq!(words.min_by_key(|w| w.len()), Some(&"fig"));
        assert_eq!(
            words.group_by(|w| w.len()),
            vec![
                (4, vec!["pear", "plum"]),
                (3, vec!["fig"]),
                (5, vec!["apple"])
            ]
        );
        assert_eq!(words.uniq_by(|w| w.len()), vec!["pear", "fig", "apple"]);
        let lengths: Result<Vec<usize>, String> = words.try_map(|w| Ok(w.len()));
        assert_eq!(lengths, Ok(vec![4, 3, 5, 4]));
        let failed: Result<Vec<usize>, String> = words.try_map(|w| {
            if w.len() > 4 {
                Err(w.to_string())
            } else {
                Ok(1)
            }
        });
        assert_eq!(failed, Err("apple".to_owned()));
        assert_eq!([Some(1), None, Some(3)].compact(), vec![1, 3]);
        assert_eq!(words.find_map(|w| w.strip_prefix('a')), Some("pple"));
        assert_eq!(words.position(|w| w.len() == 5), Some(2));
        assert_eq!(words.enumerate()[1], (1, &"fig"));
        assert_eq!(words.zip(&[1, 2]), vec![(&"pear", &1), (&"fig", &2)]);
        assert_eq!(words.reversed(), vec!["plum", "apple", "fig", "pear"]);
        // On a `Vec` too, which derefs to the slice.
        let owned: Vec<i32> = Vec::from([3, 1, 2]);
        assert_eq!(owned.position(|n| *n == 1), Some(1));
        let numbers = [1, 2, 3, 4, 5];
        assert_eq!(
            numbers.partition(|n| n % 2 == 0),
            (vec![2, 4], vec![1, 3, 5])
        );
        assert_eq!(words.index_by(|w| w.len())[&3], "fig");
        assert_eq!(words.count_by(|w| w.len()), vec![(4, 2), (3, 1), (5, 1)]);
        assert_eq!(numbers.chunked(2), vec![vec![1, 2], vec![3, 4], vec![5]]);
        assert_eq!(numbers[..3].sliding(2), vec![vec![1, 2], vec![2, 3]]);
        assert_eq!(words.minimum(|w| w.len()), Some(3));
        assert_eq!(words.maximum(|w| w.len()), Some(5));
        assert_eq!(numbers.average(|n| *n), Some(3.0));
        assert_eq!(Vec::<i32>::new().average(|n| *n), None);
    }
}