#![no_std]
#[cfg(feature = "alloc")]
extern crate alloc;
pub trait Collection<T>:
AsRef<[T]> + AsMut<[T]> + Default + Length + Truncate + TryExtend<T> + TryPush<T>
{
}
pub trait Length {
fn len(&self) -> usize;
fn is_empty(&self) -> bool {
self.len() == 0
}
}
pub trait Truncate {
fn truncate(&mut self, len: usize);
}
pub trait TryExtend<A> {
type Error;
fn try_extend<T>(&mut self, iter: &mut T) -> Result<(), Self::Error>
where
T: Iterator<Item = A>;
fn try_extend_from_slice(&mut self, slice: &[A]) -> Result<(), Self::Error>
where
A: Clone,
{
self.try_extend(&mut slice.iter().cloned())
}
}
pub trait TryFromIterator<A>: Sized {
type Error;
fn try_from_iter<T>(iter: &mut T) -> Result<Self, Self::Error>
where
T: Iterator<Item = A>;
}
impl<A, C: Default + TryExtend<A>> TryFromIterator<A> for C {
type Error = <Self as TryExtend<A>>::Error;
fn try_from_iter<T>(iter: &mut T) -> Result<Self, Self::Error>
where
T: Iterator<Item = A>,
{
let mut collection = Self::default();
collection.try_extend(iter)?;
Ok(collection)
}
}
pub trait TryPush<T> {
fn try_push(&mut self, item: T) -> Result<(), T>;
}
pub trait TryCollect<A> {
fn try_collect<B>(&mut self) -> Result<B, B::Error>
where
B: TryFromIterator<A>;
}
impl<A, T> TryCollect<A> for T
where
T: Iterator<Item = A>,
{
fn try_collect<B>(&mut self) -> Result<B, B::Error>
where
B: TryFromIterator<A>,
{
B::try_from_iter(self)
}
}
#[cfg(feature = "alloc")]
mod vec_impls {
use super::{Length, Truncate, TryExtend};
use alloc::vec::Vec;
use core::convert::Infallible;
impl<T> Length for Vec<T> {
fn len(&self) -> usize {
Vec::len(self)
}
}
impl<T> Truncate for Vec<T> {
fn truncate(&mut self, len: usize) {
Vec::truncate(self, len);
}
}
impl<A> TryExtend<A> for Vec<A> {
type Error = Infallible;
fn try_extend<T: IntoIterator<Item = A>>(&mut self, iter: T) -> Result<(), Infallible> {
Vec::extend(self, iter);
Ok(())
}
}
}