You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
genmarkov/src/util.rs

93 lines
1.7 KiB

//! Utils
pub trait NewCapacity: Sized
{
fn new() -> Self;
fn with_capacity(cap: usize) -> Self;
}
impl NewCapacity for String
{
fn new() -> Self
{
Self::new()
}
fn with_capacity(cap: usize) -> Self
{
Self::with_capacity(cap)
}
}
impl<T> NewCapacity for Vec<T>
{
fn new() -> Self
{
Self::new()
}
fn with_capacity(cap: usize) -> Self
{
Self::with_capacity(cap)
}
}
pub fn hint_cap<T: NewCapacity, I: Iterator>(iter: &I) -> T
{
match iter.size_hint() {
(0, Some(0)) | (0, None) => T::new(),
(_, Some(x)) | (x, _) => T::with_capacity(x)
}
}
#[macro_export] macro_rules! opaque_error {
($msg:literal) => {
{
#[derive(Debug)]
struct OpaqueError;
impl ::std::error::Error for OpaqueError{}
impl ::std::fmt::Display for OpaqueError
{
fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result
{
write!(f, $msg)
}
}
OpaqueError
}
};
($msg:literal $($tt:tt)*) => {
{
#[derive(Debug)]
struct OpaqueError(String);
impl ::std::error::Error for OpaqueError{}
impl ::std::fmt::Display for OpaqueError
{
fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result
{
write!(f, "{}", self.0)
}
}
OpaqueError(format!($msg $($tt)*))
}
};
(yield $msg:literal $($tt:tt)*) => {
{
#[derive(Debug)]
struct OpaqueError<'a>(fmt::Arguments<'a>);
impl ::std::error::Error for OpaqueError{}
impl ::std::fmt::Display for OpaqueError
{
fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result
{
write!(f, "{}", self.0)
}
}
OpaqueError(format_args!($msg $($tt)*))
}
};
}