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
pub mod read;
pub mod write;

use std::ops::{Residual, Try};

pub use read::*;
pub use write::*;

pub use strict_result::*;

#[derive(Debug, thiserror::Error)]
#[error("cannot convert {value} into {type_}\n{source}")]
pub struct CastError {
	source: Box<dyn std::error::Error + Sync + Send>,
	type_: &'static str,
	value: String,
}

pub fn cast<A, B>(a: A) -> Result<B, CastError> where
	A: std::fmt::Debug + Clone,
	B: TryFrom<A>,
	B::Error: std::error::Error + Sync + Send + 'static,
{
	a.clone().try_into().map_err(|e| cast_error::<B>(a, e))
}

pub fn cast_bool(a: impl Into<u64> + std::fmt::Debug + Clone) -> Result<bool, CastError> {
	match a.into() {
		0 => Ok(false),
		1 => Ok(true),
		n => Err(cast_error::<bool>(n, "out of range integral type conversion attempted")),
	}
}

pub fn cast_error<T>(
	val: impl std::fmt::Debug,
	cause: impl Into<Box<dyn std::error::Error + Sync + Send>>,
) -> CastError {
	CastError {
		type_: std::any::type_name::<T>(),
		value: format!("{:?}", val),
		source: cause.into()
	}
}

pub macro ensure {
	($cond:expr, $($t:tt)*) => {
		if !($cond) {
			bail!($($t)*)
		}
	},
	($cond:expr) => {
		ensure!($cond, stringify!($cond).into())
	}
}

pub macro bail {
	($str:literal $($arg:tt)*) => {
		bail!(format!($str $($arg)*).into())
	},
	($e:expr) => {
		Err($e).strict()?
	}
}

pub fn array<const N: usize, R: Try>(
	mut f: impl FnMut() -> R,
) -> <R::Residual as Residual<[R::Output; N]>>::TryType where
	R::Residual: Residual<[R::Output; N]>,
{
	[(); N].try_map(move |()| f())
}

pub fn list<V, E>(
	n: usize,
	mut f: impl FnMut() -> Result<V, E>,
) -> Result<Vec<V>, E> {
	let mut a = Vec::with_capacity(n);
	for _ in 0..n {
		a.push(f()?);
	}
	Ok(a)
}