//! Extensions use super::*; use std::{ borrow::{ Borrow, ToOwned, }, iter, }; pub trait Tuple2MapExt { fn map(self, fun: F) -> (U, U) where F: FnMut(T) -> U; } impl Tuple2MapExt for (T,T) { fn map(self, mut fun: F) -> (U, U) where F: FnMut(T) -> U { (fun(self.0), fun(self.1)) } } pub trait JitterExt { /// Produce a random value between `self.0` and `self.1` inclusive fn jitter(self) -> T; } impl JitterExt for (T, T) where T: rand::distributions::uniform::SampleUniform { fn jitter(self) -> T { util::jitter(self.0, self.1) } } pub trait Unreference { fn cloned(self) -> Option; } impl<'a, T> Unreference for Option<&'a T> where T: Clone { fn cloned(self) -> Option { self.map(Clone::clone) } } /// An iterator over `char` that maps certain characters to others pub struct CharSubstituteIter<'map, I, T= char> where I: Iterator, { iter: I, map: &'map smallmap::Map, } impl<'a, I, T> Iterator for CharSubstituteIter<'a, I, T> where I: Iterator, T: From + smallmap::Collapse, char: Borrow { type Item = T; fn next(&mut self) -> Option { self.iter.next() .map(|item| self.map.get(&item) .cloned() .map(T::from) .unwrap_or(item)) } #[inline] fn size_hint(&self) -> (usize, Option) { self.iter.size_hint() } } impl<'a, I, T> DoubleEndedIterator for CharSubstituteIter<'a, I, T> where I: Iterator + DoubleEndedIterator, T: From + smallmap::Collapse, char: Borrow { fn next_back(&mut self) -> Option { self.iter.next_back() .map(|item| self.map.get(&item) .cloned() .map(T::from) .unwrap_or(item)) } } impl<'a, I, T> iter::FusedIterator for CharSubstituteIter<'a, I, T> where I: Iterator + iter::FusedIterator, T: From + smallmap::Collapse, char: Borrow{} impl<'a, I, T> iter::ExactSizeIterator for CharSubstituteIter<'a, I, T> where I: Iterator + ExactSizeIterator, T: From + smallmap::Collapse, char: Borrow{} pub trait CharMapExt: Sized + IntoIterator { /// Creates an iterator that maps chars over this one fn replace_chars(self, map: &smallmap::Map) -> CharSubstituteIter<'_, Self::IntoIter, T>; } impl CharMapExt for S where S: IntoIterator, T: From + smallmap::Collapse, char: Borrow { #[inline] fn replace_chars(self, map: &smallmap::Map) -> CharSubstituteIter<'_, Self::IntoIter, T> { CharSubstituteIter { iter: self.into_iter(), map, } } }