rig/one_or_many.rs
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 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302
/// Struct containing either a single item or a list of items of type T.
/// If a single item is present, `first` will contain it and `rest` will be empty.
/// If multiple items are present, `first` will contain the first item and `rest` will contain the rest.
/// IMPORTANT: this struct cannot be created with an empty vector.
/// OneOrMany objects can only be created using OneOrMany::from() or OneOrMany::try_from().
#[derive(PartialEq, Eq, Debug, Clone)]
pub struct OneOrMany<T> {
/// First item in the list.
first: T,
/// Rest of the items in the list.
rest: Vec<T>,
}
/// Error type for when trying to create a OneOrMany object with an empty vector.
#[derive(Debug, thiserror::Error)]
#[error("Cannot create OneOrMany with an empty vector.")]
pub struct EmptyListError;
impl<T: Clone> OneOrMany<T> {
/// Get the first item in the list.
pub fn first(&self) -> T {
self.first.clone()
}
/// Get the rest of the items in the list (excluding the first one).
pub fn rest(&self) -> Vec<T> {
self.rest.clone()
}
/// After `OneOrMany<T>` is created, add an item of type T to the `rest`.
pub fn push(&mut self, item: T) {
self.rest.push(item);
}
/// Length of all items in `OneOrMany<T>`.
pub fn len(&self) -> usize {
1 + self.rest.len()
}
/// If `OneOrMany<T>` is empty. This will always be false because you cannot create an empty `OneOrMany<T>`.
/// This method is required when the method `len` exists.
pub fn is_empty(&self) -> bool {
false
}
/// Create a OneOrMany object with a single item of any type.
pub fn one(item: T) -> Self {
OneOrMany {
first: item,
rest: vec![],
}
}
/// Create a OneOrMany object with a vector of items of any type.
pub fn many(items: Vec<T>) -> Result<Self, EmptyListError> {
let mut iter = items.into_iter();
Ok(OneOrMany {
first: match iter.next() {
Some(item) => item,
None => return Err(EmptyListError),
},
rest: iter.collect(),
})
}
/// Merge a list of OneOrMany items into a single OneOrMany item.
pub fn merge(one_or_many_items: Vec<OneOrMany<T>>) -> Result<Self, EmptyListError> {
let items = one_or_many_items
.into_iter()
.flat_map(|one_or_many| one_or_many.into_iter())
.collect::<Vec<_>>();
OneOrMany::many(items)
}
pub fn iter(&self) -> Iter<T> {
Iter {
first: Some(&self.first),
rest: self.rest.iter(),
}
}
pub fn iter_mut(&mut self) -> IterMut<'_, T> {
IterMut {
first: Some(&mut self.first),
rest: self.rest.iter_mut(),
}
}
}
// ================================================================
// Implementations of Iterator for OneOrMany
// - OneOrMany<T>::iter() -> iterate over references of T objects
// - OneOrMany<T>::into_iter() -> iterate over owned T objects
// - OneOrMany<T>::iter_mut() -> iterate over mutable references of T objects
// ================================================================
/// Struct returned by call to `OneOrMany::iter()`.
pub struct Iter<'a, T> {
// References.
first: Option<&'a T>,
rest: std::slice::Iter<'a, T>,
}
/// Implement `Iterator` for `Iter<T>`.
/// The Item type of the `Iterator` trait is a reference of `T`.
impl<'a, T> Iterator for Iter<'a, T> {
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> {
if let Some(first) = self.first.take() {
Some(first)
} else {
self.rest.next()
}
}
}
/// Struct returned by call to `OneOrMany::into_iter()`.
pub struct IntoIter<T> {
// Owned.
first: Option<T>,
rest: std::vec::IntoIter<T>,
}
/// Implement `Iterator` for `IntoIter<T>`.
impl<T: Clone> IntoIterator for OneOrMany<T> {
type Item = T;
type IntoIter = IntoIter<T>;
fn into_iter(self) -> Self::IntoIter {
IntoIter {
first: Some(self.first),
rest: self.rest.into_iter(),
}
}
}
/// Implement `Iterator` for `IntoIter<T>`.
/// The Item type of the `Iterator` trait is an owned `T`.
impl<T: Clone> Iterator for IntoIter<T> {
type Item = T;
fn next(&mut self) -> Option<Self::Item> {
if let Some(first) = self.first.take() {
Some(first)
} else {
self.rest.next()
}
}
}
/// Struct returned by call to `OneOrMany::iter_mut()`.
pub struct IterMut<'a, T> {
// Mutable references.
first: Option<&'a mut T>,
rest: std::slice::IterMut<'a, T>,
}
// Implement `Iterator` for `IterMut<T>`.
// The Item type of the `Iterator` trait is a mutable reference of `OneOrMany<T>`.
impl<'a, T> Iterator for IterMut<'a, T> {
type Item = &'a mut T;
fn next(&mut self) -> Option<Self::Item> {
if let Some(first) = self.first.take() {
Some(first)
} else {
self.rest.next()
}
}
}
#[cfg(test)]
mod test {
use super::OneOrMany;
#[test]
fn test_single() {
let one_or_many = OneOrMany::one("hello".to_string());
assert_eq!(one_or_many.iter().count(), 1);
one_or_many.iter().for_each(|i| {
assert_eq!(i, "hello");
});
}
#[test]
fn test() {
let one_or_many = OneOrMany::many(vec!["hello".to_string(), "word".to_string()]).unwrap();
assert_eq!(one_or_many.iter().count(), 2);
one_or_many.iter().enumerate().for_each(|(i, item)| {
if i == 0 {
assert_eq!(item, "hello");
}
if i == 1 {
assert_eq!(item, "word");
}
});
}
#[test]
fn test_one_or_many_into_iter_single() {
let one_or_many = OneOrMany::one("hello".to_string());
assert_eq!(one_or_many.clone().into_iter().count(), 1);
one_or_many.into_iter().for_each(|i| {
assert_eq!(i, "hello".to_string());
});
}
#[test]
fn test_one_or_many_into_iter() {
let one_or_many = OneOrMany::many(vec!["hello".to_string(), "word".to_string()]).unwrap();
assert_eq!(one_or_many.clone().into_iter().count(), 2);
one_or_many.into_iter().enumerate().for_each(|(i, item)| {
if i == 0 {
assert_eq!(item, "hello".to_string());
}
if i == 1 {
assert_eq!(item, "word".to_string());
}
});
}
#[test]
fn test_one_or_many_merge() {
let one_or_many_1 = OneOrMany::many(vec!["hello".to_string(), "word".to_string()]).unwrap();
let one_or_many_2 = OneOrMany::one("sup".to_string());
let merged = OneOrMany::merge(vec![one_or_many_1, one_or_many_2]).unwrap();
assert_eq!(merged.iter().count(), 3);
merged.iter().enumerate().for_each(|(i, item)| {
if i == 0 {
assert_eq!(item, "hello");
}
if i == 1 {
assert_eq!(item, "word");
}
if i == 2 {
assert_eq!(item, "sup");
}
});
}
#[test]
fn test_mut_single() {
let mut one_or_many = OneOrMany::one("hello".to_string());
assert_eq!(one_or_many.iter_mut().count(), 1);
one_or_many.iter_mut().for_each(|i| {
assert_eq!(i, "hello");
});
}
#[test]
fn test_mut() {
let mut one_or_many =
OneOrMany::many(vec!["hello".to_string(), "word".to_string()]).unwrap();
assert_eq!(one_or_many.iter_mut().count(), 2);
one_or_many.iter_mut().enumerate().for_each(|(i, item)| {
if i == 0 {
item.push_str(" world");
assert_eq!(item, "hello world");
}
if i == 1 {
assert_eq!(item, "word");
}
});
}
#[test]
fn test_one_or_many_error() {
assert!(OneOrMany::<String>::many(vec![]).is_err())
}
#[test]
fn test_len_single() {
let one_or_many = OneOrMany::one("hello".to_string());
assert_eq!(one_or_many.len(), 1);
}
#[test]
fn test_len_many() {
let one_or_many = OneOrMany::many(vec!["hello".to_string(), "word".to_string()]).unwrap();
assert_eq!(one_or_many.len(), 2);
}
}