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 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367
use core::{
cmp::Ordering,
iter::{
Chain, Cloned, Copied, Cycle, Enumerate, FlatMap, Fuse, Inspect, Map, Peekable, Rev, Take,
},
num::NonZeroUsize,
};
use crate::NonEmpty;
macro_rules! unwrap {
($expr:expr) => {
match $expr {
Some(it) => it,
// Safety:
// - NonEmpty<impl Iterator> is only constructed from known NonEmpty items
// - NonEmpty<impl Iterator> does give out mutable access to the inner iterator
// (so it always has one element)
None => unsafe { crate::unreachable() },
}
};
}
/// Methods on [`Iterator`]s with a non-empty invariant.
///
/// See [`Self::relax`] to access the normal iterator inside.
impl<I> NonEmpty<I>
where
I: Iterator,
{
/// [`NonEmpty`] version of [`Iterator::next`].
/// ```
/// # use nunny::{vec};
/// let v = vec![1, 2, 3];
/// let _: Option<&u8> = v.iter().next();
/// // ^ normally you have to handle the empty case
/// let _: &u8 = v.iter_ne().first();
/// // ^ but we know there is at least one element
/// ```
pub fn first(mut self) -> I::Item {
unwrap!(self.inner.next())
}
/// [`NonEmpty`] version of [`Iterator::last`].
/// ```
/// # use nunny::{vec};
/// let v = vec![1, 2, 3];
/// let _: Option<&u8> = v.iter().last();
/// // ^ normally you have to handle the empty case
/// let _: &u8 = v.iter_ne().last();
/// // ^ but we know there is at least one element
/// ```
pub fn last(self) -> I::Item {
unwrap!(self.inner.last())
}
/// [`NonEmpty`] version of [`Iterator::map`].
/// ```
/// # use nunny::{slice};
/// let iter = slice![1, 2, 3].iter_ne();
/// assert_eq!(
/// iter.map(|it| *it * 2).last(),
/// // ^ the invariant is maintained
/// // so we _know_ there's a last element
/// 6
/// );
/// ```
pub fn map<B, F>(self, f: F) -> NonEmpty<Map<I, F>>
where
F: FnMut(I::Item) -> B,
{
NonEmpty {
inner: self.inner.map(f),
}
}
/// [`NonEmpty`] version of [`Iterator::chain`].
/// ```
/// # use nunny::{slice};
/// let iter = slice![1, 2].iter_ne();
/// assert_eq!(
/// iter.chain(&[3]).last(),
/// // ^ the invariant is maintained
/// // so we _know_ there's a last element
/// &3
/// );
/// ```
pub fn chain<U>(self, other: U) -> NonEmpty<Chain<I, <U as IntoIterator>::IntoIter>>
where
U: IntoIterator<Item = I::Item>,
{
NonEmpty {
inner: self.inner.chain(other),
}
}
/// [`NonEmpty`] version of [`Iterator::enumerate`].
/// ```
/// # use nunny::{slice};
/// let iter = slice!['a', 'b'].iter_ne();
/// assert_eq!(
/// iter.enumerate().last(),
/// // ^ the invariant is maintained
/// // so we _know_ there's a last element
/// (1, &'b')
/// );
/// ```
pub fn enumerate(self) -> NonEmpty<Enumerate<I>> {
NonEmpty {
inner: self.inner.enumerate(),
}
}
/// [`NonEmpty`] version of [`Iterator::peekable`], allowing you to use
/// [`Self::peek`] and [`Self::peek_mut`]
/// ```
/// # use nunny::{vec, NonEmpty};
/// let mut peek_me = vec!['a', 'b'].into_iter_ne().peekable();
/// assert_eq!(
/// *peek_me.peek(),
/// 'a'
/// );
/// *peek_me.peek_mut() = 'b';
/// assert_eq!(
/// peek_me.collect_vec(),
/// ['b', 'b']
/// );
/// ```
pub fn peekable(self) -> NonEmpty<Peekable<I>> {
NonEmpty {
inner: self.inner.peekable(),
}
}
/// [`NonEmpty`] version of [`Iterator::take`].
///
/// Note that `n` cannot be zero, to maintain the [`NonEmpty`] invariant.
///
/// ```
/// # use nunny::{slice, nonzero};
/// let iter = slice!['a', 'b'].iter_ne();
/// assert_eq!(
/// iter.take(nonzero!(1)).last(),
/// // ^ compile time checked
/// &'a'
/// )
/// ```
pub fn take(self, n: NonZeroUsize) -> NonEmpty<Take<I>> {
NonEmpty {
inner: self.inner.take(n.get()),
}
}
// pub fn flat_map
/// [`NonEmpty`] version of [`Iterator::flatten`].
///
/// Note that the inner items must also be [`NonEmpty`], to maintain the invariant.
/// ```
/// use nunny::{vec};
/// let nested = vec![vec![1], vec![2, 3]];
/// assert_eq!(
/// nested.into_iter_ne().flatten().collect_vec(),
/// [1, 2, 3],
/// );
/// ```
#[allow(clippy::type_complexity)]
pub fn flatten<II, T>(self) -> NonEmpty<FlatMap<I, II, fn(I::Item) -> II>>
where
I: Iterator<Item = NonEmpty<II>>,
// ^ each item is nonempty
II: IntoIterator<Item = T>,
// TODO(aatifsyed): a trait NonEmptyIterator would make this more ergonomic
// See commit history for an attempt
{
NonEmpty {
inner: self.inner.flat_map(|it| it.inner),
}
}
/// [`NonEmpty`] version of [`Iterator::fuse`].
pub fn fuse(self) -> NonEmpty<Fuse<I>> {
NonEmpty {
inner: self.inner.fuse(),
}
}
/// [`NonEmpty`] version of [`Iterator::inspect`].
pub fn inspect<F>(self, f: F) -> NonEmpty<Inspect<I, F>>
where
F: FnMut(&I::Item),
{
NonEmpty {
inner: self.inner.inspect(f),
}
}
/// [`NonEmpty`] version of [`Iterator::reduce`].
/// ```
/// # use nunny::{vec};
/// # use core::cmp::min;
/// let v = vec![1, 2, 3];
/// let _: Option<&u8> = v.iter().reduce(min);
/// // ^ normally you have to handle the empty case
/// let _: &u8 = v.iter_ne().reduce(min);
/// // ^ but we know there is at least one element
/// ```
pub fn reduce<F>(self, f: F) -> I::Item
where
F: FnMut(I::Item, I::Item) -> I::Item,
{
unwrap!(self.inner.reduce(f))
}
/// [`NonEmpty`] version of [`Iterator::max`].
/// ```
/// # use nunny::{vec};
/// let v = vec![1, 2, 3];
/// let _: Option<&u8> = v.iter().max();
/// // ^ normally you have to handle the empty case
/// let _: &u8 = v.iter_ne().max();
/// // ^ but we know there is at least one element
/// ```
pub fn max(self) -> I::Item
where
I::Item: Ord,
{
unwrap!(self.inner.max())
}
/// [`NonEmpty`] version of [`Iterator::min`].
/// ```
/// # use nunny::{vec};
/// let v = vec![1, 2, 3];
/// let _: Option<&u8> = v.iter().min();
/// // ^ normally you have to handle the empty case
/// let _: &u8 = v.iter_ne().min();
/// // ^ but we know there is at least one element
/// ```
pub fn min(self) -> I::Item
where
I::Item: Ord,
{
unwrap!(self.inner.min())
}
/// [`NonEmpty`] version of [`Iterator::max_by_key`].
pub fn max_by_key<B, F>(self, f: F) -> I::Item
where
B: Ord,
F: FnMut(&I::Item) -> B,
{
unwrap!(self.inner.max_by_key(f))
}
/// [`NonEmpty`] version of [`Iterator::max_by`].
pub fn max_by<F>(self, compare: F) -> I::Item
where
F: FnMut(&I::Item, &I::Item) -> Ordering,
{
unwrap!(self.inner.max_by(compare))
}
/// [`NonEmpty`] version of [`Iterator::min_by_key`].
pub fn min_by_key<B, F>(self, f: F) -> I::Item
where
B: Ord,
F: FnMut(&I::Item) -> B,
{
unwrap!(self.inner.min_by_key(f))
}
/// [`NonEmpty`] version of [`Iterator::min_by`].
pub fn min_by<F>(self, compare: F) -> I::Item
where
F: FnMut(&I::Item, &I::Item) -> Ordering,
{
unwrap!(self.inner.min_by(compare))
}
/// [`NonEmpty`] version of [`Iterator::rev`].
pub fn rev(self) -> NonEmpty<Rev<I>>
where
I: DoubleEndedIterator,
{
NonEmpty {
inner: self.inner.rev(),
}
}
/// [`NonEmpty`] version of [`Iterator::unzip`].
#[cfg(feature = "alloc")]
#[cfg_attr(do_doc_cfg, doc(cfg(feature = "alloc")))]
pub fn unzip_vec<A, B>(self) -> (crate::Vec<A>, crate::Vec<B>)
where
I: Iterator<Item = (A, B)>,
{
let (a, b) = self.inner.unzip();
// Safety:
// - NonEmpty<impl Iterator> is only constructed from known NonEmpty items
// - NonEmpty<impl Iterator> does not allow mutable access to the inner iterator
// (so it always has one element)
unsafe { (crate::Vec::new_unchecked(a), crate::Vec::new_unchecked(b)) }
}
/// [`NonEmpty`] version of [`Iterator::copied`].
pub fn copied<'a, T>(self) -> NonEmpty<Copied<I>>
where
T: 'a + Copy,
I: Iterator<Item = &'a T>,
{
NonEmpty {
inner: self.inner.copied(),
}
}
/// [`NonEmpty`] version of [`Iterator::cloned`].
pub fn cloned<'a, T>(self) -> NonEmpty<Cloned<I>>
where
T: 'a + Clone,
I: Iterator<Item = &'a T>,
{
NonEmpty {
inner: self.inner.cloned(),
}
}
/// [`NonEmpty`] version of [`Iterator::cycle`].
pub fn cycle(self) -> NonEmpty<Cycle<I>>
where
I: Clone,
{
NonEmpty {
inner: self.inner.cycle(),
}
}
/// Remove the [`NonEmpty`] wrapper, allowing you to access normal iterator
/// methods like [`Iterator::filter`].
#[doc(alias = "into_iter")]
#[doc(alias = "into_inner")]
pub fn relax(self) -> I {
self.inner
}
/// Collect this iterator into a [`NonEmpty<Vec>`].
#[cfg(feature = "alloc")]
#[cfg_attr(do_doc_cfg, doc(cfg(feature = "alloc")))]
pub fn collect_vec(self) -> crate::Vec<I::Item> {
// Safety:
// - NonEmpty<impl Iterator> is only constructed from known NonEmpty items
// - NonEmpty<impl Iterator> does not allow mutable access to the inner iterator
// (so it always has one element)
unsafe { crate::Vec::new_unchecked(self.inner.collect()) }
}
/// Collect [`Ok`] items into a [`NonEmpty<Vec>`], short-circuiting on [`Err`].
#[cfg(feature = "alloc")]
#[cfg_attr(do_doc_cfg, doc(cfg(feature = "alloc")))]
pub fn try_collect_vec<T, E>(self) -> Result<crate::Vec<T>, E>
where
I: Iterator<Item = Result<T, E>>,
{
match self.inner.collect() {
// Safety:
// - NonEmpty<impl Iterator> is only constructed from known NonEmpty items
// - NonEmpty<impl Iterator> does not allow mutable access to the inner iterator
// (so it always has one element)
Ok(it) => Ok(unsafe { crate::Vec::new_unchecked(it) }),
Err(e) => Err(e),
}
}
}
impl<I> NonEmpty<Peekable<I>>
where
I: Iterator,
{
/// Peek this [`NonEmpty`] iterator, without advancing it.
///
/// See [`Self::peekable`].
pub fn peek(&mut self) -> &I::Item {
unwrap!(self.inner.peek())
}
/// Peek and modify this [`NonEmpty`] iterator, without advancing it.
///
/// See [`Self::peekable`].
pub fn peek_mut(&mut self) -> &mut I::Item {
unwrap!(self.inner.peek_mut())
}
}