1use std::ops::Deref;
2
3pub trait VecExt<T> {
4 fn any<F: Fn(&T) -> bool>(&self, f: F) -> bool;
5 fn fold<F, U>(&self, f: F, init: U) -> U
6 where
7 F: Fn(U, &T) -> U;
8 fn into_first(self) -> Option<T>;
9 fn into_last(self) -> Option<T>;
10 fn recollect<U: From<T>>(self) -> Vec<U>;
11 fn merge_grouped<U>(
12 &mut self,
13 children: Vec<U>,
14 matcher: impl Fn(&T, &U) -> bool,
15 merger: impl Fn(&mut T, U),
16 );
17}
18
19pub trait DerefVec<T>
20where
21 T: Deref,
22{
23 fn includes(&self, item: &T::Target) -> bool;
24}
25
26impl<T> VecExt<T> for Vec<T> {
27 fn any<F: Fn(&T) -> bool>(&self, f: F) -> bool {
28 self.iter().any(f)
29 }
30
31 fn fold<F, U>(&self, f: F, init: U) -> U
32 where
33 F: Fn(U, &T) -> U,
34 {
35 self.iter().fold(init, f)
36 }
37
38 fn into_first(self) -> Option<T> {
39 self.into_iter().next()
40 }
41
42 fn into_last(mut self) -> Option<T> {
43 if self.is_empty() {
44 return None;
45 }
46 Some(self.remove(self.len() - 1))
47 }
48 fn recollect<U: From<T>>(self) -> Vec<U> {
49 self.into_iter().map(Into::into).collect()
50 }
51
52 fn merge_grouped<U>(
53 &mut self,
54 children: Vec<U>,
55 matcher: impl Fn(&T, &U) -> bool,
56 merger: impl Fn(&mut T, U),
57 ) {
58 let mut it = self.iter_mut().peekable();
59 for child in children {
60 while !matcher(it.peek().unwrap(), &child) {
61 it.next();
62 }
63 let current = it.peek_mut().unwrap();
64 merger(current, child);
65 }
66 }
67}
68
69impl<T> DerefVec<T> for Vec<T>
70where
71 T: Deref + PartialEq<T::Target>,
72{
73 fn includes(&self, item: &T::Target) -> bool {
74 self.iter().any(|i| i == item)
75 }
76}
77
78#[macro_export]
79macro_rules! vec_into {
80 ($(($($item:expr),*)),* $(,)?) => {
81 {
82 let mut v = Vec::new();
83 $(v.push(($($item.into()),*));)*
84 v
85 }
86 };
87 ($($item:expr),* $(,)?) => {
88 {
89 let mut v = Vec::new();
90 $(v.push($item.into());)*
91 v
92 }
93 };
94}
95
96#[cfg(test)]
97mod tests {
98 use super::*;
99
100 #[test]
101 fn test_deref() {
102 let s = vec!["a".to_string(), "b".to_string()];
103 assert!(s.includes("a"));
104 }
105
106 #[test]
107 fn test_vec_into() {
108 let s: Vec<String> = vec_into!["a", "b"];
109 assert_eq!(s, vec!["a".to_string(), "b".to_string()]);
110 }
111}