use serde::{Serialize, ser};
use crate::error::{Error, ErrorKind, Result};
pub(crate) fn is_valid_name(name: &str) -> bool {
let mut chars = name.chars();
match chars.next() {
Some(c) if c.is_ascii_alphabetic() || c == '*' => {}
_ => return false,
}
chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '*'))
}
fn validate_name(name: &str) -> Result<()> {
if is_valid_name(name) {
Ok(())
} else {
Err(ErrorKind::InvalidSettingName(name.to_string()).into())
}
}
pub(crate) fn escape_str_into(out: &mut String, s: &str) {
out.push('"');
for ch in s.chars() {
match ch {
'"' => out.push_str("\\\""),
'\\' => out.push_str("\\\\"),
'\n' => out.push_str("\\n"),
'\r' => out.push_str("\\r"),
'\t' => out.push_str("\\t"),
'\x0C' => out.push_str("\\f"),
'\x08' => out.push_str("\\b"),
'\x0B' => out.push_str("\\v"),
'\x07' => out.push_str("\\a"),
c if (c as u32) < 0x20 => {
out.push_str(&format!("\\x{:02x}", c as u32));
}
_ => out.push(ch),
}
}
out.push('"');
}
#[derive(Debug, Clone, PartialEq)]
#[must_use]
pub struct WriteOptions {
float_precision: Option<u8>,
scientific_notation: bool,
tab_width: u8,
semicolon_separators: bool,
colon_assignment_for_groups: bool,
colon_assignment_for_non_groups: bool,
open_brace_on_separate_line: bool,
}
impl Default for WriteOptions {
fn default() -> Self {
WriteOptions {
float_precision: None,
scientific_notation: false,
tab_width: 2,
semicolon_separators: true,
colon_assignment_for_groups: false,
colon_assignment_for_non_groups: false,
open_brace_on_separate_line: false,
}
}
}
impl WriteOptions {
pub fn new() -> Self {
WriteOptions::default()
}
pub fn float_precision(mut self, digits: u8) -> Self {
self.float_precision = Some(digits.min(17));
self
}
pub fn scientific_notation(mut self, enabled: bool) -> Self {
self.scientific_notation = enabled;
self
}
pub fn tab_width(mut self, width: u8) -> Self {
self.tab_width = width.min(15);
self
}
pub fn semicolon_separators(mut self, enabled: bool) -> Self {
self.semicolon_separators = enabled;
self
}
pub fn colon_assignment_for_groups(mut self, enabled: bool) -> Self {
self.colon_assignment_for_groups = enabled;
self
}
pub fn colon_assignment_for_non_groups(mut self, enabled: bool) -> Self {
self.colon_assignment_for_non_groups = enabled;
self
}
pub fn open_brace_on_separate_line(mut self, enabled: bool) -> Self {
self.open_brace_on_separate_line = enabled;
self
}
}
pub(crate) fn write_f64(out: &mut String, v: f64, options: &WriteOptions) -> Result<()> {
if !v.is_finite() {
return Err(ErrorKind::NonFiniteFloat.into());
}
let s = match (options.float_precision, options.scientific_notation) {
(None, false) => v.to_string(),
(None, true) => format!("{:e}", v),
(Some(p), false) => format!("{:.*}", p as usize, v),
(Some(p), true) => format!("{:.*e}", p as usize, v),
};
out.push_str(&s);
if !s.contains('.') && !s.contains('e') && !s.contains('E') {
out.push_str(".0");
}
Ok(())
}
pub struct Serializer {
output: String,
indent_level: usize,
options: WriteOptions,
at_root: bool,
}
impl Serializer {
pub fn new() -> Self {
Serializer::with_options(WriteOptions::default())
}
pub fn with_options(options: WriteOptions) -> Self {
Serializer {
output: String::new(),
indent_level: 0,
options,
at_root: true,
}
}
pub fn into_output(self) -> String {
self.output
}
fn indent(&mut self) {
self.indent_level += 1;
}
fn dedent(&mut self) {
self.indent_level = self.indent_level.saturating_sub(1);
}
fn write_indent(&mut self) {
if self.options.tab_width == 0 {
for _ in 0..self.indent_level {
self.output.push('\t');
}
} else {
for _ in 0..(self.indent_level * self.options.tab_width as usize) {
self.output.push(' ');
}
}
}
}
impl Default for Serializer {
fn default() -> Self {
Serializer::new()
}
}
pub fn to_string<T>(value: &T) -> Result<String>
where
T: ?Sized + Serialize,
{
to_string_with_options(value, &WriteOptions::default())
}
pub fn to_string_with_options<T>(value: &T, options: &WriteOptions) -> Result<String>
where
T: ?Sized + Serialize,
{
let mut serializer = Serializer::with_options(options.clone());
value.serialize(&mut serializer)?;
Ok(serializer.output)
}
pub fn to_writer<W, T>(mut writer: W, value: &T) -> Result<()>
where
W: std::io::Write,
T: ?Sized + Serialize,
{
let s = to_string(value)?;
writer
.write_all(s.as_bytes())
.map_err(|e| ErrorKind::Io(e.to_string()))?;
Ok(())
}
struct NoneProbe;
fn value_is_none<T: ?Sized + Serialize>(value: &T) -> bool {
value.serialize(NoneProbe).unwrap_or(false)
}
struct GroupProbe<'a> {
is_group: &'a mut bool,
}
fn value_is_group<T: ?Sized + Serialize>(value: &T) -> bool {
let mut is_group = false;
let _ = value.serialize(GroupProbe {
is_group: &mut is_group,
});
is_group
}
macro_rules! group_probe_false {
($($method:ident: $ty:ty,)*) => {
$(fn $method(self, _v: $ty) -> Result<()> { Ok(()) })*
};
}
impl ser::Serializer for GroupProbe<'_> {
type Ok = ();
type Error = Error;
type SerializeSeq = ser::Impossible<(), Error>;
type SerializeTuple = ser::Impossible<(), Error>;
type SerializeTupleStruct = ser::Impossible<(), Error>;
type SerializeTupleVariant = ser::Impossible<(), Error>;
type SerializeMap = ser::Impossible<(), Error>;
type SerializeStruct = ser::Impossible<(), Error>;
type SerializeStructVariant = ser::Impossible<(), Error>;
group_probe_false! {
serialize_bool: bool, serialize_i8: i8, serialize_i16: i16,
serialize_i32: i32, serialize_i64: i64, serialize_u8: u8,
serialize_u16: u16, serialize_u32: u32, serialize_u64: u64,
serialize_f32: f32, serialize_f64: f64, serialize_char: char,
serialize_str: &str, serialize_bytes: &[u8],
}
fn serialize_none(self) -> Result<()> {
Ok(())
}
fn serialize_some<T: ?Sized + Serialize>(self, value: &T) -> Result<()> {
value.serialize(GroupProbe {
is_group: self.is_group,
})
}
fn serialize_unit(self) -> Result<()> {
Ok(())
}
fn serialize_unit_struct(self, _name: &'static str) -> Result<()> {
Ok(())
}
fn serialize_unit_variant(
self,
_name: &'static str,
_variant_index: u32,
_variant: &'static str,
) -> Result<()> {
Ok(())
}
fn serialize_newtype_struct<T: ?Sized + Serialize>(
self,
_name: &'static str,
value: &T,
) -> Result<()> {
value.serialize(GroupProbe {
is_group: self.is_group,
})
}
fn serialize_newtype_variant<T: ?Sized + Serialize>(
self,
_name: &'static str,
_variant_index: u32,
_variant: &'static str,
_value: &T,
) -> Result<()> {
*self.is_group = true;
Ok(())
}
fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq> {
Err(ErrorKind::Message("probe".to_string()).into())
}
fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple> {
Err(ErrorKind::Message("probe".to_string()).into())
}
fn serialize_tuple_struct(
self,
_name: &'static str,
_len: usize,
) -> Result<Self::SerializeTupleStruct> {
Err(ErrorKind::Message("probe".to_string()).into())
}
fn serialize_tuple_variant(
self,
_name: &'static str,
_variant_index: u32,
_variant: &'static str,
_len: usize,
) -> Result<Self::SerializeTupleVariant> {
*self.is_group = true;
Err(ErrorKind::Message("probe".to_string()).into())
}
fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap> {
*self.is_group = true;
Err(ErrorKind::Message("probe".to_string()).into())
}
fn serialize_struct(self, _name: &'static str, _len: usize) -> Result<Self::SerializeStruct> {
*self.is_group = true;
Err(ErrorKind::Message("probe".to_string()).into())
}
fn serialize_struct_variant(
self,
_name: &'static str,
_variant_index: u32,
_variant: &'static str,
_len: usize,
) -> Result<Self::SerializeStructVariant> {
*self.is_group = true;
Err(ErrorKind::Message("probe".to_string()).into())
}
}
macro_rules! probe_false {
($($method:ident: $ty:ty,)*) => {
$(fn $method(self, _v: $ty) -> Result<bool> { Ok(false) })*
};
}
impl ser::Serializer for NoneProbe {
type Ok = bool;
type Error = Error;
type SerializeSeq = ser::Impossible<bool, Error>;
type SerializeTuple = ser::Impossible<bool, Error>;
type SerializeTupleStruct = ser::Impossible<bool, Error>;
type SerializeTupleVariant = ser::Impossible<bool, Error>;
type SerializeMap = ser::Impossible<bool, Error>;
type SerializeStruct = ser::Impossible<bool, Error>;
type SerializeStructVariant = ser::Impossible<bool, Error>;
fn serialize_none(self) -> Result<bool> {
Ok(true)
}
fn serialize_some<T: ?Sized + Serialize>(self, _value: &T) -> Result<bool> {
Ok(false)
}
probe_false! {
serialize_bool: bool, serialize_i8: i8, serialize_i16: i16,
serialize_i32: i32, serialize_i64: i64, serialize_u8: u8,
serialize_u16: u16, serialize_u32: u32, serialize_u64: u64,
serialize_f32: f32, serialize_f64: f64, serialize_char: char,
serialize_str: &str, serialize_bytes: &[u8],
}
fn serialize_unit(self) -> Result<bool> {
Ok(false)
}
fn serialize_unit_struct(self, _name: &'static str) -> Result<bool> {
Ok(false)
}
fn serialize_unit_variant(
self,
_name: &'static str,
_variant_index: u32,
_variant: &'static str,
) -> Result<bool> {
Ok(false)
}
fn serialize_newtype_struct<T: ?Sized + Serialize>(
self,
_name: &'static str,
_value: &T,
) -> Result<bool> {
Ok(false)
}
fn serialize_newtype_variant<T: ?Sized + Serialize>(
self,
_name: &'static str,
_variant_index: u32,
_variant: &'static str,
_value: &T,
) -> Result<bool> {
Ok(false)
}
fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq> {
Err(ErrorKind::Message("probe".to_string()).into())
}
fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple> {
Err(ErrorKind::Message("probe".to_string()).into())
}
fn serialize_tuple_struct(
self,
_name: &'static str,
_len: usize,
) -> Result<Self::SerializeTupleStruct> {
Err(ErrorKind::Message("probe".to_string()).into())
}
fn serialize_tuple_variant(
self,
_name: &'static str,
_variant_index: u32,
_variant: &'static str,
_len: usize,
) -> Result<Self::SerializeTupleVariant> {
Err(ErrorKind::Message("probe".to_string()).into())
}
fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap> {
Err(ErrorKind::Message("probe".to_string()).into())
}
fn serialize_struct(self, _name: &'static str, _len: usize) -> Result<Self::SerializeStruct> {
Err(ErrorKind::Message("probe".to_string()).into())
}
fn serialize_struct_variant(
self,
_name: &'static str,
_variant_index: u32,
_variant: &'static str,
_len: usize,
) -> Result<Self::SerializeStructVariant> {
Err(ErrorKind::Message("probe".to_string()).into())
}
}
impl<'a> ser::Serializer for &'a mut Serializer {
type Ok = ();
type Error = Error;
type SerializeSeq = SeqSerializer<'a>;
type SerializeTuple = Self;
type SerializeTupleStruct = Self;
type SerializeTupleVariant = TupleVariantSerializer<'a>;
type SerializeMap = MapSerializer<'a>;
type SerializeStruct = MapSerializer<'a>;
type SerializeStructVariant = StructVariantSerializer<'a>;
fn serialize_bool(self, v: bool) -> Result<()> {
self.output += if v { "true" } else { "false" };
Ok(())
}
fn serialize_i8(self, v: i8) -> Result<()> {
self.serialize_i32(i32::from(v))
}
fn serialize_i16(self, v: i16) -> Result<()> {
self.serialize_i32(i32::from(v))
}
fn serialize_i32(self, v: i32) -> Result<()> {
self.output += &v.to_string();
Ok(())
}
fn serialize_i64(self, v: i64) -> Result<()> {
self.output += &v.to_string();
self.output += "L";
Ok(())
}
fn serialize_u8(self, v: u8) -> Result<()> {
self.serialize_u32(u32::from(v))
}
fn serialize_u16(self, v: u16) -> Result<()> {
self.serialize_u32(u32::from(v))
}
fn serialize_u32(self, v: u32) -> Result<()> {
self.output += &v.to_string();
if v > i32::MAX as u32 {
self.output += "L";
}
Ok(())
}
fn serialize_u64(self, v: u64) -> Result<()> {
if v > i64::MAX as u64 {
return Err(ErrorKind::IntegerOutOfRange.into());
}
self.output += &v.to_string();
self.output += "L";
Ok(())
}
fn serialize_f32(self, v: f32) -> Result<()> {
self.serialize_f64(f64::from(v))
}
fn serialize_f64(self, v: f64) -> Result<()> {
write_f64(&mut self.output, v, &self.options)
}
fn serialize_char(self, v: char) -> Result<()> {
self.serialize_str(&v.to_string())
}
fn serialize_str(self, v: &str) -> Result<()> {
escape_str_into(&mut self.output, v);
Ok(())
}
fn serialize_bytes(self, v: &[u8]) -> Result<()> {
use ser::SerializeSeq;
let mut seq = self.serialize_seq(Some(v.len()))?;
for byte in v {
seq.serialize_element(byte)?;
}
seq.end()
}
fn serialize_none(self) -> Result<()> {
Err(ErrorKind::TypeNotSupported("Option::None".to_string()).into())
}
fn serialize_some<T>(self, value: &T) -> Result<()>
where
T: ?Sized + Serialize,
{
value.serialize(self)
}
fn serialize_unit(self) -> Result<()> {
Err(ErrorKind::UnitNotSupported.into())
}
fn serialize_unit_struct(self, _name: &'static str) -> Result<()> {
self.serialize_unit()
}
fn serialize_unit_variant(
self,
_name: &'static str,
_variant_index: u32,
variant: &'static str,
) -> Result<()> {
self.serialize_str(variant)
}
fn serialize_newtype_struct<T>(self, _name: &'static str, value: &T) -> Result<()>
where
T: ?Sized + Serialize,
{
value.serialize(self)
}
fn serialize_newtype_variant<T>(
self,
_name: &'static str,
_variant_index: u32,
variant: &'static str,
value: &T,
) -> Result<()>
where
T: ?Sized + Serialize,
{
validate_name(variant)?;
self.at_root = false;
self.output += "{ ";
self.output += variant;
self.output += " = ";
value.serialize(&mut *self)?;
self.output += "; }";
Ok(())
}
fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq> {
self.at_root = false;
Ok(SeqSerializer {
elements: Vec::with_capacity(len.unwrap_or(0)),
ser: self,
})
}
fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple> {
self.at_root = false;
self.output.push('(');
Ok(self)
}
fn serialize_tuple_struct(
self,
_name: &'static str,
_len: usize,
) -> Result<Self::SerializeTupleStruct> {
self.at_root = false;
self.output.push('(');
Ok(self)
}
fn serialize_tuple_variant(
self,
_name: &'static str,
_variant_index: u32,
variant: &'static str,
_len: usize,
) -> Result<Self::SerializeTupleVariant> {
validate_name(variant)?;
self.at_root = false;
self.output += "{ ";
self.output += variant;
self.output += " = (";
Ok(TupleVariantSerializer { ser: self })
}
fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap> {
let root = std::mem::replace(&mut self.at_root, false);
if !root {
if self.options.open_brace_on_separate_line {
self.output.push('\n');
self.write_indent();
}
self.output.push('{');
self.indent();
}
Ok(MapSerializer {
ser: self,
root,
first: true,
pending_key: None,
})
}
fn serialize_struct(self, _name: &'static str, len: usize) -> Result<Self::SerializeStruct> {
self.serialize_map(Some(len))
}
fn serialize_struct_variant(
self,
_name: &'static str,
_variant_index: u32,
variant: &'static str,
_len: usize,
) -> Result<Self::SerializeStructVariant> {
validate_name(variant)?;
self.at_root = false;
self.output += "{ ";
self.output += variant;
self.output += " = {";
self.indent();
Ok(StructVariantSerializer { ser: self })
}
}
#[doc(hidden)]
pub struct MapSerializer<'a> {
ser: &'a mut Serializer,
root: bool,
first: bool,
pending_key: Option<String>,
}
impl MapSerializer<'_> {
fn begin_field(&mut self) {
let sep = self.ser.options.semicolon_separators;
if self.root {
if !self.first {
if sep {
self.ser.output.push(';');
}
self.ser.output.push('\n');
}
} else {
if !self.first && sep {
self.ser.output.push(';');
}
self.ser.output.push('\n');
self.ser.write_indent();
}
self.first = false;
}
fn write_assignment(&mut self, key: &str, value_is_group: bool) {
self.ser.output += key;
let colon = if value_is_group {
self.ser.options.colon_assignment_for_groups
} else {
self.ser.options.colon_assignment_for_non_groups
};
self.ser.output += if colon { " :" } else { " =" };
if !(value_is_group && self.ser.options.open_brace_on_separate_line) {
self.ser.output.push(' ');
}
}
fn finish(self) -> Result<()> {
let sep = self.ser.options.semicolon_separators;
if self.root {
if !self.first && sep {
self.ser.output.push(';');
}
} else {
self.ser.dedent();
if !self.first && sep {
self.ser.output.push(';');
}
self.ser.output.push('\n');
self.ser.write_indent();
self.ser.output.push('}');
}
Ok(())
}
}
impl ser::SerializeMap for MapSerializer<'_> {
type Ok = ();
type Error = Error;
fn serialize_key<T>(&mut self, key: &T) -> Result<()>
where
T: ?Sized + Serialize,
{
let mut key_capture = KeyCapture { key: String::new() };
key.serialize(&mut key_capture)?;
self.pending_key = Some(key_capture.key);
Ok(())
}
fn serialize_value<T>(&mut self, value: &T) -> Result<()>
where
T: ?Sized + Serialize,
{
let key = self.pending_key.take().ok_or_else(|| {
Error::from(ErrorKind::Message(
"serialize_value called without serialize_key".to_string(),
))
})?;
if value_is_none(value) {
return Ok(());
}
self.begin_field();
self.write_assignment(&key, value_is_group(value));
value.serialize(&mut *self.ser)
}
fn end(self) -> Result<()> {
self.finish()
}
}
impl ser::SerializeStruct for MapSerializer<'_> {
type Ok = ();
type Error = Error;
fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<()>
where
T: ?Sized + Serialize,
{
validate_name(key)?;
if value_is_none(value) {
return Ok(());
}
self.begin_field();
self.write_assignment(key, value_is_group(value));
value.serialize(&mut *self.ser)
}
fn end(self) -> Result<()> {
self.finish()
}
}
#[derive(Clone, Copy, PartialEq)]
enum ElemKind {
Bool,
Integer,
Integer64,
Float,
Str,
NonScalar,
}
impl ElemKind {
fn classify(rendered: &str) -> ElemKind {
match rendered.as_bytes().first() {
Some(b'"') => ElemKind::Str,
Some(b'{' | b'(' | b'[' | b'\n') => ElemKind::NonScalar,
Some(b't' | b'f') => ElemKind::Bool,
_ if rendered.contains('.') || rendered.contains('e') || rendered.contains('E') => {
ElemKind::Float
}
_ if rendered.ends_with('L') => ElemKind::Integer64,
_ => ElemKind::Integer,
}
}
fn same_scalar_type(self, other: ElemKind) -> bool {
let fold = |k| match k {
ElemKind::Integer64 => ElemKind::Integer,
k => k,
};
fold(self) == fold(other)
}
}
#[doc(hidden)]
pub struct SeqSerializer<'a> {
ser: &'a mut Serializer,
elements: Vec<(ElemKind, String)>,
}
impl ser::SerializeSeq for SeqSerializer<'_> {
type Ok = ();
type Error = Error;
fn serialize_element<T>(&mut self, value: &T) -> Result<()>
where
T: ?Sized + Serialize,
{
let mut tmp = Serializer {
output: String::new(),
indent_level: self.ser.indent_level,
options: self.ser.options.clone(),
at_root: false,
};
value.serialize(&mut tmp)?;
let kind = ElemKind::classify(&tmp.output);
self.elements.push((kind, tmp.output));
Ok(())
}
fn end(self) -> Result<()> {
let as_array = self.elements.iter().all(|(k, _)| *k != ElemKind::NonScalar)
&& self
.elements
.windows(2)
.all(|w| w[0].0.same_scalar_type(w[1].0));
if as_array {
let promote = self.elements.iter().any(|(k, _)| *k == ElemKind::Integer64)
&& self.elements.iter().any(|(k, _)| *k == ElemKind::Integer);
self.ser.output.push('[');
for (i, (kind, rendered)) in self.elements.iter().enumerate() {
if i > 0 {
self.ser.output.push_str(", ");
}
self.ser.output.push_str(rendered);
if promote && *kind == ElemKind::Integer {
self.ser.output.push('L');
}
}
self.ser.output.push(']');
} else {
self.ser.output.push('(');
for (i, (_, rendered)) in self.elements.iter().enumerate() {
if i > 0 {
self.ser.output.push_str(", ");
}
self.ser.output.push_str(rendered);
}
self.ser.output.push(')');
}
Ok(())
}
}
#[doc(hidden)]
pub struct TupleVariantSerializer<'a> {
ser: &'a mut Serializer,
}
impl ser::SerializeTupleVariant for TupleVariantSerializer<'_> {
type Ok = ();
type Error = Error;
fn serialize_field<T>(&mut self, value: &T) -> Result<()>
where
T: ?Sized + Serialize,
{
if !self.ser.output.ends_with('(') {
self.ser.output += ", ";
}
value.serialize(&mut *self.ser)
}
fn end(self) -> Result<()> {
self.ser.output += "); }";
Ok(())
}
}
#[doc(hidden)]
pub struct StructVariantSerializer<'a> {
ser: &'a mut Serializer,
}
impl ser::SerializeStructVariant for StructVariantSerializer<'_> {
type Ok = ();
type Error = Error;
fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<()>
where
T: ?Sized + Serialize,
{
validate_name(key)?;
if !self.ser.output.ends_with('{') {
self.ser.output.push(';');
}
self.ser.output.push('\n');
self.ser.write_indent();
self.ser.output += key;
self.ser.output += " = ";
value.serialize(&mut *self.ser)
}
fn end(self) -> Result<()> {
self.ser.dedent();
if !self.ser.output.ends_with('{') {
self.ser.output.push(';');
}
self.ser.output.push('\n');
self.ser.write_indent();
self.ser.output += "}; }";
Ok(())
}
}
impl ser::SerializeTuple for &mut Serializer {
type Ok = ();
type Error = Error;
fn serialize_element<T>(&mut self, value: &T) -> Result<()>
where
T: ?Sized + Serialize,
{
if !self.output.ends_with('(') {
self.output += ", ";
}
value.serialize(&mut **self)
}
fn end(self) -> Result<()> {
self.output.push(')');
Ok(())
}
}
impl ser::SerializeTupleStruct for &mut Serializer {
type Ok = ();
type Error = Error;
fn serialize_field<T>(&mut self, value: &T) -> Result<()>
where
T: ?Sized + Serialize,
{
if !self.output.ends_with('(') {
self.output += ", ";
}
value.serialize(&mut **self)
}
fn end(self) -> Result<()> {
self.output.push(')');
Ok(())
}
}
pub(crate) struct KeyCapture {
pub(crate) key: String,
}
impl ser::Serializer for &mut KeyCapture {
type Ok = ();
type Error = Error;
type SerializeSeq = ser::Impossible<(), Error>;
type SerializeTuple = ser::Impossible<(), Error>;
type SerializeTupleStruct = ser::Impossible<(), Error>;
type SerializeTupleVariant = ser::Impossible<(), Error>;
type SerializeMap = ser::Impossible<(), Error>;
type SerializeStruct = ser::Impossible<(), Error>;
type SerializeStructVariant = ser::Impossible<(), Error>;
fn serialize_str(self, v: &str) -> Result<()> {
validate_name(v)?;
self.key = v.to_string();
Ok(())
}
fn serialize_unit_variant(
self,
_name: &'static str,
_variant_index: u32,
variant: &'static str,
) -> Result<()> {
validate_name(variant)?;
self.key = variant.to_string();
Ok(())
}
fn serialize_newtype_struct<T>(self, _name: &'static str, value: &T) -> Result<()>
where
T: ?Sized + Serialize,
{
value.serialize(self)
}
fn serialize_bool(self, _v: bool) -> Result<()> {
Err(ErrorKind::KeyMustBeAString.into())
}
fn serialize_i8(self, _v: i8) -> Result<()> {
Err(ErrorKind::KeyMustBeAString.into())
}
fn serialize_i16(self, _v: i16) -> Result<()> {
Err(ErrorKind::KeyMustBeAString.into())
}
fn serialize_i32(self, _v: i32) -> Result<()> {
Err(ErrorKind::KeyMustBeAString.into())
}
fn serialize_i64(self, _v: i64) -> Result<()> {
Err(ErrorKind::KeyMustBeAString.into())
}
fn serialize_u8(self, _v: u8) -> Result<()> {
Err(ErrorKind::KeyMustBeAString.into())
}
fn serialize_u16(self, _v: u16) -> Result<()> {
Err(ErrorKind::KeyMustBeAString.into())
}
fn serialize_u32(self, _v: u32) -> Result<()> {
Err(ErrorKind::KeyMustBeAString.into())
}
fn serialize_u64(self, _v: u64) -> Result<()> {
Err(ErrorKind::KeyMustBeAString.into())
}
fn serialize_f32(self, _v: f32) -> Result<()> {
Err(ErrorKind::KeyMustBeAString.into())
}
fn serialize_f64(self, _v: f64) -> Result<()> {
Err(ErrorKind::KeyMustBeAString.into())
}
fn serialize_char(self, _v: char) -> Result<()> {
Err(ErrorKind::KeyMustBeAString.into())
}
fn serialize_bytes(self, _v: &[u8]) -> Result<()> {
Err(ErrorKind::KeyMustBeAString.into())
}
fn serialize_none(self) -> Result<()> {
Err(ErrorKind::KeyMustBeAString.into())
}
fn serialize_some<T>(self, _value: &T) -> Result<()>
where
T: ?Sized + Serialize,
{
Err(ErrorKind::KeyMustBeAString.into())
}
fn serialize_unit(self) -> Result<()> {
Err(ErrorKind::KeyMustBeAString.into())
}
fn serialize_unit_struct(self, _name: &'static str) -> Result<()> {
Err(ErrorKind::KeyMustBeAString.into())
}
fn serialize_newtype_variant<T>(
self,
_name: &'static str,
_variant_index: u32,
_variant: &'static str,
_value: &T,
) -> Result<()>
where
T: ?Sized + Serialize,
{
Err(ErrorKind::KeyMustBeAString.into())
}
fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq> {
Err(ErrorKind::KeyMustBeAString.into())
}
fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple> {
Err(ErrorKind::KeyMustBeAString.into())
}
fn serialize_tuple_struct(
self,
_name: &'static str,
_len: usize,
) -> Result<Self::SerializeTupleStruct> {
Err(ErrorKind::KeyMustBeAString.into())
}
fn serialize_tuple_variant(
self,
_name: &'static str,
_variant_index: u32,
_variant: &'static str,
_len: usize,
) -> Result<Self::SerializeTupleVariant> {
Err(ErrorKind::KeyMustBeAString.into())
}
fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap> {
Err(ErrorKind::KeyMustBeAString.into())
}
fn serialize_struct(self, _name: &'static str, _len: usize) -> Result<Self::SerializeStruct> {
Err(ErrorKind::KeyMustBeAString.into())
}
fn serialize_struct_variant(
self,
_name: &'static str,
_variant_index: u32,
_variant: &'static str,
_len: usize,
) -> Result<Self::SerializeStructVariant> {
Err(ErrorKind::KeyMustBeAString.into())
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde::Serialize;
#[test]
fn test_serialize_primitives() {
assert_eq!(to_string(&42u32).unwrap(), "42");
assert_eq!(to_string(&42i64).unwrap(), "42L");
assert_eq!(to_string(&2.25f64).unwrap(), "2.25");
assert_eq!(to_string(&true).unwrap(), "true");
assert_eq!(to_string(&"hello".to_string()).unwrap(), "\"hello\"");
}
#[test]
fn test_serialize_array() {
let arr = vec![1, 2, 3];
assert_eq!(to_string(&arr).unwrap(), "[1, 2, 3]");
}
#[test]
fn test_serialize_struct() {
#[derive(Serialize)]
struct Test {
a: i32,
b: String,
}
let test = Test {
a: 42,
b: "hello".to_string(),
};
let result = to_string(&test).unwrap();
assert!(result.contains("a = 42"));
assert!(result.contains("b = \"hello\""));
}
#[test]
fn test_serialize_i8_no_l_suffix() {
assert_eq!(to_string(&42i8).unwrap(), "42");
assert_eq!(to_string(&42i16).unwrap(), "42");
assert_eq!(to_string(&42i32).unwrap(), "42");
assert_eq!(to_string(&42i64).unwrap(), "42L");
}
#[test]
fn test_serialize_u64_has_l_suffix() {
assert_eq!(to_string(&42u8).unwrap(), "42");
assert_eq!(to_string(&42u16).unwrap(), "42");
assert_eq!(to_string(&42u32).unwrap(), "42");
assert_eq!(to_string(&42u64).unwrap(), "42L");
}
#[test]
fn test_serialize_u32_beyond_i32_gets_l_suffix() {
assert_eq!(to_string(&(i32::MAX as u32)).unwrap(), "2147483647");
assert_eq!(to_string(&(i32::MAX as u32 + 1)).unwrap(), "2147483648L");
assert_eq!(to_string(&u32::MAX).unwrap(), "4294967295L");
}
#[test]
fn test_serialize_float_always_has_decimal() {
assert_eq!(to_string(&1.0f64).unwrap(), "1.0");
assert_eq!(to_string(&0.0f64).unwrap(), "0.0");
assert_eq!(to_string(&2.25f64).unwrap(), "2.25");
}
#[test]
fn test_serialize_non_finite_floats_error() {
assert!(matches!(
to_string(&f64::INFINITY),
Err(e) if *e.kind() == ErrorKind::NonFiniteFloat
));
assert!(matches!(
to_string(&f64::NEG_INFINITY),
Err(e) if *e.kind() == ErrorKind::NonFiniteFloat
));
assert!(matches!(to_string(&f64::NAN), Err(e) if *e.kind() == ErrorKind::NonFiniteFloat));
assert!(matches!(to_string(&f32::NAN), Err(e) if *e.kind() == ErrorKind::NonFiniteFloat));
}
#[test]
fn test_serialize_u64_out_of_range_errors() {
assert_eq!(to_string(&(i64::MAX as u64)).unwrap(), "9223372036854775807L");
assert!(matches!(
to_string(&(i64::MAX as u64 + 1)),
Err(e) if *e.kind() == ErrorKind::IntegerOutOfRange
));
assert!(matches!(to_string(&u64::MAX), Err(e) if *e.kind() == ErrorKind::IntegerOutOfRange));
}
#[test]
fn test_serialize_invalid_map_key_errors() {
use indexmap::IndexMap;
for bad in ["my key", "2bad", "", "quoted\"", "dot.ted"] {
let mut map = IndexMap::new();
map.insert(bad.to_string(), 1i32);
assert!(
matches!(to_string(&map), Err(e) if matches!(e.kind(), ErrorKind::InvalidSettingName(_))),
"key {bad:?} should be rejected"
);
}
let mut map = IndexMap::new();
map.insert("*wild-card_2*".to_string(), 1i32);
assert!(to_string(&map).is_ok());
}
#[test]
fn test_serialize_control_chars_escaped() {
assert_eq!(to_string(&"a\x01b").unwrap(), "\"a\\x01b\"");
assert_eq!(to_string(&"bell\x07").unwrap(), "\"bell\\a\"");
assert_eq!(to_string(&"tab\tnl\n").unwrap(), "\"tab\\tnl\\n\"");
let s = "\x01\x02\x07\x08\x0b\x1f ok";
let out = to_string(&s.to_string()).unwrap();
let back: String = crate::from_str(&out).unwrap();
assert_eq!(back, s);
}
#[test]
fn test_serialize_seq_of_groups_becomes_list() {
#[derive(Serialize)]
struct P {
x: i32,
}
let out = to_string(&vec![P { x: 1 }, P { x: 2 }]).unwrap();
assert!(out.starts_with('('), "expected list, got: {out}");
assert!(out.ends_with(')'));
let nested = to_string(&vec![vec![1, 2], vec![3]]).unwrap();
assert_eq!(nested, "([1, 2], [3])");
assert_eq!(to_string(&vec![1, 2, 3]).unwrap(), "[1, 2, 3]");
assert_eq!(to_string(&vec!["a", "b"]).unwrap(), "[\"a\", \"b\"]");
}
#[test]
fn test_serialize_mixed_int_widths_promote_to_i64() {
use crate::Value;
let v = Value::Array(vec![Value::Integer(1), Value::Integer64(5_000_000_000)]);
assert_eq!(to_string(&v).unwrap(), "[1L, 5000000000L]");
}
#[test]
fn test_write_options_assignment_and_layout() {
use crate::{Config, WriteOptions};
let config = Config::from_str("port = 80;\ndb = {\n host = \"h\";\n};").unwrap();
let opts = WriteOptions::new()
.colon_assignment_for_groups(true)
.open_brace_on_separate_line(true);
let text = config.to_string_with_options(&opts).unwrap();
assert_eq!(text, "port = 80;\ndb :\n{\n host = \"h\";\n};");
assert_eq!(Config::from_str(&text).unwrap(), config);
let opts = WriteOptions::new()
.colon_assignment_for_groups(true)
.colon_assignment_for_non_groups(true);
let text = config.to_string_with_options(&opts).unwrap();
assert!(text.contains("port : 80"));
assert_eq!(Config::from_str(&text).unwrap(), config);
let opts = WriteOptions::new().semicolon_separators(false);
let text = config.to_string_with_options(&opts).unwrap();
assert!(!text.contains(';'), "got: {text}");
assert_eq!(Config::from_str(&text).unwrap(), config);
let opts = WriteOptions::new().tab_width(4);
let text = config.to_string_with_options(&opts).unwrap();
assert!(text.contains("\n host"), "got: {text}");
let opts = WriteOptions::new().tab_width(0);
let text = config.to_string_with_options(&opts).unwrap();
assert!(text.contains("\n\thost"), "got: {text}");
assert_eq!(Config::from_str(&text).unwrap(), config);
assert_eq!(
config.to_string_with_options(&WriteOptions::default()).unwrap(),
config.to_string().unwrap()
);
}
#[test]
fn test_write_options_floats() {
use crate::{Value, WriteOptions};
let opts = WriteOptions::new().float_precision(3);
assert_eq!(to_string_with_options(&2.5f64, &opts).unwrap(), "2.500");
let opts = WriteOptions::new().float_precision(0);
assert_eq!(to_string_with_options(&3.0f64, &opts).unwrap(), "3.0");
let opts = WriteOptions::new().scientific_notation(true);
let text = to_string_with_options(&2500.0f64, &opts).unwrap();
assert_eq!(text, "2.5e3");
assert_eq!(crate::from_str::<f64>(&text).unwrap(), 2500.0);
let text = to_string_with_options(&vec![100000.0f64, 2.5], &opts).unwrap();
assert_eq!(text, "[1e5, 2.5e0]");
let v: Value = crate::from_str(&format!("x = {};", text)).unwrap();
assert!(v["x"].is_array());
assert_eq!(v["x"].get_index(0).unwrap().as_f64(), Some(1e5));
assert!(to_string_with_options(&f64::NAN, &opts).is_err());
}
#[test]
fn test_serialize_enum_variants() {
#[derive(Serialize)]
enum E {
Unit,
Newtype(i32),
Tuple(i32, bool),
Struct { x: i32 },
}
assert_eq!(to_string(&E::Unit).unwrap(), "\"Unit\"");
assert_eq!(to_string(&E::Newtype(5)).unwrap(), "{ Newtype = 5; }");
assert_eq!(to_string(&E::Tuple(7, true)).unwrap(), "{ Tuple = (7, true); }");
let s = to_string(&E::Struct { x: 9 }).unwrap();
assert!(s.starts_with("{ Struct = {"), "got: {s}");
assert!(s.ends_with("}; }"), "got: {s}");
}
#[test]
fn test_serialize_tuple_as_list() {
let tup = (1, 2, 3);
assert_eq!(to_string(&tup).unwrap(), "(1, 2, 3)");
}
#[test]
fn test_serialize_map_bare_keys() {
use indexmap::IndexMap;
let mut map = IndexMap::new();
map.insert("key".to_string(), 42i32);
let result = to_string(&map).unwrap();
assert!(result.contains("key = 42"));
assert!(!result.contains("\"key\""));
}
}