#![doc = include_str!("../../docs/ser.md")]
use std::borrow::Cow;
use serde::{Serialize, Serializer};
mod context;
mod scope;
mod value;
mod void_serializer;
mod wrapper;
pub use scope::{
EndScope, EnumVariantScope, ErrorScope, MapInsertLocation, MapKeyScope, MapKeySelector,
MapScope, SeqScope, StartScope, StructScope, TupleScope, TupleStructScope, ValueScope,
};
use context::SerializableWithContext;
use crate::Path;
pub trait Hooks {
#[allow(unused_variables)]
fn on_start(&self, start: &mut StartScope) {}
#[allow(unused_variables)]
fn on_end<Error: serde::ser::Error>(&self, end: &mut EndScope<Error>) {}
#[allow(unused_variables)]
fn on_value<S: Serializer>(&self, path: &Path, value: &mut ValueScope<S>) {}
#[allow(unused_variables)]
fn on_struct(&self, path: &Path, st: &mut StructScope) {}
#[allow(unused_variables)]
fn on_seq(&self, path: &Path, seq: &mut SeqScope) {}
#[allow(unused_variables)]
fn on_tuple(&self, path: &Path, tpl: &mut TupleScope, seq: &mut SeqScope) {}
#[allow(unused_variables)]
fn on_tuple_struct(&self, path: &Path, tpl: &mut TupleStructScope, seq: &mut SeqScope) {}
#[allow(unused_variables)]
fn on_map(&self, path: &Path, map: &mut MapScope) {}
#[allow(unused_variables)]
fn on_map_key<S: Serializer>(&self, path: &Path, map_key: &mut MapKeyScope<S>) {}
#[allow(unused_variables)]
fn on_enum_variant(&self, path: &Path, ev: &mut EnumVariantScope) {}
#[allow(unused_variables)]
fn on_struct_variant(&self, path: &Path, ev: &mut EnumVariantScope, st: &mut StructScope) {}
#[allow(unused_variables)]
fn on_tuple_variant(
&self,
path: &Path,
ev: &mut EnumVariantScope,
tpl: &mut TupleScope,
seq: &mut SeqScope,
) {
}
#[allow(unused_variables)]
fn on_scope_error(&self, path: &Path, err: &mut ErrorScope) {}
}
#[derive(Debug, thiserror::Error, Eq, PartialEq)]
pub enum HooksError {
#[error("cannot add entry with an index {0}, please specify key value")]
CannotAddEntryByIndex(usize),
#[error("key {0} not found")]
KeyNotFound(MapKeySelector),
#[error("field \"{0}\" not found")]
FieldNotFound(Cow<'static, str>),
#[error("value is not serializable: {0}")]
ValueNotSerializable(String),
#[error("index \"{0}\" not found")]
IndexNotFound(usize),
#[error("cannot flatten unsupported data type \"{0}\"")]
CannotFlattenUnsupportedDataType(&'static str),
}
pub fn hook<'s, 'h: 's, T: Serialize + ?Sized, H: Hooks>(
serializable: &'s T,
hooks: &'h H,
) -> impl Serialize + 's {
SerializableWithContext::new(serializable, hooks)
}
pub fn invoke_hooks<'s, 'h: 's, T: Serialize + ?Sized, H: Hooks>(
serializable: &'s T,
hooks: &'h H,
) -> Result<(), void_serializer::Error> {
hook(serializable, hooks).serialize(void_serializer::VoidSerializer)
}