grafix_toolbox/kit/policies/func/
vec.rs1use std::{collections::HashMap, hash::Hash};
2
3pub trait Utf8Len {
4 fn utf8_len(&self) -> usize;
5 fn len_at_char(&self, idx: usize) -> usize;
6}
7impl Utf8Len for &str {
8 fn utf8_len(&self) -> usize {
9 self.chars().count()
10 }
11 fn len_at_char(&self, idx: usize) -> usize {
12 self.char_indices().nth(idx).map_or_else(|| self.len(), |(i, _)| i)
13 }
14}
15
16pub trait CountItems<T: Eq + Hash>: Sized + Iterator<Item = T> {
17 fn map_count(self) -> HashMap<T, usize> {
18 let mut map = HashMap::new();
19 for i in self {
20 *map.entry(i).or_default() += 1;
21 }
22 map
23 }
24}
25impl<T: Eq + Hash, V: Sized + Iterator<Item = T>> CountItems<T> for V {}
26
27pub trait CollectVec<T>: Sized + Iterator<Item = T> {
28 fn collect_vec(self) -> Vec<T> {
29 self.collect()
30 }
31 fn collect_box(self) -> Box<[T]> {
32 self.collect()
33 }
34 fn collect_arr<const N: usize>(self) -> [T; N] {
35 let vec = self.collect_vec();
36 ASSERT!(vec.len() == N, "Collecting into array of wrong length");
37 unsafe { vec.try_into().unwrap_unchecked() }
38 }
39}
40impl<V: Sized + Iterator<Item = T>, T> CollectVec<T> for V {}