vec_utils/lib.rs
1#![forbid(missing_docs)]
2
3/*!
4# vec-utils
5
6This is an experimental crate that adds some helpful functionality to `Vec<T>`, like `map` and `zip_with`. These functions allow you to transform a vec and try and reuse the allocation if possible!
7
8```rust
9use vec_utils::VecExt;
10
11fn to_bits(v: Vec<f32>) -> Vec<u32> {
12 v.map(|x| x.to_bits())
13}
14
15fn sum_2(v: Vec<f32>, w: Vec<f64>) -> Vec<f64> {
16 v.zip_with(w, |x, y| f64::from(x) + y)
17}
18```
19
20But `zip_with` is limited to taking only a single additional vector. To get around this limitation, this crate also exports some macros that can take an arbitrary number of input vectors, and in most cases will compile down to the same assembly as `Vec::map` and `Vec::zip_with` (sometimes with some additional cleanup code, but even then the macro solution is just as fast as the built-in version).
21
22You can use the `zip_with` and `try_zip_with` macros like so,
23
24```rust
25use vec_utils::{zip_with, try_zip_with};
26
27fn to_bits(v: Vec<f32>) -> Vec<u32> {
28 zip_with!(v, |x| x.to_bits())
29}
30
31fn sum_2(v: Vec<f32>, w: Vec<f64>) -> Vec<f64> {
32 zip_with!((v, w), |x, y| f64::from(x) + y)
33}
34
35fn sum_5(a: Vec<i32>, b: Vec<i32>, c: Vec<i32>, d: Vec<i32>, e: Vec<i32>) -> Vec<i32> {
36 zip_with!((a, b, c, d, e), |a, b, c, d, e| a + b + c + d + e)
37}
38
39fn mul_with(a: Vec<i32>) -> Vec<i32> {
40 zip_with!((a, vec![0, 1, 2, 3, 4, 5, 6, 7]), |a, x| a * x)
41}
42
43fn to_bits_no_nans(v: Vec<f32>) -> Result<Vec<u32>, &'static str> {
44 try_zip_with!(v, |x| if x.is_nan() { Err("Found NaN!") } else { Ok(x.to_bits()) })
45}
46```
47
48You can use as many input vectors as you want, just put them all inside the input tuple. Note that the second argument is not a closure, but syntax that looks like a closure, i.e. you can't make a closure before-hand and pass it as the second argument. Also, you can't use general patterns in the "closure"'s arguments, only identifiers are allowed. You can specify if you want a move closure by adding the move keyword in from of the "closure".
49
50```rust
51use vec_utils::zip_with;
52
53fn add(a: Vec<i32>, b: i32) -> Vec<i32> {
54 zip_with!(a, move |a| a + b)
55}
56```
57
58It also adds some functionality to reuse the allocation of a `Box<T>`, using the `BoxExt`/`UninitBox` api.
59
60```rust
61use vec_utils::BoxExt;
62
63fn replace(b: Box<i32>, f: f32) -> Box<f32> {
64 Box::drop_box(b).init(f)
65}
66
67fn get_and_replace(b: Box<i32>, f: f32) -> (Box<f32>, i32) {
68 let (b, x) = Box::take_box(b);
69 (b.init(f), x)
70}
71```
72*/
73
74/// This allows running destructors, even if other destructors have panicked
75macro_rules! defer {
76 ($($do_work:tt)*) => {
77 let _guard = $crate::OnDrop(Some(|| { $($do_work)* }));
78 }
79}
80
81/// A macro to give syntactic sugar for `general_zip::try_zip_with`
82///
83/// This allows combining multiple vectors into a one with short-circuiting
84/// on the failure case
85///
86/// # Usage
87///
88/// ```rust
89/// use vec_utils::{zip_with, try_zip_with};
90///
91/// fn to_bits(v: Vec<f32>) -> Vec<u32> {
92/// zip_with!(v, |x| x.to_bits())
93/// }
94///
95/// fn sum_2(v: Vec<f32>, w: Vec<f64>) -> Vec<f64> {
96/// zip_with!((v, w), |x, y| f64::from(x) + y)
97/// }
98///
99/// fn sum_5(a: Vec<i32>, b: Vec<i32>, c: Vec<i32>, d: Vec<i32>, e: Vec<i32>) -> Vec<i32> {
100/// zip_with!((a, b, c, d, e), |a, b, c, d, e| a + b + c + d + e)
101/// }
102///
103/// fn mul_with(a: Vec<i32>) -> Vec<i32> {
104/// zip_with!((a, vec![0, 1, 2, 3, 4, 5, 6, 7]), |a, x| a * x)
105/// }
106///
107/// fn to_bits_no_nans(v: Vec<f32>) -> Result<Vec<u32>, &'static str> {
108/// try_zip_with!(v, |x| if x.is_nan() { Err("Found NaN!") } else { Ok(x.to_bits()) })
109/// }
110/// ```
111/// You can use as many input vectors as you want, just put them all inside the input tuple.
112/// Note that the second argument is not a closure, but syntax that looks like a closure,
113/// i.e. you can't make a closure before-hand and pass it as the second argument. Also, you can't
114/// use general patterns in the "closure"'s arguments, only identifiers are allowed.
115/// You can specify if you want a move closure by adding the move keyword in from of the "closure".
116///
117/// ```rust
118/// use vec_utils::zip_with;
119///
120/// fn add(a: Vec<i32>, b: i32) -> Vec<i32> {
121/// zip_with!(a, move |a| a + b)
122/// }
123/// ```
124#[macro_export]
125macro_rules! try_zip_with {
126 ($vec:expr, $($move:ident)? |$($i:ident),+ $(,)?| $($work:tt)*) => {{
127 #[allow(unused_parens)]
128 let ($($i),*) = $vec;
129
130 $crate::try_zip_with_impl(
131 $crate::list!(WRAP $($i),*),
132 $($move)? |$crate::list!(PLACE $($i),*)| $($work)*
133 )
134 }};
135}
136
137/// A wrapper around `try_zip_with` for infallible mapping
138#[macro_export]
139macro_rules! zip_with {
140 ($vec:expr, $($move:ident)? |$($i:ident),+ $(,)?| $($work:tt)*) => {
141 match $crate::try_zip_with!(
142 $vec, $($move)? |$($i),+|
143 Ok::<_, std::convert::Infallible>($($work)*)
144 ) {
145 Ok(x) => x,
146 Err(x) => match x {}
147 }
148 };
149}
150
151#[doc(hidden)]
152#[macro_export]
153macro_rules! list {
154 (WRAP $e:ident) => {
155 ($e,)
156 };
157 (PLACE $e:ident) => {
158 $e
159 };
160 ($wrap:ident $e:ident $(, $rest:ident)* $(,)?) => {
161 ($e, $crate::list!($wrap $($rest),*))
162 };
163}
164
165struct OnDrop<F: FnOnce()>(Option<F>);
166
167impl<F: FnOnce()> Drop for OnDrop<F> {
168 fn drop(&mut self) {
169 self.0.take().unwrap()()
170 }
171}
172
173mod boxed;
174mod r#try;
175mod vec;
176
177pub use self::boxed::*;
178pub use self::r#try::*;
179pub use self::vec::*;