use std::io::Write;
use serde::de;
use crate::error::Result;
use crate::{Deserializer, Serializer};
#[derive(Clone, Copy, Debug)]
pub struct Config {
pub(crate) max_depth: usize,
pub(crate) use_form_encoding: bool,
pub(crate) array_format: ArrayFormat,
pub(crate) duplicate_key_behavior: DuplicateKeyBehavior,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ArrayFormat {
Indexed,
EmptyIndexed,
Unindexed,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum DuplicateKeyBehavior {
#[default]
TakeLast,
Error,
}
impl Default for Config {
fn default() -> Self {
Self::new()
}
}
impl Config {
pub const fn new() -> Self {
Self {
max_depth: 5,
use_form_encoding: cfg!(feature = "default_to_form_encoding"),
array_format: ArrayFormat::Indexed,
duplicate_key_behavior: DuplicateKeyBehavior::TakeLast,
}
}
pub const fn max_depth(mut self, max_depth: usize) -> Self {
self.max_depth = max_depth;
self
}
pub const fn use_form_encoding(mut self, use_form_encoding: bool) -> Self {
self.use_form_encoding = use_form_encoding;
self
}
pub const fn array_format(mut self, array_format: ArrayFormat) -> Self {
self.array_format = array_format;
self
}
pub const fn duplicate_key_behavior(
mut self,
duplicate_key_behavior: DuplicateKeyBehavior,
) -> Self {
self.duplicate_key_behavior = duplicate_key_behavior;
self
}
pub fn deserialize_bytes<'de, T: de::Deserialize<'de>>(self, input: &'de [u8]) -> Result<T> {
T::deserialize(Deserializer::with_config(self, input)?)
}
pub fn deserialize_str<'de, T: de::Deserialize<'de>>(self, input: &'de str) -> Result<T> {
self.deserialize_bytes(input.as_bytes())
}
pub fn serialize_string<T: serde::Serialize>(self, input: &T) -> Result<String> {
let mut buffer = Vec::with_capacity(128);
let mut serializer = Serializer::new(&mut buffer, self);
input.serialize(&mut serializer)?;
String::from_utf8(buffer).map_err(crate::Error::from)
}
pub fn serialize_to_writer<T: serde::Serialize, W: Write>(
self,
input: &T,
writer: &mut W,
) -> Result<()> {
let mut serializer = Serializer::new(writer, self);
input.serialize(&mut serializer)
}
}