Skip to main content

nil_util/
vec.rs

1// Copyright (C) Call of Nil contributors
2// SPDX-License-Identifier: AGPL-3.0-only
3
4use smallvec::SmallVec;
5use std::ops::{ControlFlow, Try};
6
7pub trait VecExt<T> {
8  fn push_unique(&mut self, value: T) -> Option<T>
9  where
10    T: PartialEq;
11
12  fn try_push<R>(&mut self, value: R)
13  where
14    R: Try<Output = T>;
15}
16
17macro_rules! impl_trait {
18  () => {
19    fn push_unique(&mut self, value: T) -> Option<T>
20    where
21      T: PartialEq,
22    {
23      if self.contains(&value) {
24        Some(value)
25      } else {
26        self.push(value);
27        None
28      }
29    }
30
31    fn try_push<R>(&mut self, value: R)
32    where
33      R: Try<Output = T>,
34    {
35      if let ControlFlow::Continue(value) = value.branch() {
36        self.push(value);
37      }
38    }
39  };
40}
41
42impl<T> VecExt<T> for Vec<T> {
43  impl_trait!();
44}
45
46impl<const N: usize, T> VecExt<T> for SmallVec<[T; N]> {
47  impl_trait!();
48}