1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
//! `NEVec<T>` represents a non-empty `Vec<T>`.

use serde::{Deserialize, Serialize};
use std::{
    error,
    fmt::{self, Debug},
    ops,
};

/// `NEVec<T>` represents a non-empty `Vec<T>`. It derefs to `Vec<T>`
/// directly.
#[derive(Clone, PartialEq, Eq, Serialize, Hash, Deserialize, Default)]
pub struct NEVec<T>(Vec<T>)
where
    T: Debug;

/// Represents the only error that can be emitted by `NEVec`, i.e. when
/// the number of items is zero.
#[derive(Debug)]
pub struct EmptyVec;

impl error::Error for EmptyVec {}

impl fmt::Display for EmptyVec {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            formatter,
            "NEVec must as least contain one item, zero given"
        )
    }
}

impl<T> NEVec<T>
where
    T: Debug,
{
    /// Creates a new non-empty vector, based on an inner `Vec<T>`. If
    /// the inner vector is empty, a `EmptyVec` error is returned.
    pub fn new(items: Vec<T>) -> Result<Self, EmptyVec> {
        if items.is_empty() {
            Err(EmptyVec)
        } else {
            Ok(Self(items))
        }
    }

    /// Converts this NEVec into Vec
    pub fn into_vec(self) -> Vec<T> {
        self.0
    }
}

impl<T> fmt::Debug for NEVec<T>
where
    T: Debug,
{
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(formatter, "{:?}", self.0)
    }
}

impl<T> ops::Deref for NEVec<T>
where
    T: Debug,
{
    type Target = Vec<T>;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}