This commit is contained in:
nora 2023-12-04 21:21:19 +01:00
parent 93af372574
commit b12e92a5cb
8 changed files with 238 additions and 10 deletions

45
helper/src/ext.rs Normal file
View file

@ -0,0 +1,45 @@
use std::mem::MaybeUninit;
use nom::{character::complete::digit1, combinator::map, IResult};
pub fn integer(input: &str) -> IResult<&str, u64> {
map(digit1, |d: &str| d.parse::<u64>().unwrap())(input)
}
#[derive(Debug)]
pub struct CollectArrayError;
/// i will not use itertools i will not use itertools i will not use itertools i will not use itertools
pub trait IteratorExt: Iterator {
/// Collect an iterator into an array.
/// If `next` panics, collected items are leaked. Too bad!
fn collect_array<const N: usize>(&mut self) -> Result<[Self::Item; N], CollectArrayError> {
// SAFETY: Uninit is valid for MaybeUninit
let mut array: [MaybeUninit<Self::Item>; N] = unsafe { MaybeUninit::uninit().assume_init() };
for i in 0..array.len() {
array[i].write(self.next().ok_or(CollectArrayError)?);
}
if self.next().is_some() {
return Err(CollectArrayError);
}
// SAFETY: All elements have been initialized
Ok(array.map(|elem| unsafe { elem.assume_init() }))
}
}
impl<I: Iterator> IteratorExt for I {}
#[cfg(test)]
mod tests {
use crate::IteratorExt;
#[test]
fn collect_array() {
assert!([0, 1].into_iter().collect_array::<3>().is_err());
assert!([0, 1].into_iter().collect_array::<1>().is_err());
assert_eq!([0, 1].into_iter().collect_array().unwrap(), [0, 1]);
}
}

View file

@ -1,11 +1,10 @@
mod cmd;
mod ext;
use std::{borrow::Cow, fmt::Debug};
use nom::{character::complete::digit1, combinator::map, IResult};
pub use self::cmd::main;
pub use divan;
pub use self::ext::*;
pub type Solution = fn(&str) -> u64;
@ -123,7 +122,7 @@ macro_rules! benchmarks {
#[macro_export]
macro_rules! _bench_sample_count {
(;$($tt:tt)*) => {
#[::divan::bench(sample_count = 10_000)]
#[::divan::bench(sample_count = 5000)]
$($tt)*
};
($sample_count:expr; $($tt:tt)*) => {
@ -209,7 +208,3 @@ macro_rules! tests {
}
};
}
pub fn integer(input: &str) -> IResult<&str, u64> {
map(digit1, |d: &str| d.parse::<u64>().unwrap())(input)
}