/// Serializes `value` into `writer`. /// /// This function does not generate any newlines or nice formatting; /// if you want that, you can use [`to_writer_pretty`] instead. pubfn to_writer<W, T>(writer: W, value: &T) -> Result<()> where
W: fmt::Write,
T: ?Sized + Serialize,
{
Options::default().to_writer(writer, value)
}
/// Serializes `value` into `writer` in a pretty way. pubfn to_writer_pretty<W, T>(writer: W, value: &T, config: PrettyConfig) -> Result<()> where
W: fmt::Write,
T: ?Sized + Serialize,
{
Options::default().to_writer_pretty(writer, value, config)
}
/// Serializes `value` and returns it as string. /// /// This function does not generate any newlines or nice formatting; /// if you want that, you can use [`to_string_pretty`] instead. pubfn to_string<T>(value: &T) -> Result<String> where
T: ?Sized + Serialize,
{
Options::default().to_string(value)
}
/// Serializes `value` in the recommended RON layout in a pretty way. pubfn to_string_pretty<T>(value: &T, config: PrettyConfig) -> Result<String> where
T: ?Sized + Serialize,
{
Options::default().to_string_pretty(value, config)
}
/// Pretty serializer state struct Pretty {
indent: usize,
}
/// Pretty serializer configuration. /// /// # Examples /// /// ``` /// use ron::ser::PrettyConfig; /// /// let my_config = PrettyConfig::new() /// .depth_limit(4) /// // definitely superior (okay, just joking) /// .indentor("\t"); /// ``` #[allow(clippy::struct_excessive_bools)] #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(default)] #[non_exhaustive] pubstruct PrettyConfig { /// Limit the pretty-ness up to the given depth. pub depth_limit: usize, /// New line string pub new_line: Cow<'static, str>, /// Indentation string pub indentor: Cow<'static, str>, /// Separator string pub separator: Cow<'static, str>, // Whether to emit struct names pub struct_names: bool, /// Separate tuple members with indentation pub separate_tuple_members: bool, /// Enumerate array items in comments pub enumerate_arrays: bool, /// Enable extensions. Only configures `implicit_some`, /// `unwrap_newtypes`, and `unwrap_variant_newtypes` for now. pub extensions: Extensions, /// Enable compact arrays, which do not insert new lines and indentation /// between the elements of an array pub compact_arrays: bool, /// Whether to serialize strings as escaped strings, /// or fall back onto raw strings if necessary. pub escape_strings: bool, /// Enable compact structs, which do not insert new lines and indentation /// between the fields of a struct pub compact_structs: bool, /// Enable compact maps, which do not insert new lines and indentation /// between the entries of a struct pub compact_maps: bool, /// Enable explicit number type suffixes like `1u16` pub number_suffixes: bool, /// Additional path-based field metadata to serialize pub path_meta: Option<path_meta::Field>,
}
/// Limits the pretty-formatting based on the number of indentations. /// I.e., with a depth limit of 5, starting with an element of depth /// (indentation level) 6, everything will be put into the same line, /// without pretty formatting. /// /// Default: [`usize::MAX`] #[must_use] pubfn depth_limit(mutself, depth_limit: usize) -> Self { self.depth_limit = depth_limit;
self
}
/// Configures the newlines used for serialization. /// /// Default: `\r\n` on Windows, `\n` otherwise #[must_use] pubfn new_line(mutself, new_line: impl Into<Cow<'static, str>>) -> Self { self.new_line = new_line.into();
self
}
/// Configures the string sequence used for indentation. /// /// Default: 4 spaces #[must_use] pubfn indentor(mutself, indentor: impl Into<Cow<'static, str>>) -> Self { self.indentor = indentor.into();
self
}
/// Configures the string sequence used to separate items inline. /// /// Default: 1 space #[must_use] pubfn separator(mutself, separator: impl Into<Cow<'static, str>>) -> Self { self.separator = separator.into();
self
}
/// Configures whether to emit struct names. /// /// See also [`Extensions::EXPLICIT_STRUCT_NAMES`] for the extension equivalent. /// /// Default: `false` #[must_use] pubfn struct_names(mutself, struct_names: bool) -> Self { self.struct_names = struct_names;
self
}
/// Configures whether tuples are single- or multi-line. /// If set to `true`, tuples will have their fields indented and in new /// lines. If set to `false`, tuples will be serialized without any /// newlines or indentations. /// /// Default: `false` #[must_use] pubfn separate_tuple_members(mutself, separate_tuple_members: bool) -> Self { self.separate_tuple_members = separate_tuple_members;
self
}
/// Configures whether a comment shall be added to every array element, /// indicating the index. /// /// Default: `false` #[must_use] pubfn enumerate_arrays(mutself, enumerate_arrays: bool) -> Self { self.enumerate_arrays = enumerate_arrays;
self
}
/// Configures whether every array should be a single line (`true`) /// or a multi line one (`false`). /// /// When `false`, `["a","b"]` will serialize to /// ``` /// [ /// "a", /// "b", /// ] /// # ; /// ``` /// When `true`, `["a","b"]` will instead serialize to /// ``` /// ["a","b"] /// # ; /// ``` /// /// Default: `false` #[must_use] pubfn compact_arrays(mutself, compact_arrays: bool) -> Self { self.compact_arrays = compact_arrays;
/// Configures whether strings should be serialized using escapes (true) /// or fall back to raw strings if the string contains a `"` (false). /// /// When `true`, `"a\nb"` will serialize to /// ``` /// "a\nb" /// # ; /// ``` /// When `false`, `"a\nb"` will instead serialize to /// ``` /// "a /// b" /// # ; /// ``` /// /// Default: `true` #[must_use] pubfn escape_strings(mutself, escape_strings: bool) -> Self { self.escape_strings = escape_strings;
self
}
/// Configures whether every struct should be a single line (`true`) /// or a multi line one (`false`). /// /// When `false`, `Struct { a: 4, b: 2 }` will serialize to /// ```ignore /// Struct( /// a: 4, /// b: 2, /// ) /// # ; /// ``` /// When `true`, `Struct { a: 4, b: 2 }` will instead serialize to /// ```ignore /// Struct(a: 4, b: 2) /// # ; /// ``` /// /// Default: `false` #[must_use] pubfn compact_structs(mutself, compact_structs: bool) -> Self { self.compact_structs = compact_structs;
self
}
/// Configures whether every map should be a single line (`true`) /// or a multi line one (`false`). /// /// When `false`, a map with entries `{ "a": 4, "b": 2 }` will serialize to /// ```ignore /// { /// "a": 4, /// "b": 2, /// } /// # ; /// ``` /// When `true`, a map with entries `{ "a": 4, "b": 2 }` will instead /// serialize to /// ```ignore /// {"a": 4, "b": 2} /// # ; /// ``` /// /// Default: `false` #[must_use] pubfn compact_maps(mutself, compact_maps: bool) -> Self { self.compact_maps = compact_maps;
self
}
/// Configures whether numbers should be printed without (`false`) or /// with (`true`) their explicit type suffixes. /// /// When `false`, the integer `12345u16` will serialize to /// ```ignore /// 12345 /// # ; /// ``` /// and the float `12345.6789f64` will serialize to /// ```ignore /// 12345.6789 /// # ; /// ``` /// When `true`, the integer `12345u16` will serialize to /// ```ignore /// 12345u16 /// # ; /// ``` /// and the float `12345.6789f64` will serialize to /// ```ignore /// 12345.6789f64 /// # ; /// ``` /// /// Default: `false` #[must_use] pubfn number_suffixes(mutself, number_suffixes: bool) -> Self { self.number_suffixes = number_suffixes;
/// The RON serializer. /// /// You can just use [`to_string`] for deserializing a value. /// If you want it pretty-printed, take a look at [`to_string_pretty`]. pubstruct Serializer<W: fmt::Write> {
output: W,
pretty: Option<(PrettyConfig, Pretty)>,
default_extensions: Extensions,
is_empty: Option<bool>,
newtype_variant: bool,
recursion_limit: Option<usize>, // Tracks the number of opened implicit `Some`s, set to 0 on backtracking
implicit_some_depth: usize,
}
impl<W: fmt::Write> Serializer<W> { /// Creates a new [`Serializer`]. /// /// Most of the time you can just use [`to_string`] or /// [`to_string_pretty`]. pubfn new(writer: W, config: Option<PrettyConfig>) -> Result<Self> { Self::with_options(writer, config, &Options::default())
}
/// Creates a new [`Serializer`]. /// /// Most of the time you can just use [`to_string`] or /// [`to_string_pretty`]. pubfn with_options( mut writer: W,
config: Option<PrettyConfig>,
options: &Options,
) -> Result<Self> { iflet Some(conf) = &config { if !conf.new_line.chars().all(is_whitespace_char) { return Err(Error::Message(String::from( "Invalid non-whitespace `PrettyConfig::new_line`",
)));
} if !conf.indentor.chars().all(is_whitespace_char) { return Err(Error::Message(String::from( "Invalid non-whitespace `PrettyConfig::indentor`",
)));
} if !conf.separator.chars().all(is_whitespace_char) { return Err(Error::Message(String::from( "Invalid non-whitespace `PrettyConfig::separator`",
)));
}
let non_default_extensions = !options.default_extensions;
/// Checks if struct names should be emitted /// /// Note that when using the `explicit_struct_names` extension, this method will use an OR operation on the extension and the [`PrettyConfig::struct_names`] option. See also [`Extensions::EXPLICIT_STRUCT_NAMES`] for the extension equivalent. fn struct_names(&self) -> bool { self.extensions()
.contains(Extensions::EXPLICIT_STRUCT_NAMES)
|| self
.pretty
.as_ref()
.map_or(false, |(pc, _)| pc.struct_names)
}
}
impl<'a, W: fmt::Write> ser::Serializer for &'a mut Serializer<W> { type Error = Error; type Ok = (); type SerializeMap = Compound<'a, W>; type SerializeSeq = Compound<'a, W>; type SerializeStruct = Compound<'a, W>; type SerializeStructVariant = Compound<'a, W>; type SerializeTuple = Compound<'a, W>; type SerializeTupleStruct = Compound<'a, W>; type SerializeTupleVariant = Compound<'a, W>;
fn serialize_bytes(self, v: &[u8]) -> Result<()> { // We need to fall back to escaping if the byte string would be invalid UTF-8 if !self.escape_strings() { iflet Ok(v) = core::str::from_utf8(v) { returnself
.serialize_unescaped_or_raw_byte_str(v)
.map_err(Error::from);
}
}
self.serialize_escaped_byte_str(v)?;
Ok(())
}
fn serialize_none(self) -> Result<()> { // We no longer need to keep track of the depth let implicit_some_depth = self.implicit_some_depth; self.implicit_some_depth = 0;
for _ in0..implicit_some_depth { self.output.write_str("Some(")?;
} self.output.write_str("None")?; for _ in0..implicit_some_depth { self.output.write_char(')')?;
}
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.