fluence_it_types/
ne_vec.rs

1//! `NEVec<T>` represents a non-empty `Vec<T>`.
2
3use serde::{Deserialize, Serialize};
4use std::{
5    error,
6    fmt::{self, Debug},
7    ops,
8};
9
10/// `NEVec<T>` represents a non-empty `Vec<T>`. It derefs to `Vec<T>`
11/// directly.
12#[derive(Clone, PartialEq, Eq, Serialize, Hash, Deserialize, Default)]
13pub struct NEVec<T>(Vec<T>)
14where
15    T: Debug;
16
17/// Represents the only error that can be emitted by `NEVec`, i.e. when
18/// the number of items is zero.
19#[derive(Debug)]
20pub struct EmptyVec;
21
22impl error::Error for EmptyVec {}
23
24impl fmt::Display for EmptyVec {
25    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
26        write!(
27            formatter,
28            "NEVec must as least contain one item, zero given"
29        )
30    }
31}
32
33impl<T> NEVec<T>
34where
35    T: Debug,
36{
37    /// Creates a new non-empty vector, based on an inner `Vec<T>`. If
38    /// the inner vector is empty, a `EmptyVec` error is returned.
39    pub fn new(items: Vec<T>) -> Result<Self, EmptyVec> {
40        if items.is_empty() {
41            Err(EmptyVec)
42        } else {
43            Ok(Self(items))
44        }
45    }
46
47    /// Converts this NEVec into Vec
48    pub fn into_vec(self) -> Vec<T> {
49        self.0
50    }
51}
52
53impl<T> fmt::Debug for NEVec<T>
54where
55    T: Debug,
56{
57    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
58        write!(formatter, "{:?}", self.0)
59    }
60}
61
62impl<T> ops::Deref for NEVec<T>
63where
64    T: Debug,
65{
66    type Target = Vec<T>;
67
68    fn deref(&self) -> &Self::Target {
69        &self.0
70    }
71}