wasmer_interface_types/
vec1.rs

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