use bigdecimal::Zero;
use crate::{
BigDecimal, BigInt, ByteBuffer, IndexMap, Instant,
schema::{Document, NULL},
serde::{MaybeBuilt, serializers::SerializeWithSchema},
};
pub trait ErrorCorrection {
type Value;
fn correct(self) -> Self::Value;
}
pub trait ErrorCorrectionDefault {
fn default() -> Self;
}
macro_rules! correction_default_impl {
($t:ty, $v:expr) => {
impl ErrorCorrectionDefault for $t {
#[inline(always)]
fn default() -> $t {
$v
}
}
};
}
correction_default_impl!(bool, true);
correction_default_impl!(i8, 0i8);
correction_default_impl!(i16, 0i16);
correction_default_impl!(i32, 0i32);
correction_default_impl!(i64, 0i64);
correction_default_impl!(f32, 0f32);
correction_default_impl!(f64, 0f64);
correction_default_impl!(
Instant,
Instant::from_epoch_milliseconds(0).expect("Instant default should always be instantiatable")
);
correction_default_impl!(String, String::new());
correction_default_impl!(BigDecimal, BigDecimal::zero());
correction_default_impl!(BigInt, BigInt::zero());
correction_default_impl!(ByteBuffer, ByteBuffer::new());
impl ErrorCorrectionDefault for Box<dyn Document> {
fn default() -> Self {
NULL.clone()
}
}
impl<E> ErrorCorrectionDefault for Vec<E> {
fn default() -> Self {
Vec::new()
}
}
impl<E> ErrorCorrectionDefault for IndexMap<String, E> {
fn default() -> Self {
IndexMap::new()
}
}
impl<E: ErrorCorrectionDefault> ErrorCorrectionDefault for Box<E> {
fn default() -> Self {
Box::new(E::default())
}
}
impl<
S: ErrorCorrectionDefault + SerializeWithSchema,
B: ErrorCorrection<Value = S> + SerializeWithSchema,
> ErrorCorrectionDefault for MaybeBuilt<S, B>
{
fn default() -> Self {
MaybeBuilt::Struct(S::default())
}
}
impl<
S: ErrorCorrectionDefault + SerializeWithSchema,
B: ErrorCorrection<Value = S> + SerializeWithSchema,
> ErrorCorrection for MaybeBuilt<S, B>
{
type Value = S;
fn correct(self) -> Self::Value {
match self {
MaybeBuilt::Struct(s) => s,
MaybeBuilt::Builder(b) => b.correct(),
}
}
}
impl<S, B: ErrorCorrection<Value = S>> ErrorCorrection for Option<B> {
type Value = Option<S>;
#[inline]
fn correct(self) -> Self::Value {
self.map(ErrorCorrection::correct)
}
}
impl<E: ErrorCorrection> ErrorCorrection for Box<E> {
type Value = Box<E::Value>;
fn correct(self) -> Self::Value {
Box::new((*self).correct())
}
}
impl<S, B: ErrorCorrection<Value = S>> ErrorCorrection for Vec<B> {
type Value = Vec<S>;
fn correct(self) -> Self::Value {
let mut results = Vec::with_capacity(self.len());
for builder in self {
results.push(builder.correct());
}
results
}
}
impl<S, B: ErrorCorrection<Value = S>> ErrorCorrection for IndexMap<String, B> {
type Value = IndexMap<String, S>;
fn correct(self) -> Self::Value {
let mut results = IndexMap::with_capacity(self.len());
for (key, builder) in self {
let _ = results.insert(key, builder.correct());
}
results
}
}