diff --git a/crates/toml/src/de.rs b/crates/toml/src/de.rs index 36453754..9eb4c418 100644 --- a/crates/toml/src/de.rs +++ b/crates/toml/src/de.rs @@ -70,16 +70,6 @@ impl Error { pub fn span(&self) -> Option> { self.inner.span() } - - /// Produces a (line, column) pair of the position of the error if available - /// - /// All indexes are 0-based. - #[deprecated(since = "0.18.0", note = "See instead `Error::span`")] - #[cfg(feature = "parse")] - pub fn line_col(&self) -> Option<(usize, usize)> { - #[allow(deprecated)] - self.inner.line_col() - } } impl serde::de::Error for Error { diff --git a/crates/toml/src/ser.rs b/crates/toml/src/ser.rs index b8cf4b1d..975333e9 100644 --- a/crates/toml/src/ser.rs +++ b/crates/toml/src/ser.rs @@ -161,51 +161,6 @@ impl<'d> Serializer<'d> { ser.settings.multiline_array = true; ser } - - #[doc(hidden)] - #[deprecated( - since = "0.6.0", - note = "string behavior is now automatic; for greater control deserialize to `toml_edit::Document` and use `toml_edit::visit_mut::VisitorMut`" - )] - pub fn pretty_string(&mut self, _value: bool) -> &mut Self { - self - } - - #[doc(hidden)] - #[deprecated( - since = "0.6.0", - note = "string behavior is now automatic; for greater control deserialize to `toml_edit::Document` and use `toml_edit::visit_mut::VisitorMut`" - )] - pub fn pretty_string_literal(&mut self, _value: bool) -> &mut Self { - self - } - - #[doc(hidden)] - #[deprecated( - since = "0.6.0", - note = "this is bundled in with `pretty`; for greater control deserialize to `toml_edit::Document` and use `toml_edit::visit_mut::VisitorMut`" - )] - pub fn pretty_array(&mut self, _value: bool) -> &mut Self { - self - } - - #[doc(hidden)] - #[deprecated( - since = "0.6.0", - note = "this is bundled in with `pretty`; for greater control deserialize to `toml_edit::Document` and use `toml_edit::visit_mut::VisitorMut`" - )] - pub fn pretty_array_indent(&mut self, _value: usize) -> &mut Self { - self - } - - #[doc(hidden)] - #[deprecated( - since = "0.6.0", - note = "this is bundled in with `pretty`; for greater control deserialize to `toml_edit::Document` and use `toml_edit::visit_mut::VisitorMut`" - )] - pub fn pretty_array_trailing_comma(&mut self, _value: bool) -> &mut Self { - self - } } #[cfg(feature = "display")] @@ -1124,24 +1079,3 @@ mod internal { Ok(()) } } - -#[doc(hidden)] -#[deprecated( - since = "0.6.0", - note = "`tables_last` is no longer needed; things just work" -)] -pub fn tables_last<'a, I, K, V, S>(data: &'a I, serializer: S) -> Result -where - &'a I: IntoIterator, - K: serde::ser::Serialize, - V: serde::ser::Serialize, - S: serde::ser::Serializer, -{ - use serde::ser::SerializeMap; - - let mut map = serializer.serialize_map(None)?; - for (k, v) in data { - map.serialize_entry(&k, &v)?; - } - map.end() -} diff --git a/crates/toml_edit/Cargo.toml b/crates/toml_edit/Cargo.toml index d4c1e71e..04c820ad 100644 --- a/crates/toml_edit/Cargo.toml +++ b/crates/toml_edit/Cargo.toml @@ -22,7 +22,7 @@ include = [ ] [package.metadata.docs.rs] -features = ["easy"] +features = ["serde"] [package.metadata.release] tag-name = "v{{version}}" @@ -36,7 +36,6 @@ pre-release-replacements = [ [features] default = [] -easy = ["serde"] perf = ["dep:kstring"] serde = ["dep:serde", "toml_datetime/serde", "dep:serde_spanned"] # Provide a method disable_recursion_limit to parse arbitrarily deep structures diff --git a/crates/toml_edit/src/de/mod.rs b/crates/toml_edit/src/de/mod.rs index efd95a25..09ea1209 100644 --- a/crates/toml_edit/src/de/mod.rs +++ b/crates/toml_edit/src/de/mod.rs @@ -55,15 +55,6 @@ impl Error { pub(crate) fn set_span(&mut self, span: Option>) { self.inner.set_span(span); } - - /// Produces a (line, column) pair of the position of the error if available - /// - /// All indexes are 0-based. - #[deprecated(since = "0.18.0", note = "See instead `Error::span`")] - pub fn line_col(&self) -> Option<(usize, usize)> { - #[allow(deprecated)] - self.inner.line_col() - } } impl serde::de::Error for Error { diff --git a/crates/toml_edit/src/easy/datetime.rs b/crates/toml_edit/src/easy/datetime.rs deleted file mode 100644 index 6bf6b1ec..00000000 --- a/crates/toml_edit/src/easy/datetime.rs +++ /dev/null @@ -1 +0,0 @@ -pub use toml_datetime::*; diff --git a/crates/toml_edit/src/easy/macros.rs b/crates/toml_edit/src/easy/macros.rs deleted file mode 100644 index e9895528..00000000 --- a/crates/toml_edit/src/easy/macros.rs +++ /dev/null @@ -1,437 +0,0 @@ -pub use serde::de::{Deserialize, IntoDeserializer}; - -use crate::easy::value::{Array, Table, Value}; - -#[doc(hidden)] -#[deprecated(since = "0.18.0", note = "Replaced with `toml::toml!`")] -#[macro_export] -macro_rules! toml { - ($($toml:tt)+) => {{ - let table = $crate::easy::value::Table::new(); - let mut root = $crate::easy::Value::Table(table); - $crate::toml_internal!(@toplevel root [] $($toml)+); - root - }}; -} - -// TT-muncher to parse TOML syntax into a toml_edit::easy::Value. -// -// @toplevel -- Parse tokens outside of an inline table or inline array. In -// this state, `[table headers]` and `[[array headers]]` are -// allowed and `key = value` pairs are not separated by commas. -// -// @topleveldatetime -- Helper to parse a Datetime from string and insert it -// into a table, continuing in the @toplevel state. -// -// @path -- Turn a path segment into a string. Segments that look like idents -// are stringified, while quoted segments like `"cfg(windows)"` -// are not. -// -// @value -- Parse the value part of a `key = value` pair, which may be a -// primitive or inline table or inline array. -// -// @table -- Parse the contents of an inline table, returning them as a -// toml_edit::easy::Value::Table. -// -// @tabledatetime -- Helper to parse a Datetime from string and insert it -// into a table, continuing in the @table state. -// -// @array -- Parse the contents of an inline array, returning them as a -// toml_edit::easy::Value::Array. -// -// @arraydatetime -- Helper to parse a Datetime from string and push it into -// an array, continuing in the @array state. -// -// @trailingcomma -- Helper to append a comma to a sequence of tokens if the -// sequence is non-empty and does not already end in a trailing -// comma. -// -#[macro_export] -#[doc(hidden)] -macro_rules! toml_internal { - // Base case, no elements remaining. - (@toplevel $root:ident [$($path:tt)*]) => {}; - - // Parse negative number `key = -value`. - (@toplevel $root:ident [$($path:tt)*] $($($k:tt)-+).+ = - $v:tt $($rest:tt)*) => { - $crate::toml_internal!(@toplevel $root [$($path)*] $($($k)-+).+ = (-$v) $($rest)*); - }; - - // Parse positive number `key = +value`. - (@toplevel $root:ident [$($path:tt)*] $($($k:tt)-+).+ = + $v:tt $($rest:tt)*) => { - $crate::toml_internal!(@toplevel $root [$($path)*] $($($k)-+).+ = ($v) $($rest)*); - }; - - // Parse offset datetime `key = 1979-05-27T00:32:00.999999-07:00`. - (@toplevel $root:ident [$($path:tt)*] $($($k:tt)-+).+ = $yr:tt - $mo:tt - $dhr:tt : $min:tt : $sec:tt . $frac:tt - $tzh:tt : $tzm:tt $($rest:tt)*) => { - $crate::toml_internal!(@topleveldatetime $root [$($path)*] $($($k)-+).+ = ($yr - $mo - $dhr : $min : $sec . $frac - $tzh : $tzm) $($rest)*); - }; - // Space instead of T. - (@toplevel $root:ident [$($path:tt)*] $($($k:tt)-+).+ = $yr:tt - $mo:tt - $day:tt $hr:tt : $min:tt : $sec:tt . $frac:tt - $tzh:tt : $tzm:tt $($rest:tt)*) => { - $crate::toml_internal!(@topleveldatetime $root [$($path)*] $($($k)-+).+ = ($yr - $mo - $day T $hr : $min : $sec . $frac - $tzh : $tzm) $($rest)*); - }; - - // Parse offset datetime `key = 1979-05-27T00:32:00-07:00`. - (@toplevel $root:ident [$($path:tt)*] $($($k:tt)-+).+ = $yr:tt - $mo:tt - $dhr:tt : $min:tt : $sec:tt - $tzh:tt : $tzm:tt $($rest:tt)*) => { - $crate::toml_internal!(@topleveldatetime $root [$($path)*] $($($k)-+).+ = ($yr - $mo - $dhr : $min : $sec - $tzh : $tzm) $($rest)*); - }; - // Space instead of T. - (@toplevel $root:ident [$($path:tt)*] $($($k:tt)-+).+ = $yr:tt - $mo:tt - $day:tt $hr:tt : $min:tt : $sec:tt - $tzh:tt : $tzm:tt $($rest:tt)*) => { - $crate::toml_internal!(@topleveldatetime $root [$($path)*] $($($k)-+).+ = ($yr - $mo - $day T $hr : $min : $sec - $tzh : $tzm) $($rest)*); - }; - - // Parse local datetime `key = 1979-05-27T00:32:00.999999`. - (@toplevel $root:ident [$($path:tt)*] $($($k:tt)-+).+ = $yr:tt - $mo:tt - $dhr:tt : $min:tt : $sec:tt . $frac:tt $($rest:tt)*) => { - $crate::toml_internal!(@topleveldatetime $root [$($path)*] $($($k)-+).+ = ($yr - $mo - $dhr : $min : $sec . $frac) $($rest)*); - }; - // Space instead of T. - (@toplevel $root:ident [$($path:tt)*] $($($k:tt)-+).+ = $yr:tt - $mo:tt - $day:tt $hr:tt : $min:tt : $sec:tt . $frac:tt $($rest:tt)*) => { - $crate::toml_internal!(@topleveldatetime $root [$($path)*] $($($k)-+).+ = ($yr - $mo - $day T $hr : $min : $sec . $frac) $($rest)*); - }; - - // Parse offset datetime `key = 1979-05-27T07:32:00Z` and local datetime `key = 1979-05-27T07:32:00`. - (@toplevel $root:ident [$($path:tt)*] $($($k:tt)-+).+ = $yr:tt - $mo:tt - $dhr:tt : $min:tt : $sec:tt $($rest:tt)*) => { - $crate::toml_internal!(@topleveldatetime $root [$($path)*] $($($k)-+).+ = ($yr - $mo - $dhr : $min : $sec) $($rest)*); - }; - // Space instead of T. - (@toplevel $root:ident [$($path:tt)*] $($($k:tt)-+).+ = $yr:tt - $mo:tt - $day:tt $hr:tt : $min:tt : $sec:tt $($rest:tt)*) => { - $crate::toml_internal!(@topleveldatetime $root [$($path)*] $($($k)-+).+ = ($yr - $mo - $day T $hr : $min : $sec) $($rest)*); - }; - - // Parse local date `key = 1979-05-27`. - (@toplevel $root:ident [$($path:tt)*] $($($k:tt)-+).+ = $yr:tt - $mo:tt - $day:tt $($rest:tt)*) => { - $crate::toml_internal!(@topleveldatetime $root [$($path)*] $($($k)-+).+ = ($yr - $mo - $day) $($rest)*); - }; - - // Parse local time `key = 00:32:00.999999`. - (@toplevel $root:ident [$($path:tt)*] $($($k:tt)-+).+ = $hr:tt : $min:tt : $sec:tt . $frac:tt $($rest:tt)*) => { - $crate::toml_internal!(@topleveldatetime $root [$($path)*] $($($k)-+).+ = ($hr : $min : $sec . $frac) $($rest)*); - }; - - // Parse local time `key = 07:32:00`. - (@toplevel $root:ident [$($path:tt)*] $($($k:tt)-+).+ = $hr:tt : $min:tt : $sec:tt $($rest:tt)*) => { - $crate::toml_internal!(@topleveldatetime $root [$($path)*] $($($k)-+).+ = ($hr : $min : $sec) $($rest)*); - }; - - // Parse any other `key = value` including string, inline array, inline - // table, number, and boolean. - (@toplevel $root:ident [$($path:tt)*] $($($k:tt)-+).+ = $v:tt $($rest:tt)*) => {{ - $crate::easy::macros::insert_toml( - &mut $root, - &[$($path)* $(&concat!($("-", $crate::toml_internal!(@path $k),)+)[1..], )+], - $crate::toml_internal!(@value $v)); - $crate::toml_internal!(@toplevel $root [$($path)*] $($rest)*); - }}; - - // Parse array header `[[bin]]`. - (@toplevel $root:ident $oldpath:tt [[$($($path:tt)-+).+]] $($rest:tt)*) => { - $crate::easy::macros::push_toml( - &mut $root, - &[$(&concat!($("-", $crate::toml_internal!(@path $path),)+)[1..],)+]); - $crate::toml_internal!(@toplevel $root [$(&concat!($("-", $crate::toml_internal!(@path $path),)+)[1..],)+] $($rest)*); - }; - - // Parse table header `[patch.crates-io]`. - (@toplevel $root:ident $oldpath:tt [$($($path:tt)-+).+] $($rest:tt)*) => { - $crate::easy::macros::insert_toml( - &mut $root, - &[$(&concat!($("-", $crate::toml_internal!(@path $path),)+)[1..],)+], - $crate::easy::Value::Table($crate::easy::value::Table::new())); - $crate::toml_internal!(@toplevel $root [$(&concat!($("-", $crate::toml_internal!(@path $path),)+)[1..],)+] $($rest)*); - }; - - // Parse datetime from string and insert into table. - (@topleveldatetime $root:ident [$($path:tt)*] $($($k:tt)-+).+ = ($($datetime:tt)+) $($rest:tt)*) => { - $crate::easy::macros::insert_toml( - &mut $root, - &[$($path)* $(&concat!($("-", $crate::toml_internal!(@path $k),)+)[1..], )+], - $crate::easy::Value::Datetime(concat!($(stringify!($datetime)),+).parse().unwrap())); - $crate::toml_internal!(@toplevel $root [$($path)*] $($rest)*); - }; - - // Turn a path segment into a string. - (@path $ident:ident) => { - stringify!($ident) - }; - - // For a path segment that is not an ident, expect that it is already a - // quoted string, like in `[target."cfg(windows)".dependencies]`. - (@path $quoted:tt) => { - $quoted - }; - - // Construct a Value from an inline table. - (@value { $($inline:tt)* }) => {{ - let mut table = $crate::easy::Value::Table($crate::easy::value::Table::new()); - $crate::toml_internal!(@trailingcomma (@table table) $($inline)*); - table - }}; - - // Construct a Value from an inline array. - (@value [ $($inline:tt)* ]) => {{ - let mut array = $crate::easy::value::Array::new(); - $crate::toml_internal!(@trailingcomma (@array array) $($inline)*); - $crate::easy::Value::Array(array) - }}; - - (@value (-nan)) => { - $crate::easy::Value::Float(-::std::f64::NAN) - }; - - (@value (nan)) => { - $crate::easy::Value::Float(::std::f64::NAN) - }; - - (@value nan) => { - $crate::easy::Value::Float(::std::f64::NAN) - }; - - (@value (-inf)) => { - $crate::easy::Value::Float(::std::f64::NEG_INFINITY) - }; - - (@value (inf)) => { - $crate::easy::Value::Float(::std::f64::INFINITY) - }; - - (@value inf) => { - $crate::easy::Value::Float(::std::f64::INFINITY) - }; - - // Construct a Value from any other type, probably string or boolean or number. - (@value $v:tt) => {{ - // TODO: Implement this with something like serde_json::to_value instead. - let de = $crate::easy::macros::IntoDeserializer::<$crate::easy::de::Error>::into_deserializer($v); - <$crate::easy::Value as $crate::easy::macros::Deserialize>::deserialize(de).unwrap() - }}; - - // Base case of inline table. - (@table $root:ident) => {}; - - // Parse negative number `key = -value`. - (@table $root:ident $($($k:tt)-+).+ = - $v:tt , $($rest:tt)*) => { - $crate::toml_internal!(@table $root $($($k)-+).+ = (-$v) , $($rest)*); - }; - - // Parse positive number `key = +value`. - (@table $root:ident $($($k:tt)-+).+ = + $v:tt , $($rest:tt)*) => { - $crate::toml_internal!(@table $root $($($k)-+).+ = ($v) , $($rest)*); - }; - - // Parse offset datetime `key = 1979-05-27T00:32:00.999999-07:00`. - (@table $root:ident $($($k:tt)-+).+ = $yr:tt - $mo:tt - $dhr:tt : $min:tt : $sec:tt . $frac:tt - $tzh:tt : $tzm:tt , $($rest:tt)*) => { - $crate::toml_internal!(@tabledatetime $root $($($k)-+).+ = ($yr - $mo - $dhr : $min : $sec . $frac - $tzh : $tzm) $($rest)*); - }; - // Space instead of T. - (@table $root:ident $($($k:tt)-+).+ = $yr:tt - $mo:tt - $day:tt $hr:tt : $min:tt : $sec:tt . $frac:tt - $tzh:tt : $tzm:tt , $($rest:tt)*) => { - $crate::toml_internal!(@tabledatetime $root $($($k)-+).+ = ($yr - $mo - $day T $hr : $min : $sec . $frac - $tzh : $tzm) $($rest)*); - }; - - // Parse offset datetime `key = 1979-05-27T00:32:00-07:00`. - (@table $root:ident $($($k:tt)-+).+ = $yr:tt - $mo:tt - $dhr:tt : $min:tt : $sec:tt - $tzh:tt : $tzm:tt , $($rest:tt)*) => { - $crate::toml_internal!(@tabledatetime $root $($($k)-+).+ = ($yr - $mo - $dhr : $min : $sec - $tzh : $tzm) $($rest)*); - }; - // Space instead of T. - (@table $root:ident $($($k:tt)-+).+ = $yr:tt - $mo:tt - $day:tt $hr:tt : $min:tt : $sec:tt - $tzh:tt : $tzm:tt , $($rest:tt)*) => { - $crate::toml_internal!(@tabledatetime $root $($($k)-+).+ = ($yr - $mo - $day T $hr : $min : $sec - $tzh : $tzm) $($rest)*); - }; - - // Parse local datetime `key = 1979-05-27T00:32:00.999999`. - (@table $root:ident $($($k:tt)-+).+ = $yr:tt - $mo:tt - $dhr:tt : $min:tt : $sec:tt . $frac:tt , $($rest:tt)*) => { - $crate::toml_internal!(@tabledatetime $root $($($k)-+).+ = ($yr - $mo - $dhr : $min : $sec . $frac) $($rest)*); - }; - // Space instead of T. - (@table $root:ident $($($k:tt)-+).+ = $yr:tt - $mo:tt - $day:tt $hr:tt : $min:tt : $sec:tt . $frac:tt , $($rest:tt)*) => { - $crate::toml_internal!(@tabledatetime $root $($($k)-+).+ = ($yr - $mo - $day T $hr : $min : $sec . $frac) $($rest)*); - }; - - // Parse offset datetime `key = 1979-05-27T07:32:00Z` and local datetime `key = 1979-05-27T07:32:00`. - (@table $root:ident $($($k:tt)-+).+ = $yr:tt - $mo:tt - $dhr:tt : $min:tt : $sec:tt , $($rest:tt)*) => { - $crate::toml_internal!(@tabledatetime $root $($($k)-+).+ = ($yr - $mo - $dhr : $min : $sec) $($rest)*); - }; - // Space instead of T. - (@table $root:ident $($($k:tt)-+).+ = $yr:tt - $mo:tt - $day:tt $hr:tt : $min:tt : $sec:tt , $($rest:tt)*) => { - $crate::toml_internal!(@tabledatetime $root $($($k)-+).+ = ($yr - $mo - $day T $hr : $min : $sec) $($rest)*); - }; - - // Parse local date `key = 1979-05-27`. - (@table $root:ident $($($k:tt)-+).+ = $yr:tt - $mo:tt - $day:tt , $($rest:tt)*) => { - $crate::toml_internal!(@tabledatetime $root $($($k)-+).+ = ($yr - $mo - $day) $($rest)*); - }; - - // Parse local time `key = 00:32:00.999999`. - (@table $root:ident $($($k:tt)-+).+ = $hr:tt : $min:tt : $sec:tt . $frac:tt , $($rest:tt)*) => { - $crate::toml_internal!(@tabledatetime $root $($($k)-+).+ = ($hr : $min : $sec . $frac) $($rest)*); - }; - - // Parse local time `key = 07:32:00`. - (@table $root:ident $($($k:tt)-+).+ = $hr:tt : $min:tt : $sec:tt , $($rest:tt)*) => { - $crate::toml_internal!(@tabledatetime $root $($($k)-+).+ = ($hr : $min : $sec) $($rest)*); - }; - - // Parse any other type, probably string or boolean or number. - (@table $root:ident $($($k:tt)-+).+ = $v:tt , $($rest:tt)*) => { - $crate::easy::macros::insert_toml( - &mut $root, - &[$(&concat!($("-", $crate::toml_internal!(@path $k),)+)[1..], )+], - $crate::toml_internal!(@value $v)); - $crate::toml_internal!(@table $root $($rest)*); - }; - - // Parse a Datetime from string and continue in @table state. - (@tabledatetime $root:ident $($($k:tt)-+).+ = ($($datetime:tt)*) $($rest:tt)*) => { - $crate::easy::macros::insert_toml( - &mut $root, - &[$(&concat!($("-", $crate::toml_internal!(@path $k),)+)[1..], )+], - $crate::easy::Value::Datetime(concat!($(stringify!($datetime)),+).parse().unwrap())); - $crate::toml_internal!(@table $root $($rest)*); - }; - - // Base case of inline array. - (@array $root:ident) => {}; - - // Parse negative number `-value`. - (@array $root:ident - $v:tt , $($rest:tt)*) => { - $crate::toml_internal!(@array $root (-$v) , $($rest)*); - }; - - // Parse positive number `+value`. - (@array $root:ident + $v:tt , $($rest:tt)*) => { - $crate::toml_internal!(@array $root ($v) , $($rest)*); - }; - - // Parse offset datetime `1979-05-27T00:32:00.999999-07:00`. - (@array $root:ident $yr:tt - $mo:tt - $dhr:tt : $min:tt : $sec:tt . $frac:tt - $tzh:tt : $tzm:tt , $($rest:tt)*) => { - $crate::toml_internal!(@arraydatetime $root ($yr - $mo - $dhr : $min : $sec . $frac - $tzh : $tzm) $($rest)*); - }; - // Space instead of T. - (@array $root:ident $yr:tt - $mo:tt - $day:tt $hr:tt : $min:tt : $sec:tt . $frac:tt - $tzh:tt : $tzm:tt , $($rest:tt)*) => { - $crate::toml_internal!(@arraydatetime $root ($yr - $mo - $day T $hr : $min : $sec . $frac - $tzh : $tzm) $($rest)*); - }; - - // Parse offset datetime `1979-05-27T00:32:00-07:00`. - (@array $root:ident $yr:tt - $mo:tt - $dhr:tt : $min:tt : $sec:tt - $tzh:tt : $tzm:tt , $($rest:tt)*) => { - $crate::toml_internal!(@arraydatetime $root ($yr - $mo - $dhr : $min : $sec - $tzh : $tzm) $($rest)*); - }; - // Space instead of T. - (@array $root:ident $yr:tt - $mo:tt - $day:tt $hr:tt : $min:tt : $sec:tt - $tzh:tt : $tzm:tt , $($rest:tt)*) => { - $crate::toml_internal!(@arraydatetime $root ($yr - $mo - $day T $hr : $min : $sec - $tzh : $tzm) $($rest)*); - }; - - // Parse local datetime `1979-05-27T00:32:00.999999`. - (@array $root:ident $yr:tt - $mo:tt - $dhr:tt : $min:tt : $sec:tt . $frac:tt , $($rest:tt)*) => { - $crate::toml_internal!(@arraydatetime $root ($yr - $mo - $dhr : $min : $sec . $frac) $($rest)*); - }; - // Space instead of T. - (@array $root:ident $yr:tt - $mo:tt - $day:tt $hr:tt : $min:tt : $sec:tt . $frac:tt , $($rest:tt)*) => { - $crate::toml_internal!(@arraydatetime $root ($yr - $mo - $day T $hr : $min : $sec . $frac) $($rest)*); - }; - - // Parse offset datetime `1979-05-27T07:32:00Z` and local datetime `1979-05-27T07:32:00`. - (@array $root:ident $yr:tt - $mo:tt - $dhr:tt : $min:tt : $sec:tt , $($rest:tt)*) => { - $crate::toml_internal!(@arraydatetime $root ($yr - $mo - $dhr : $min : $sec) $($rest)*); - }; - // Space instead of T. - (@array $root:ident $yr:tt - $mo:tt - $day:tt $hr:tt : $min:tt : $sec:tt , $($rest:tt)*) => { - $crate::toml_internal!(@arraydatetime $root ($yr - $mo - $day T $hr : $min : $sec) $($rest)*); - }; - - // Parse local date `1979-05-27`. - (@array $root:ident $yr:tt - $mo:tt - $day:tt , $($rest:tt)*) => { - $crate::toml_internal!(@arraydatetime $root ($yr - $mo - $day) $($rest)*); - }; - - // Parse local time `00:32:00.999999`. - (@array $root:ident $hr:tt : $min:tt : $sec:tt . $frac:tt , $($rest:tt)*) => { - $crate::toml_internal!(@arraydatetime $root ($hr : $min : $sec . $frac) $($rest)*); - }; - - // Parse local time `07:32:00`. - (@array $root:ident $hr:tt : $min:tt : $sec:tt , $($rest:tt)*) => { - $crate::toml_internal!(@arraydatetime $root ($hr : $min : $sec) $($rest)*); - }; - - // Parse any other type, probably string or boolean or number. - (@array $root:ident $v:tt , $($rest:tt)*) => { - $root.push($crate::toml_internal!(@value $v)); - $crate::toml_internal!(@array $root $($rest)*); - }; - - // Parse a Datetime from string and continue in @array state. - (@arraydatetime $root:ident ($($datetime:tt)*) $($rest:tt)*) => { - $root.push($crate::easy::Value::Datetime(concat!($(stringify!($datetime)),+).parse().unwrap())); - $crate::toml_internal!(@array $root $($rest)*); - }; - - // No trailing comma required if the tokens are empty. - (@trailingcomma ($($args:tt)*)) => { - $crate::toml_internal!($($args)*); - }; - - // Tokens end with a trailing comma, do not append another one. - (@trailingcomma ($($args:tt)*) ,) => { - $crate::toml_internal!($($args)* ,); - }; - - // Tokens end with something other than comma, append a trailing comma. - (@trailingcomma ($($args:tt)*) $last:tt) => { - $crate::toml_internal!($($args)* $last ,); - }; - - // Not yet at the last token. - (@trailingcomma ($($args:tt)*) $first:tt $($rest:tt)+) => { - $crate::toml_internal!(@trailingcomma ($($args)* $first) $($rest)+); - }; -} - -// Called when parsing a `key = value` pair. -// Inserts an entry into the table at the given path. -pub fn insert_toml(root: &mut Value, path: &[&str], value: Value) { - *traverse(root, path) = value; -} - -// Called when parsing an `[[array header]]`. -// Pushes an empty table onto the array at the given path. -pub fn push_toml(root: &mut Value, path: &[&str]) { - let target = traverse(root, path); - if !target.is_array() { - *target = Value::Array(Array::new()); - } - target - .as_array_mut() - .unwrap() - .push(Value::Table(Table::new())); -} - -fn traverse<'a>(root: &'a mut Value, path: &[&str]) -> &'a mut Value { - let mut cur = root; - for &key in path { - // Lexical lifetimes :D - let cur1 = cur; - - // From the TOML spec: - // - // > Each double-bracketed sub-table will belong to the most recently - // > defined table element above it. - let cur2 = if cur1.is_array() { - cur1.as_array_mut().unwrap().last_mut().unwrap() - } else { - cur1 - }; - - // We are about to index into this value, so it better be a table. - if !cur2.is_table() { - *cur2 = Value::Table(Table::new()); - } - - if !cur2.as_table().unwrap().contains_key(key) { - // Insert an empty table for the next loop iteration to point to. - let empty = Value::Table(Table::new()); - cur2.as_table_mut().unwrap().insert(key.to_owned(), empty); - } - - // Step into the current table. - cur = cur2.as_table_mut().unwrap().get_mut(key).unwrap(); - } - cur -} diff --git a/crates/toml_edit/src/easy/map.rs b/crates/toml_edit/src/easy/map.rs deleted file mode 100644 index 061ca962..00000000 --- a/crates/toml_edit/src/easy/map.rs +++ /dev/null @@ -1,548 +0,0 @@ -// Copyright 2017 Serde Developers -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! A map of String to toml::Value. - -use std::borrow::Borrow; -use std::fmt::{self, Debug}; -use std::hash::Hash; -use std::iter::FromIterator; -use std::ops; - -use indexmap::map::IndexMap; -use serde::{de, ser}; - -use crate::easy::value::Value; - -#[doc(hidden)] -#[deprecated(since = "0.18.0", note = "Replaced with `toml::map::Map`")] -pub struct Map { - map: MapImpl, -} - -type MapImpl = IndexMap; - -impl Map { - /// Makes a new empty Map. - #[inline] - pub fn new() -> Self { - Map { - map: MapImpl::new(), - } - } - - /// Makes a new empty Map with the given initial capacity. - #[inline] - pub fn with_capacity(capacity: usize) -> Self { - Map { - map: IndexMap::with_capacity(capacity), - } - } - - /// Clears the map, removing all values. - #[inline] - pub fn clear(&mut self) { - self.map.clear() - } - - /// Returns a reference to the value corresponding to the key. - /// - /// The key may be any borrowed form of the map's key type, but the ordering - /// on the borrowed form *must* match the ordering on the key type. - #[inline] - pub fn get(&self, key: &Q) -> Option<&Value> - where - String: Borrow, - Q: Ord + Eq + Hash, - { - self.map.get(key) - } - - /// Returns true if the map contains a value for the specified key. - /// - /// The key may be any borrowed form of the map's key type, but the ordering - /// on the borrowed form *must* match the ordering on the key type. - #[inline] - pub fn contains_key(&self, key: &Q) -> bool - where - String: Borrow, - Q: Ord + Eq + Hash, - { - self.map.contains_key(key) - } - - /// Returns a mutable reference to the value corresponding to the key. - /// - /// The key may be any borrowed form of the map's key type, but the ordering - /// on the borrowed form *must* match the ordering on the key type. - #[inline] - pub fn get_mut(&mut self, key: &Q) -> Option<&mut Value> - where - String: Borrow, - Q: Ord + Eq + Hash, - { - self.map.get_mut(key) - } - - /// Inserts a key-value pair into the map. - /// - /// If the map did not have this key present, `None` is returned. - /// - /// If the map did have this key present, the value is updated, and the old - /// value is returned. The key is not updated, though; this matters for - /// types that can be `==` without being identical. - #[inline] - pub fn insert(&mut self, k: String, v: Value) -> Option { - self.map.insert(k, v) - } - - /// Removes a key from the map, returning the value at the key if the key - /// was previously in the map. - /// - /// The key may be any borrowed form of the map's key type, but the ordering - /// on the borrowed form *must* match the ordering on the key type. - #[inline] - pub fn remove(&mut self, key: &Q) -> Option - where - String: Borrow, - Q: Ord + Eq + Hash, - { - self.map.remove(key) - } - - /// Gets the given key's corresponding entry in the map for in-place - /// manipulation. - pub fn entry(&mut self, key: S) -> Entry<'_> - where - S: Into, - { - use indexmap::map::Entry as EntryImpl; - - match self.map.entry(key.into()) { - EntryImpl::Vacant(vacant) => Entry::Vacant(VacantEntry { vacant }), - EntryImpl::Occupied(occupied) => Entry::Occupied(OccupiedEntry { occupied }), - } - } - - /// Returns the number of elements in the map. - #[inline] - pub fn len(&self) -> usize { - self.map.len() - } - - /// Returns true if the map contains no elements. - #[inline] - pub fn is_empty(&self) -> bool { - self.map.is_empty() - } - - /// Gets an iterator over the entries of the map. - #[inline] - pub fn iter(&self) -> Iter<'_> { - Iter { - iter: self.map.iter(), - } - } - - /// Gets a mutable iterator over the entries of the map. - #[inline] - pub fn iter_mut(&mut self) -> IterMut<'_> { - IterMut { - iter: self.map.iter_mut(), - } - } - - /// Gets an iterator over the keys of the map. - #[inline] - pub fn keys(&self) -> Keys<'_> { - Keys { - iter: self.map.keys(), - } - } - - /// Gets an iterator over the values of the map. - #[inline] - pub fn values(&self) -> Values<'_> { - Values { - iter: self.map.values(), - } - } -} - -impl Default for Map { - #[inline] - fn default() -> Self { - Map { - map: MapImpl::new(), - } - } -} - -impl Clone for Map { - #[inline] - fn clone(&self) -> Self { - Map { - map: self.map.clone(), - } - } -} - -impl PartialEq for Map { - #[inline] - fn eq(&self, other: &Self) -> bool { - self.map.eq(&other.map) - } -} - -/// Access an element of this map. Panics if the given key is not present in the -/// map. -impl<'a, Q: ?Sized> ops::Index<&'a Q> for Map -where - String: Borrow, - Q: Ord + Eq + Hash, -{ - type Output = Value; - - fn index(&self, index: &Q) -> &Value { - self.map.index(index) - } -} - -/// Mutably access an element of this map. Panics if the given key is not -/// present in the map. -impl<'a, Q: ?Sized> ops::IndexMut<&'a Q> for Map -where - String: Borrow, - Q: Ord + Eq + Hash, -{ - fn index_mut(&mut self, index: &Q) -> &mut Value { - self.map.get_mut(index).expect("no entry found for key") - } -} - -impl Debug for Map { - #[inline] - fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { - self.map.fmt(formatter) - } -} - -impl ser::Serialize for Map { - #[inline] - fn serialize(&self, serializer: S) -> Result - where - S: ser::Serializer, - { - use serde::ser::SerializeMap; - let mut map = serializer.serialize_map(Some(self.len()))?; - for (k, v) in self { - map.serialize_key(k)?; - map.serialize_value(v)?; - } - map.end() - } -} - -impl<'de> de::Deserialize<'de> for Map { - #[inline] - fn deserialize(deserializer: D) -> Result - where - D: de::Deserializer<'de>, - { - struct Visitor; - - impl<'de> de::Visitor<'de> for Visitor { - type Value = Map; - - fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { - formatter.write_str("a map") - } - - #[inline] - fn visit_unit(self) -> Result - where - E: de::Error, - { - Ok(Map::new()) - } - - #[inline] - fn visit_map(self, mut visitor: V) -> Result - where - V: de::MapAccess<'de>, - { - let mut values = Map::new(); - - while let Some((key, value)) = visitor.next_entry()? { - values.insert(key, value); - } - - Ok(values) - } - } - - deserializer.deserialize_map(Visitor) - } -} - -impl FromIterator<(String, Value)> for Map { - fn from_iter(iter: T) -> Self - where - T: IntoIterator, - { - Map { - map: FromIterator::from_iter(iter), - } - } -} - -impl Extend<(String, Value)> for Map { - fn extend(&mut self, iter: T) - where - T: IntoIterator, - { - self.map.extend(iter); - } -} - -macro_rules! delegate_iterator { - (($name:ident $($generics:tt)*) => $item:ty) => { - impl $($generics)* Iterator for $name $($generics)* { - type Item = $item; - #[inline] - fn next(&mut self) -> Option { - self.iter.next() - } - #[inline] - fn size_hint(&self) -> (usize, Option) { - self.iter.size_hint() - } - } - - impl $($generics)* DoubleEndedIterator for $name $($generics)* { - #[inline] - fn next_back(&mut self) -> Option { - self.iter.next_back() - } - } - - impl $($generics)* ExactSizeIterator for $name $($generics)* { - #[inline] - fn len(&self) -> usize { - self.iter.len() - } - } - } -} - -////////////////////////////////////////////////////////////////////////////// - -/// A view into a single entry in a map, which may either be vacant or occupied. -/// This enum is constructed from the [`entry`] method on [`Map`]. -/// -/// [`entry`]: struct.Map.html#method.entry -/// [`Map`]: struct.Map.html -pub enum Entry<'a> { - /// A vacant Entry. - Vacant(VacantEntry<'a>), - /// An occupied Entry. - Occupied(OccupiedEntry<'a>), -} - -/// A vacant Entry. It is part of the [`Entry`] enum. -/// -/// [`Entry`]: enum.Entry.html -pub struct VacantEntry<'a> { - vacant: VacantEntryImpl<'a>, -} - -/// An occupied Entry. It is part of the [`Entry`] enum. -/// -/// [`Entry`]: enum.Entry.html -pub struct OccupiedEntry<'a> { - occupied: OccupiedEntryImpl<'a>, -} - -type VacantEntryImpl<'a> = indexmap::map::VacantEntry<'a, String, Value>; - -type OccupiedEntryImpl<'a> = indexmap::map::OccupiedEntry<'a, String, Value>; - -impl<'a> Entry<'a> { - /// Returns a reference to this entry's key. - pub fn key(&self) -> &String { - match *self { - Entry::Vacant(ref e) => e.key(), - Entry::Occupied(ref e) => e.key(), - } - } - - /// Ensures a value is in the entry by inserting the default if empty, and - /// returns a mutable reference to the value in the entry. - pub fn or_insert(self, default: Value) -> &'a mut Value { - match self { - Entry::Vacant(entry) => entry.insert(default), - Entry::Occupied(entry) => entry.into_mut(), - } - } - - /// Ensures a value is in the entry by inserting the result of the default - /// function if empty, and returns a mutable reference to the value in the - /// entry. - pub fn or_insert_with(self, default: F) -> &'a mut Value - where - F: FnOnce() -> Value, - { - match self { - Entry::Vacant(entry) => entry.insert(default()), - Entry::Occupied(entry) => entry.into_mut(), - } - } -} - -impl<'a> VacantEntry<'a> { - /// Gets a reference to the key that would be used when inserting a value - /// through the VacantEntry. - #[inline] - pub fn key(&self) -> &String { - self.vacant.key() - } - - /// Sets the value of the entry with the VacantEntry's key, and returns a - /// mutable reference to it. - #[inline] - pub fn insert(self, value: Value) -> &'a mut Value { - self.vacant.insert(value) - } -} - -impl<'a> OccupiedEntry<'a> { - /// Gets a reference to the key in the entry. - #[inline] - pub fn key(&self) -> &String { - self.occupied.key() - } - - /// Gets a reference to the value in the entry. - #[inline] - pub fn get(&self) -> &Value { - self.occupied.get() - } - - /// Gets a mutable reference to the value in the entry. - #[inline] - pub fn get_mut(&mut self) -> &mut Value { - self.occupied.get_mut() - } - - /// Converts the entry into a mutable reference to its value. - #[inline] - pub fn into_mut(self) -> &'a mut Value { - self.occupied.into_mut() - } - - /// Sets the value of the entry with the `OccupiedEntry`'s key, and returns - /// the entry's old value. - #[inline] - pub fn insert(&mut self, value: Value) -> Value { - self.occupied.insert(value) - } - - /// Takes the value of the entry out of the map, and returns it. - #[inline] - pub fn remove(self) -> Value { - self.occupied.remove() - } -} - -////////////////////////////////////////////////////////////////////////////// - -impl<'a> IntoIterator for &'a Map { - type Item = (&'a String, &'a Value); - type IntoIter = Iter<'a>; - #[inline] - fn into_iter(self) -> Self::IntoIter { - Iter { - iter: self.map.iter(), - } - } -} - -/// An iterator over a toml::Map's entries. -pub struct Iter<'a> { - iter: IterImpl<'a>, -} - -type IterImpl<'a> = indexmap::map::Iter<'a, String, Value>; - -delegate_iterator!((Iter<'a>) => (&'a String, &'a Value)); - -////////////////////////////////////////////////////////////////////////////// - -impl<'a> IntoIterator for &'a mut Map { - type Item = (&'a String, &'a mut Value); - type IntoIter = IterMut<'a>; - #[inline] - fn into_iter(self) -> Self::IntoIter { - IterMut { - iter: self.map.iter_mut(), - } - } -} - -/// A mutable iterator over a toml::Map's entries. -pub struct IterMut<'a> { - iter: IterMutImpl<'a>, -} - -type IterMutImpl<'a> = indexmap::map::IterMut<'a, String, Value>; - -delegate_iterator!((IterMut<'a>) => (&'a String, &'a mut Value)); - -////////////////////////////////////////////////////////////////////////////// - -impl IntoIterator for Map { - type Item = (String, Value); - type IntoIter = IntoIter; - #[inline] - fn into_iter(self) -> Self::IntoIter { - IntoIter { - iter: self.map.into_iter(), - } - } -} - -/// An owning iterator over a toml::Map's entries. -pub struct IntoIter { - iter: IntoIterImpl, -} - -type IntoIterImpl = indexmap::map::IntoIter; - -delegate_iterator!((IntoIter) => (String, Value)); - -////////////////////////////////////////////////////////////////////////////// - -/// An iterator over a toml::Map's keys. -pub struct Keys<'a> { - iter: KeysImpl<'a>, -} - -type KeysImpl<'a> = indexmap::map::Keys<'a, String, Value>; - -delegate_iterator!((Keys<'a>) => &'a String); - -////////////////////////////////////////////////////////////////////////////// - -/// An iterator over a toml::Map's values. -pub struct Values<'a> { - iter: ValuesImpl<'a>, -} - -type ValuesImpl<'a> = indexmap::map::Values<'a, String, Value>; - -delegate_iterator!((Values<'a>) => &'a Value); diff --git a/crates/toml_edit/src/easy/mod.rs b/crates/toml_edit/src/easy/mod.rs deleted file mode 100644 index 3bc46193..00000000 --- a/crates/toml_edit/src/easy/mod.rs +++ /dev/null @@ -1,21 +0,0 @@ -#![doc(hidden)] -#![deprecated(since = "0.18.0", note = "Replaced with `toml::Value`")] -#![allow(deprecated)] - -mod datetime; - -#[doc(hidden)] -pub mod macros; -pub mod map; -pub mod value; - -pub use crate::de; -pub use crate::ser; -pub use crate::toml; -#[doc(no_inline)] -pub use de::{from_document, from_slice, from_str, Deserializer}; -#[doc(no_inline)] -pub use ser::{to_document, to_string, to_string_pretty, to_vec, ValueSerializer}; -pub use serde_spanned::Spanned; -#[doc(no_inline)] -pub use value::Value; diff --git a/crates/toml_edit/src/easy/value.rs b/crates/toml_edit/src/easy/value.rs deleted file mode 100644 index 636c49b8..00000000 --- a/crates/toml_edit/src/easy/value.rs +++ /dev/null @@ -1,567 +0,0 @@ -//! Definition of a TOML value - -use std::collections::{BTreeMap, HashMap}; -use std::hash::Hash; -use std::mem::discriminant; -use std::ops; -use std::str::FromStr; - -use serde::de::IntoDeserializer as _; -use serde::Deserialize as _; -use serde::Serialize as _; - -pub use crate::easy::datetime::*; -use crate::easy::map::Entry; -pub use crate::easy::map::Map; - -#[doc(hidden)] -#[deprecated(since = "0.18.0", note = "Replaced with `toml::Value`")] -#[derive(PartialEq, Clone, Debug)] -pub enum Value { - /// Represents a TOML integer - Integer(i64), - /// Represents a TOML float - Float(f64), - /// Represents a TOML boolean - Boolean(bool), - /// Represents a TOML datetime - Datetime(Datetime), - /// Represents a TOML string - String(String), - /// Represents a TOML array - Array(Array), - /// Represents a TOML table - Table(Table), -} - -#[doc(hidden)] -#[deprecated(since = "0.18.0", note = "Replaced with `toml::value::Array`")] -pub type Array = Vec; - -#[doc(hidden)] -#[deprecated(since = "0.18.0", note = "Replaced with `toml::Table`")] -pub type Table = Map; - -impl Value { - /// Convert a `T` into `toml::Value` which is an enum that can represent - /// any valid TOML data. - /// - /// This conversion can fail if `T`'s implementation of `Serialize` decides to - /// fail, or if `T` contains a map with non-string keys. - pub fn try_from(value: T) -> Result - where - T: serde::ser::Serialize, - { - let value = value.serialize(super::ValueSerializer::new())?; - let value = value.into_deserializer(); - let target = Self::deserialize(value)?; - Ok(target) - } - - /// Interpret a `toml::Value` as an instance of type `T`. - /// - /// This conversion can fail if the structure of the `Value` does not match the - /// structure expected by `T`, for example if `T` is a struct type but the - /// `Value` contains something other than a TOML table. It can also fail if the - /// structure is correct but `T`'s implementation of `Deserialize` decides that - /// something is wrong with the data, for example required struct fields are - /// missing from the TOML map or some number is too big to fit in the expected - /// primitive type. - pub fn try_into(self) -> Result - where - T: serde::de::DeserializeOwned, - { - let value = (&self).serialize(super::ValueSerializer::new())?; - let value = value.into_deserializer(); - let target = T::deserialize(value)?; - Ok(target) - } - - /// Index into a TOML array or map. A string index can be used to access a - /// value in a map, and a usize index can be used to access an element of an - /// array. - /// - /// Returns `None` if the type of `self` does not match the type of the - /// index, for example if the index is a string and `self` is an array or a - /// number. Also returns `None` if the given key does not exist in the map - /// or the given index is not within the bounds of the array. - pub fn get(&self, index: I) -> Option<&Value> { - index.index(self) - } - - /// Mutably index into a TOML array or map. A string index can be used to - /// access a value in a map, and a usize index can be used to access an - /// element of an array. - /// - /// Returns `None` if the type of `self` does not match the type of the - /// index, for example if the index is a string and `self` is an array or a - /// number. Also returns `None` if the given key does not exist in the map - /// or the given index is not within the bounds of the array. - pub fn get_mut(&mut self, index: I) -> Option<&mut Value> { - index.index_mut(self) - } - - /// Extracts the integer value if it is an integer. - pub fn as_integer(&self) -> Option { - match *self { - Value::Integer(i) => Some(i), - _ => None, - } - } - - /// Tests whether this value is an integer. - pub fn is_integer(&self) -> bool { - self.as_integer().is_some() - } - - /// Extracts the float value if it is a float. - pub fn as_float(&self) -> Option { - match *self { - Value::Float(f) => Some(f), - _ => None, - } - } - - /// Tests whether this value is a float. - pub fn is_float(&self) -> bool { - self.as_float().is_some() - } - - /// Extracts the boolean value if it is a boolean. - pub fn as_bool(&self) -> Option { - match *self { - Value::Boolean(b) => Some(b), - _ => None, - } - } - - /// Tests whether this value is a boolean. - pub fn is_bool(&self) -> bool { - self.as_bool().is_some() - } - - /// Extracts the string of this value if it is a string. - pub fn as_str(&self) -> Option<&str> { - match *self { - Value::String(ref s) => Some(&**s), - _ => None, - } - } - - /// Tests if this value is a string. - pub fn is_str(&self) -> bool { - self.as_str().is_some() - } - - /// Extracts the datetime value if it is a datetime. - /// - /// Note that a parsed TOML value will only contain ISO 8601 dates. An - /// example date is: - /// - /// ```notrust - /// 1979-05-27T07:32:00Z - /// ``` - pub fn as_datetime(&self) -> Option<&Datetime> { - match *self { - Value::Datetime(ref s) => Some(s), - _ => None, - } - } - - /// Tests whether this value is a datetime. - pub fn is_datetime(&self) -> bool { - self.as_datetime().is_some() - } - - /// Extracts the array value if it is an array. - pub fn as_array(&self) -> Option<&Vec> { - match *self { - Value::Array(ref s) => Some(s), - _ => None, - } - } - - /// Extracts the array value if it is an array. - pub fn as_array_mut(&mut self) -> Option<&mut Vec> { - match *self { - Value::Array(ref mut s) => Some(s), - _ => None, - } - } - - /// Tests whether this value is an array. - pub fn is_array(&self) -> bool { - self.as_array().is_some() - } - - /// Extracts the table value if it is a table. - pub fn as_table(&self) -> Option<&Table> { - match *self { - Value::Table(ref s) => Some(s), - _ => None, - } - } - - /// Extracts the table value if it is a table. - pub fn as_table_mut(&mut self) -> Option<&mut Table> { - match *self { - Value::Table(ref mut s) => Some(s), - _ => None, - } - } - - /// Tests whether this value is a table. - pub fn is_table(&self) -> bool { - self.as_table().is_some() - } - - /// Tests whether this and another value have the same type. - pub fn same_type(&self, other: &Value) -> bool { - discriminant(self) == discriminant(other) - } - - /// Returns a human-readable representation of the type of this value. - pub fn type_str(&self) -> &'static str { - match *self { - Value::String(..) => "string", - Value::Integer(..) => "integer", - Value::Float(..) => "float", - Value::Boolean(..) => "boolean", - Value::Datetime(..) => "datetime", - Value::Array(..) => "array", - Value::Table(..) => "table", - } - } -} - -impl std::fmt::Display for Value { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match *self { - Value::String(..) - | Value::Integer(..) - | Value::Float(..) - | Value::Boolean(..) - | Value::Datetime(..) - | Value::Array(..) => self - .serialize(super::ValueSerializer::new()) - .map_err(|_| std::fmt::Error)? - .fmt(f), - Value::Table(_) => crate::ser::to_string_pretty(self) - .map_err(|_| std::fmt::Error)? - .fmt(f), - } - } -} - -impl ops::Index for Value -where - I: Index, -{ - type Output = Value; - - fn index(&self, index: I) -> &Value { - self.get(index).expect("index not found") - } -} - -impl ops::IndexMut for Value -where - I: Index, -{ - fn index_mut(&mut self, index: I) -> &mut Value { - self.get_mut(index).expect("index not found") - } -} - -impl<'a> From<&'a str> for Value { - #[inline] - fn from(val: &'a str) -> Value { - Value::String(val.to_string()) - } -} - -impl> From> for Value { - fn from(val: Vec) -> Value { - Value::Array(val.into_iter().map(|v| v.into()).collect()) - } -} - -impl, V: Into> From> for Value { - fn from(val: BTreeMap) -> Value { - let table = val.into_iter().map(|(s, v)| (s.into(), v.into())).collect(); - - Value::Table(table) - } -} - -impl + Hash + Eq, V: Into> From> for Value { - fn from(val: HashMap) -> Value { - let table = val.into_iter().map(|(s, v)| (s.into(), v.into())).collect(); - - Value::Table(table) - } -} - -macro_rules! impl_into_value { - ($variant:ident : $T:ty) => { - impl From<$T> for Value { - #[inline] - fn from(val: $T) -> Value { - Value::$variant(val.into()) - } - } - }; -} - -impl_into_value!(String: String); -impl_into_value!(Integer: i64); -impl_into_value!(Integer: i32); -impl_into_value!(Integer: i8); -impl_into_value!(Integer: u8); -impl_into_value!(Integer: u32); -impl_into_value!(Float: f64); -impl_into_value!(Float: f32); -impl_into_value!(Boolean: bool); -impl_into_value!(Datetime: Datetime); -impl_into_value!(Table: Table); - -/// Types that can be used to index a `toml_edit::easy::Value` -/// -/// Currently this is implemented for `usize` to index arrays and `str` to index -/// tables. -/// -/// This trait is sealed and not intended for implementation outside of the -/// `toml` crate. -pub trait Index: crate::private::Sealed { - #[doc(hidden)] - fn index<'a>(&self, val: &'a Value) -> Option<&'a Value>; - #[doc(hidden)] - fn index_mut<'a>(&self, val: &'a mut Value) -> Option<&'a mut Value>; -} - -impl Index for usize { - fn index<'a>(&self, val: &'a Value) -> Option<&'a Value> { - match *val { - Value::Array(ref a) => a.get(*self), - _ => None, - } - } - - fn index_mut<'a>(&self, val: &'a mut Value) -> Option<&'a mut Value> { - match *val { - Value::Array(ref mut a) => a.get_mut(*self), - _ => None, - } - } -} - -impl Index for str { - fn index<'a>(&self, val: &'a Value) -> Option<&'a Value> { - match *val { - Value::Table(ref a) => a.get(self), - _ => None, - } - } - - fn index_mut<'a>(&self, val: &'a mut Value) -> Option<&'a mut Value> { - match *val { - Value::Table(ref mut a) => a.get_mut(self), - _ => None, - } - } -} - -impl Index for String { - fn index<'a>(&self, val: &'a Value) -> Option<&'a Value> { - self[..].index(val) - } - - fn index_mut<'a>(&self, val: &'a mut Value) -> Option<&'a mut Value> { - self[..].index_mut(val) - } -} - -impl<'s, T: ?Sized> Index for &'s T -where - T: Index, -{ - fn index<'a>(&self, val: &'a Value) -> Option<&'a Value> { - (**self).index(val) - } - - fn index_mut<'a>(&self, val: &'a mut Value) -> Option<&'a mut Value> { - (**self).index_mut(val) - } -} - -impl FromStr for Value { - type Err = crate::easy::de::Error; - fn from_str(s: &str) -> Result { - crate::easy::from_str(s) - } -} - -impl serde::Serialize for Value { - fn serialize(&self, serializer: S) -> Result - where - S: serde::Serializer, - { - match self { - Value::Integer(value) => value.serialize(serializer), - Value::Float(value) => value.serialize(serializer), - Value::Boolean(value) => value.serialize(serializer), - Value::Datetime(value) => value.serialize(serializer), - Value::String(value) => value.serialize(serializer), - Value::Array(value) => value.serialize(serializer), - Value::Table(value) => value.serialize(serializer), - } - } -} - -impl<'de> serde::de::Deserialize<'de> for Value { - fn deserialize(deserializer: D) -> Result - where - D: serde::de::Deserializer<'de>, - { - struct ValueVisitor; - - impl<'de> serde::de::Visitor<'de> for ValueVisitor { - type Value = Value; - - fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - formatter.write_str("any valid TOML value") - } - - fn visit_bool(self, value: bool) -> Result { - Ok(Value::Boolean(value)) - } - - fn visit_i64(self, value: i64) -> Result { - Ok(Value::Integer(value)) - } - - fn visit_u64(self, value: u64) -> Result { - if value <= i64::max_value() as u64 { - Ok(Value::Integer(value as i64)) - } else { - Err(serde::de::Error::custom("u64 value was too large")) - } - } - - fn visit_u32(self, value: u32) -> Result { - Ok(Value::Integer(value.into())) - } - - fn visit_i32(self, value: i32) -> Result { - Ok(Value::Integer(value.into())) - } - - fn visit_f64(self, value: f64) -> Result { - Ok(Value::Float(value)) - } - - fn visit_str(self, value: &str) -> Result { - Ok(Value::String(value.into())) - } - - fn visit_string(self, value: String) -> Result { - Ok(Value::String(value)) - } - - fn visit_some(self, deserializer: D) -> Result - where - D: serde::de::Deserializer<'de>, - { - serde::de::Deserialize::deserialize(deserializer) - } - - fn visit_seq(self, mut visitor: V) -> Result - where - V: serde::de::SeqAccess<'de>, - { - let mut vec = Vec::new(); - while let Some(elem) = visitor.next_element()? { - vec.push(elem); - } - Ok(Value::Array(vec)) - } - - fn visit_map(self, mut visitor: V) -> Result - where - V: serde::de::MapAccess<'de>, - { - let mut key = String::new(); - let datetime = visitor.next_key_seed(DatetimeOrTable { key: &mut key })?; - match datetime { - Some(true) => { - let date: String = visitor.next_value()?; - let date = date.parse::().map_err(serde::de::Error::custom)?; - return Ok(Value::Datetime(date)); - } - None => return Ok(Value::Table(Map::new())), - Some(false) => {} - } - let mut map = Map::new(); - map.insert(key, visitor.next_value()?); - while let Some(key) = visitor.next_key::()? { - if let Entry::Vacant(vacant) = map.entry(&key) { - vacant.insert(visitor.next_value()?); - } else { - let msg = format!("duplicate key: `{}`", key); - return Err(serde::de::Error::custom(msg)); - } - } - Ok(Value::Table(map)) - } - } - - deserializer.deserialize_any(ValueVisitor) - } -} - -struct DatetimeOrTable<'a> { - key: &'a mut String, -} - -impl<'a, 'de> serde::de::DeserializeSeed<'de> for DatetimeOrTable<'a> { - type Value = bool; - - fn deserialize(self, deserializer: D) -> Result - where - D: serde::de::Deserializer<'de>, - { - deserializer.deserialize_any(self) - } -} - -impl<'a, 'de> serde::de::Visitor<'de> for DatetimeOrTable<'a> { - type Value = bool; - - fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - formatter.write_str("a string key") - } - - fn visit_str(self, s: &str) -> Result - where - E: serde::de::Error, - { - if s == toml_datetime::__unstable::FIELD { - Ok(true) - } else { - self.key.push_str(s); - Ok(false) - } - } - - fn visit_string(self, s: String) -> Result - where - E: serde::de::Error, - { - if s == toml_datetime::__unstable::FIELD { - Ok(true) - } else { - *self.key = s; - Ok(false) - } - } -} diff --git a/crates/toml_edit/src/lib.rs b/crates/toml_edit/src/lib.rs index 73082c88..81a68fce 100644 --- a/crates/toml_edit/src/lib.rs +++ b/crates/toml_edit/src/lib.rs @@ -78,9 +78,6 @@ mod repr; mod table; mod value; -#[cfg(feature = "easy")] -pub mod easy; - #[cfg(feature = "serde")] pub mod de; #[cfg(feature = "serde")] diff --git a/crates/toml_edit/src/parser/errors.rs b/crates/toml_edit/src/parser/errors.rs index ffe30fea..0baf6bdd 100644 --- a/crates/toml_edit/src/parser/errors.rs +++ b/crates/toml_edit/src/parser/errors.rs @@ -72,18 +72,6 @@ impl TomlError { pub(crate) fn set_original(&mut self, original: Option) { self.original = original; } - - /// Produces a (line, column) pair of the position of the error if available - /// - /// All indexes are 0-based. - #[deprecated(since = "0.18.0", note = "See instead `TomlError::span`")] - pub fn line_col(&self) -> Option<(usize, usize)> { - if let (Some(original), Some(span)) = (&self.original, self.span()) { - Some(translate_position(original.as_bytes(), span.start)) - } else { - None - } - } } /// Displays a TOML parse error