Change names to saphyr_serde.

This commit is contained in:
Ethiraric 2024-10-21 00:16:45 +02:00
parent 71cb7f162f
commit a8ee8c31c2
28 changed files with 553 additions and 460 deletions

View file

@ -9,6 +9,8 @@ members = [
"bench/tools/gen_large_yaml", "bench/tools/gen_large_yaml",
"bench/tools/bench_compare", "bench/tools/bench_compare",
"fuzz", "fuzz",
"serde",
"serde/fuzz",
] ]
resolver = "2" resolver = "2"

View file

@ -3,8 +3,8 @@ name = "saphyr-parser"
readme = "README.md" readme = "README.md"
authors = { workspace = true } authors = { workspace = true }
categories = { workspace = true } categories = { workspace = true }
description = { workspace = true } description = "A fully YAML 1.2 compliant YAML parser"
documentation = { workspace = true } documentation = "https://docs.rs/saphyr-parser"
edition = { workspace = true } edition = { workspace = true }
keywords = { workspace = true } keywords = { workspace = true }
license = { workspace = true } license = { workspace = true }

View file

@ -0,0 +1,191 @@
Copyright (c) 2024 Ethiraric
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS

View file

@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2024 Ethiraric
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View file

@ -1,15 +1,20 @@
[package] [package]
name = "serde_yaml" name = "saphyr-serde"
version = "0.9.34+deprecated" readme = "README.md"
authors = ["David Tolnay <dtolnay@gmail.com>"] authors = [
"David Tolnay <dtolnay@gmail.com>",
"Ethiraric <ethiraric@gmail.com>",
"David Aguilar <davvid@gmail.com>",
]
categories = ["encoding", "parser-implementations"] categories = ["encoding", "parser-implementations"]
description = "YAML data format for Serde" description = "YAML data format for Serde"
documentation = "https://docs.rs/serde_yaml/" documentation = "https://docs.rs/saphyr-serde/"
edition = "2021" edition = { workspace = true }
keywords = ["yaml", "serde", "serialization"] keywords = ["yaml", "serde", "serialization"]
license = "MIT OR Apache-2.0" license = { workspace = true }
repository = "https://github.com/dtolnay/serde-yaml" repository = { workspace = true }
rust-version = "1.64" rust-version = "1.64"
version = { workspace = true }
[dependencies] [dependencies]
indexmap = "2.2.1" indexmap = "2.2.1"
@ -21,7 +26,7 @@ unsafe-libyaml = "0.2.11"
[dev-dependencies] [dev-dependencies]
anyhow = "1.0.79" anyhow = "1.0.79"
indoc = "2.0" indoc = "2.0"
serde_derive = "1.0.195" serde = { version = "1.0.195", features = ["derive"] }
[lib] [lib]
doc-scrape-examples = false doc-scrape-examples = false

3
serde/LICENSE Normal file
View file

@ -0,0 +1,3 @@
This code is based on the work of [dtolnay](https://github.com/dtolnay)'s [`serde-yaml`](https://github.com/dtolnay/serde-yaml/).
As thus, redistributions of this Work must include licenses of both dtolnay and Ethiraric.

View file

@ -1,51 +1,42 @@
Serde YAML `saphyr-serde`
========== ==============
[<img alt="github" src="https://img.shields.io/badge/github-dtolnay/serde--yaml-8da0cb?style=for-the-badge&labelColor=555555&logo=github" height="20">](https://github.com/dtolnay/serde-yaml) Rust library for using the [`serde`] serialization framework with data in [YAML]
[<img alt="crates.io" src="https://img.shields.io/crates/v/serde_yaml.svg?style=for-the-badge&color=fc8d62&logo=rust" height="20">](https://crates.io/crates/serde_yaml) file format.
[<img alt="docs.rs" src="https://img.shields.io/badge/docs.rs-serde__yaml-66c2a5?style=for-the-badge&labelColor=555555&logo=docs.rs" height="20">](https://docs.rs/serde_yaml)
[<img alt="build status" src="https://img.shields.io/github/actions/workflow/status/dtolnay/serde-yaml/ci.yml?branch=master&style=for-the-badge" height="20">](https://github.com/dtolnay/serde-yaml/actions?query=branch%3Amaster)
Rust library for using the [Serde] serialization framework with data in [YAML] This project is a continuation of [dtolnay]'s [`serde-yaml`]. The backend has
file format. _(This project is no longer maintained.)_ been changed from [`unsafe-libyaml`] to [`saphyr-parser`].
[Serde]: https://github.com/serde-rs/serde
[YAML]: https://yaml.org/
## Dependency ## Dependency
```toml ```sh
[dependencies] cargo add serde
serde = "1.0" cargo add saphyr-serde
serde_yaml = "0.9"
``` ```
Release notes are available under [GitHub releases]. Release notes are available under [GitHub releases].
[GitHub releases]: https://github.com/dtolnay/serde-yaml/releases
## Using Serde YAML ## Using `saphyr-serde`
[API documentation is available in rustdoc form][docs.rs] but the general idea [API documentation is available in rustdoc form][docs.rs] but the general idea
is: is:
[docs.rs]: https://docs.rs/serde_yaml
```rust ```rust
use std::collections::BTreeMap; use std::collections::BTreeMap;
fn main() -> Result<(), serde_yaml::Error> { fn main() -> Result<(), saphyr_serde::Error> {
// You have some type. // You have some type.
let mut map = BTreeMap::new(); let mut map = BTreeMap::new();
map.insert("x".to_string(), 1.0); map.insert("x".to_string(), 1.0);
map.insert("y".to_string(), 2.0); map.insert("y".to_string(), 2.0);
// Serialize it to a YAML string. // Serialize it to a YAML string.
let yaml = serde_yaml::to_string(&map)?; let yaml = saphyr_serde::to_string(&map)?;
assert_eq!(yaml, "x: 1.0\ny: 2.0\n"); assert_eq!(yaml, "x: 1.0\ny: 2.0\n");
// Deserialize it back to a Rust type. // Deserialize it back to a Rust type.
let deserialized_map: BTreeMap<String, f64> = serde_yaml::from_str(&yaml)?; let deserialized_map: BTreeMap<String, f64> = saphyr_serde::from_str(&yaml)?;
assert_eq!(map, deserialized_map); assert_eq!(map, deserialized_map);
Ok(()) Ok(())
} }
@ -54,10 +45,9 @@ fn main() -> Result<(), serde_yaml::Error> {
It can also be used with Serde's derive macros to handle structs and enums It can also be used with Serde's derive macros to handle structs and enums
defined in your program. defined in your program.
```toml ```sh
[dependencies] cargo add serde --features derive
serde = { version = "1.0", features = ["derive"] } cargo add saphyr-serde
serde_yaml = "0.9"
``` ```
Structs serialize in the obvious way: Structs serialize in the obvious way:
@ -71,13 +61,13 @@ struct Point {
y: f64, y: f64,
} }
fn main() -> Result<(), serde_yaml::Error> { fn main() -> Result<(), saphyr_serde::Error> {
let point = Point { x: 1.0, y: 2.0 }; let point = Point { x: 1.0, y: 2.0 };
let yaml = serde_yaml::to_string(&point)?; let yaml = saphyr_serde::to_string(&point)?;
assert_eq!(yaml, "x: 1.0\ny: 2.0\n"); assert_eq!(yaml, "x: 1.0\ny: 2.0\n");
let deserialized_point: Point = serde_yaml::from_str(&yaml)?; let deserialized_point: Point = saphyr_serde::from_str(&yaml)?;
assert_eq!(point, deserialized_point); assert_eq!(point, deserialized_point);
Ok(()) Ok(())
} }
@ -96,13 +86,13 @@ enum Enum {
Struct { x: f64, y: f64 }, Struct { x: f64, y: f64 },
} }
fn main() -> Result<(), serde_yaml::Error> { fn main() -> Result<(), saphyr_serde::Error> {
let yaml = " let yaml = "
- !Newtype 1 - !Newtype 1
- !Tuple [0, 0, 0] - !Tuple [0, 0, 0]
- !Struct {x: 1.0, y: 2.0} - !Struct {x: 1.0, y: 2.0}
"; ";
let values: Vec<Enum> = serde_yaml::from_str(yaml).unwrap(); let values: Vec<Enum> = saphyr_serde::from_str(yaml).unwrap();
assert_eq!(values[0], Enum::Newtype(1)); assert_eq!(values[0], Enum::Newtype(1));
assert_eq!(values[1], Enum::Tuple(0, 0, 0)); assert_eq!(values[1], Enum::Tuple(0, 0, 0));
assert_eq!(values[2], Enum::Struct { x: 1.0, y: 2.0 }); assert_eq!(values[2], Enum::Struct { x: 1.0, y: 2.0 });
@ -117,7 +107,7 @@ fn main() -> Result<(), serde_yaml::Error> {
x: 1.0 x: 1.0
y: 2.0 y: 2.0
"; ";
let values: Vec<Enum> = serde_yaml::from_str(yaml).unwrap(); let values: Vec<Enum> = saphyr_serde::from_str(yaml).unwrap();
assert_eq!(values[0], Enum::Tuple(0, 0, 0)); assert_eq!(values[0], Enum::Tuple(0, 0, 0));
assert_eq!(values[1], Enum::Struct { x: 1.0, y: 2.0 }); assert_eq!(values[1], Enum::Struct { x: 1.0, y: 2.0 });
@ -126,7 +116,7 @@ fn main() -> Result<(), serde_yaml::Error> {
- Unit # serialization produces this one - Unit # serialization produces this one
- !Unit - !Unit
"; ";
let values: Vec<Enum> = serde_yaml::from_str(yaml).unwrap(); let values: Vec<Enum> = saphyr_serde::from_str(yaml).unwrap();
assert_eq!(values[0], Enum::Unit); assert_eq!(values[0], Enum::Unit);
assert_eq!(values[1], Enum::Unit); assert_eq!(values[1], Enum::Unit);
@ -139,8 +129,8 @@ fn main() -> Result<(), serde_yaml::Error> {
#### License #### License
<sup> <sup>
Licensed under either of <a href="LICENSE-APACHE">Apache License, Version Licensed under either of Apache License, Version 2.0 or MIT license at your
2.0</a> or <a href="LICENSE-MIT">MIT license</a> at your option. option.
</sup> </sup>
<br> <br>
@ -150,3 +140,12 @@ Unless you explicitly state otherwise, any contribution intentionally submitted
for inclusion in this crate by you, as defined in the Apache-2.0 license, shall for inclusion in this crate by you, as defined in the Apache-2.0 license, shall
be dual licensed as above, without any additional terms or conditions. be dual licensed as above, without any additional terms or conditions.
</sub> </sub>
[`serde`]: https://github.com/serde-rs/serde
[YAML]: https://yaml.org/
[dtolnay]: https://github.com/dtolnay
[`serde-yaml`]: https://github.com/dtolnay/serde-yaml
[`unsafe-libyaml`]: https://github.com/dtolnay/unsafe-libyaml
[`saphyr-parser`]: https://github.com/saphyr-rs/saphyr-parser
[GitHub releases]: https://github.com/saphyr-rs/saphyr-serde/releases
[docs.rs]: https://docs.rs/saphyr-serde

View file

@ -1,5 +1,5 @@
[package] [package]
name = "serde_yaml-fuzz" name = "saphyr_serde-fuzz"
version = "0.0.0" version = "0.0.0"
authors = ["David Tolnay <dtolnay@gmail.com>"] authors = ["David Tolnay <dtolnay@gmail.com>"]
edition = "2021" edition = "2021"
@ -10,12 +10,10 @@ cargo-fuzz = true
[dependencies] [dependencies]
libfuzzer-sys = "0.4" libfuzzer-sys = "0.4"
serde_yaml = { path = ".." } saphyr-serde = { path = ".." }
[[bin]] [[bin]]
name = "fuzz_from_slice" name = "fuzz_from_slice"
path = "fuzz_targets/fuzz_from_slice.rs" path = "fuzz_targets/fuzz_from_slice.rs"
test = false test = false
doc = false doc = false
[workspace]

View file

@ -4,6 +4,6 @@ use libfuzzer_sys::fuzz_target;
fuzz_target!(|data: &[u8]| { fuzz_target!(|data: &[u8]| {
if data.len() <= 10240 { if data.len() <= 10240 {
_ = serde_yaml::from_slice::<serde_yaml::Value>(data); _ = saphyr_serde::from_slice::<saphyr_serde::Value>(data);
} }
}); });

View file

@ -26,11 +26,11 @@ type Result<T, E = Error> = std::result::Result<T, E>;
/// ``` /// ```
/// use anyhow::Result; /// use anyhow::Result;
/// use serde::Deserialize; /// use serde::Deserialize;
/// use serde_yaml::Value; /// use saphyr_serde::Value;
/// ///
/// fn main() -> Result<()> { /// fn main() -> Result<()> {
/// let input = "k: 107\n"; /// let input = "k: 107\n";
/// let de = serde_yaml::Deserializer::from_str(input); /// let de = saphyr_serde::Deserializer::from_str(input);
/// let value = Value::deserialize(de)?; /// let value = Value::deserialize(de)?;
/// println!("{:?}", value); /// println!("{:?}", value);
/// Ok(()) /// Ok(())
@ -42,12 +42,12 @@ type Result<T, E = Error> = std::result::Result<T, E>;
/// ``` /// ```
/// use anyhow::Result; /// use anyhow::Result;
/// use serde::Deserialize; /// use serde::Deserialize;
/// use serde_yaml::Value; /// use saphyr_serde::Value;
/// ///
/// fn main() -> Result<()> { /// fn main() -> Result<()> {
/// let input = "---\nk: 107\n...\n---\nj: 106\n"; /// let input = "---\nk: 107\n...\n---\nj: 106\n";
/// ///
/// for document in serde_yaml::Deserializer::from_str(input) { /// for document in saphyr_serde::Deserializer::from_str(input) {
/// let value = Value::deserialize(document)?; /// let value = Value::deserialize(document)?;
/// println!("{:?}", value); /// println!("{:?}", value);
/// } /// }

View file

@ -11,7 +11,7 @@ use std::sync::Arc;
/// An error that happened serializing or deserializing YAML data. /// An error that happened serializing or deserializing YAML data.
pub struct Error(Box<ErrorImpl>); pub struct Error(Box<ErrorImpl>);
/// Alias for a `Result` with the error type `serde_yaml::Error`. /// Alias for a `Result` with the error type `saphyr_serde::Error`.
pub type Result<T> = result::Result<T, Error>; pub type Result<T> = result::Result<T, Error>;
#[derive(Debug)] #[derive(Debug)]
@ -89,10 +89,10 @@ impl Error {
/// # Examples /// # Examples
/// ///
/// ``` /// ```
/// # use serde_yaml::{Value, Error}; /// # use saphyr_serde::{Value, Error};
/// # /// #
/// // The `@` character as the first character makes this invalid yaml /// // The `@` character as the first character makes this invalid yaml
/// let invalid_yaml: Result<Value, Error> = serde_yaml::from_str("@invalid_yaml"); /// let invalid_yaml: Result<Value, Error> = saphyr_serde::from_str("@invalid_yaml");
/// ///
/// let location = invalid_yaml.unwrap_err().location().unwrap(); /// let location = invalid_yaml.unwrap_err().location().unwrap();
/// ///

View file

@ -1,121 +1,5 @@
//! [![github]](https://github.com/dtolnay/serde-yaml)&ensp;[![crates-io]](https://crates.io/crates/serde-yaml)&ensp;[![docs-rs]](https://docs.rs/serde-yaml) #![doc = include_str!("../README.md")]
//! #![doc(html_root_url = "https://docs.rs/saphyr_serde/0.9.34+deprecated")]
//! [github]: https://img.shields.io/badge/github-8da0cb?style=for-the-badge&labelColor=555555&logo=github
//! [crates-io]: https://img.shields.io/badge/crates.io-fc8d62?style=for-the-badge&labelColor=555555&logo=rust
//! [docs-rs]: https://img.shields.io/badge/docs.rs-66c2a5?style=for-the-badge&labelColor=555555&logo=docs.rs
//!
//! <br>
//!
//! Rust library for using the [Serde] serialization framework with data in
//! [YAML] file format. _(This project is no longer maintained.)_
//!
//! [Serde]: https://github.com/serde-rs/serde
//! [YAML]: https://yaml.org/
//!
//! # Examples
//!
//! ```
//! use std::collections::BTreeMap;
//!
//! fn main() -> Result<(), serde_yaml::Error> {
//! // You have some type.
//! let mut map = BTreeMap::new();
//! map.insert("x".to_string(), 1.0);
//! map.insert("y".to_string(), 2.0);
//!
//! // Serialize it to a YAML string.
//! let yaml = serde_yaml::to_string(&map)?;
//! assert_eq!(yaml, "x: 1.0\ny: 2.0\n");
//!
//! // Deserialize it back to a Rust type.
//! let deserialized_map: BTreeMap<String, f64> = serde_yaml::from_str(&yaml)?;
//! assert_eq!(map, deserialized_map);
//! Ok(())
//! }
//! ```
//!
//! ## Using Serde derive
//!
//! It can also be used with Serde's derive macros to handle structs and enums
//! defined in your program.
//!
//! Structs serialize in the obvious way:
//!
//! ```
//! # use serde_derive::{Serialize, Deserialize};
//! use serde::{Serialize, Deserialize};
//!
//! #[derive(Serialize, Deserialize, PartialEq, Debug)]
//! struct Point {
//! x: f64,
//! y: f64,
//! }
//!
//! fn main() -> Result<(), serde_yaml::Error> {
//! let point = Point { x: 1.0, y: 2.0 };
//!
//! let yaml = serde_yaml::to_string(&point)?;
//! assert_eq!(yaml, "x: 1.0\ny: 2.0\n");
//!
//! let deserialized_point: Point = serde_yaml::from_str(&yaml)?;
//! assert_eq!(point, deserialized_point);
//! Ok(())
//! }
//! ```
//!
//! Enums serialize using YAML's `!tag` syntax to identify the variant name.
//!
//! ```
//! # use serde_derive::{Serialize, Deserialize};
//! use serde::{Serialize, Deserialize};
//!
//! #[derive(Serialize, Deserialize, PartialEq, Debug)]
//! enum Enum {
//! Unit,
//! Newtype(usize),
//! Tuple(usize, usize, usize),
//! Struct { x: f64, y: f64 },
//! }
//!
//! fn main() -> Result<(), serde_yaml::Error> {
//! let yaml = "
//! - !Newtype 1
//! - !Tuple [0, 0, 0]
//! - !Struct {x: 1.0, y: 2.0}
//! ";
//! let values: Vec<Enum> = serde_yaml::from_str(yaml).unwrap();
//! assert_eq!(values[0], Enum::Newtype(1));
//! assert_eq!(values[1], Enum::Tuple(0, 0, 0));
//! assert_eq!(values[2], Enum::Struct { x: 1.0, y: 2.0 });
//!
//! // The last two in YAML's block style instead:
//! let yaml = "
//! - !Tuple
//! - 0
//! - 0
//! - 0
//! - !Struct
//! x: 1.0
//! y: 2.0
//! ";
//! let values: Vec<Enum> = serde_yaml::from_str(yaml).unwrap();
//! assert_eq!(values[0], Enum::Tuple(0, 0, 0));
//! assert_eq!(values[1], Enum::Struct { x: 1.0, y: 2.0 });
//!
//! // Variants with no data can be written using !Tag or just the string name.
//! let yaml = "
//! - Unit # serialization produces this one
//! - !Unit
//! ";
//! let values: Vec<Enum> = serde_yaml::from_str(yaml).unwrap();
//! assert_eq!(values[0], Enum::Unit);
//! assert_eq!(values[1], Enum::Unit);
//!
//! Ok(())
//! }
//! ```
#![doc(html_root_url = "https://docs.rs/serde_yaml/0.9.34+deprecated")]
#![deny(missing_docs, unsafe_op_in_unsafe_fn)] #![deny(missing_docs, unsafe_op_in_unsafe_fn)]
// Suppressed clippy_pedantic lints // Suppressed clippy_pedantic lints
#![allow( #![allow(

View file

@ -9,7 +9,7 @@ use std::fmt::{self, Display};
use std::hash::{Hash, Hasher}; use std::hash::{Hash, Hasher};
use std::mem; use std::mem;
/// A YAML mapping in which the keys and values are both `serde_yaml::Value`. /// A YAML mapping in which the keys and values are both `saphyr_serde::Value`.
#[derive(Clone, Default, Eq, PartialEq)] #[derive(Clone, Default, Eq, PartialEq)]
pub struct Mapping { pub struct Mapping {
map: IndexMap<Value, Value>, map: IndexMap<Value, Value>,
@ -236,11 +236,11 @@ impl Mapping {
} }
} }
/// A type that can be used to index into a `serde_yaml::Mapping`. See the /// A type that can be used to index into a `saphyr_serde::Mapping`. See the
/// methods `get`, `get_mut`, `contains_key`, and `remove` of `Value`. /// methods `get`, `get_mut`, `contains_key`, and `remove` of `Value`.
/// ///
/// This trait is sealed and cannot be implemented for types outside of /// This trait is sealed and cannot be implemented for types outside of
/// `serde_yaml`. /// `saphyr_serde`.
pub trait Index: private::Sealed { pub trait Index: private::Sealed {
#[doc(hidden)] #[doc(hidden)]
fn is_key_into(&self, v: &Mapping) -> bool; fn is_key_into(&self, v: &Mapping) -> bool;
@ -547,7 +547,7 @@ macro_rules! delegate_iterator {
} }
} }
/// Iterator over `&serde_yaml::Mapping`. /// Iterator over `&saphyr_serde::Mapping`.
pub struct Iter<'a> { pub struct Iter<'a> {
iter: indexmap::map::Iter<'a, Value, Value>, iter: indexmap::map::Iter<'a, Value, Value>,
} }
@ -565,7 +565,7 @@ impl<'a> IntoIterator for &'a Mapping {
} }
} }
/// Iterator over `&mut serde_yaml::Mapping`. /// Iterator over `&mut saphyr_serde::Mapping`.
pub struct IterMut<'a> { pub struct IterMut<'a> {
iter: indexmap::map::IterMut<'a, Value, Value>, iter: indexmap::map::IterMut<'a, Value, Value>,
} }
@ -583,7 +583,7 @@ impl<'a> IntoIterator for &'a mut Mapping {
} }
} }
/// Iterator over `serde_yaml::Mapping` by value. /// Iterator over `saphyr_serde::Mapping` by value.
pub struct IntoIter { pub struct IntoIter {
iter: indexmap::map::IntoIter<Value, Value>, iter: indexmap::map::IntoIter<Value, Value>,
} }
@ -601,35 +601,35 @@ impl IntoIterator for Mapping {
} }
} }
/// Iterator of the keys of a `&serde_yaml::Mapping`. /// Iterator of the keys of a `&saphyr_serde::Mapping`.
pub struct Keys<'a> { pub struct Keys<'a> {
iter: indexmap::map::Keys<'a, Value, Value>, iter: indexmap::map::Keys<'a, Value, Value>,
} }
delegate_iterator!((Keys<'a>) => &'a Value); delegate_iterator!((Keys<'a>) => &'a Value);
/// Iterator of the keys of a `serde_yaml::Mapping`. /// Iterator of the keys of a `saphyr_serde::Mapping`.
pub struct IntoKeys { pub struct IntoKeys {
iter: indexmap::map::IntoKeys<Value, Value>, iter: indexmap::map::IntoKeys<Value, Value>,
} }
delegate_iterator!((IntoKeys) => Value); delegate_iterator!((IntoKeys) => Value);
/// Iterator of the values of a `&serde_yaml::Mapping`. /// Iterator of the values of a `&saphyr_serde::Mapping`.
pub struct Values<'a> { pub struct Values<'a> {
iter: indexmap::map::Values<'a, Value, Value>, iter: indexmap::map::Values<'a, Value, Value>,
} }
delegate_iterator!((Values<'a>) => &'a Value); delegate_iterator!((Values<'a>) => &'a Value);
/// Iterator of the values of a `&mut serde_yaml::Mapping`. /// Iterator of the values of a `&mut saphyr_serde::Mapping`.
pub struct ValuesMut<'a> { pub struct ValuesMut<'a> {
iter: indexmap::map::ValuesMut<'a, Value, Value>, iter: indexmap::map::ValuesMut<'a, Value, Value>,
} }
delegate_iterator!((ValuesMut<'a>) => &'a mut Value); delegate_iterator!((ValuesMut<'a>) => &'a mut Value);
/// Iterator of the values of a `serde_yaml::Mapping`. /// Iterator of the values of a `saphyr_serde::Mapping`.
pub struct IntoValues { pub struct IntoValues {
iter: indexmap::map::IntoValues<Value, Value>, iter: indexmap::map::IntoValues<Value, Value>,
} }

View file

@ -26,16 +26,16 @@ enum N {
} }
impl Number { impl Number {
/// Returns true if the `Number` is an integer between `i64::MIN` and /// Returns true if the `Number` is an integer between [`i64::MIN` and
/// `i64::MAX`. /// `i64::MAX`.
/// ///
/// For any Number on which `is_i64` returns true, `as_i64` is guaranteed to /// For any Number on which `is_i64` returns true, `as_i64` is guaranteed to
/// return the integer value. /// return the integer value.
/// ///
/// ``` /// ```
/// # fn main() -> serde_yaml::Result<()> { /// # fn main() -> saphyr_serde::Result<()> {
/// let big = i64::MAX as u64 + 10; /// let big = i64::MAX as u64 + 10;
/// let v: serde_yaml::Value = serde_yaml::from_str(r#" /// let v: saphyr_serde::Value = saphyr_serde::from_str(r#"
/// a: 64 /// a: 64
/// b: 9223372036854775817 /// b: 9223372036854775817
/// c: 256.0 /// c: 256.0
@ -55,7 +55,7 @@ impl Number {
#[allow(clippy::cast_sign_loss)] #[allow(clippy::cast_sign_loss)]
pub fn is_i64(&self) -> bool { pub fn is_i64(&self) -> bool {
match self.n { match self.n {
N::PosInt(v) => v <= i64::max_value() as u64, N::PosInt(v) => v <= i64::MAX as u64,
N::NegInt(_) => true, N::NegInt(_) => true,
N::Float(_) => false, N::Float(_) => false,
} }
@ -67,8 +67,8 @@ impl Number {
/// return the integer value. /// return the integer value.
/// ///
/// ``` /// ```
/// # fn main() -> serde_yaml::Result<()> { /// # fn main() -> saphyr_serde::Result<()> {
/// let v: serde_yaml::Value = serde_yaml::from_str(r#" /// let v: saphyr_serde::Value = saphyr_serde::from_str(r#"
/// a: 64 /// a: 64
/// b: -64 /// b: -64
/// c: 256.0 /// c: 256.0
@ -101,8 +101,8 @@ impl Number {
/// `is_u64` return false but this is not a guarantee in the future. /// `is_u64` return false but this is not a guarantee in the future.
/// ///
/// ``` /// ```
/// # fn main() -> serde_yaml::Result<()> { /// # fn main() -> saphyr_serde::Result<()> {
/// let v: serde_yaml::Value = serde_yaml::from_str(r#" /// let v: saphyr_serde::Value = saphyr_serde::from_str(r#"
/// a: 256.0 /// a: 256.0
/// b: 64 /// b: 64
/// c: -64 /// c: -64
@ -128,9 +128,9 @@ impl Number {
/// None otherwise. /// None otherwise.
/// ///
/// ``` /// ```
/// # fn main() -> serde_yaml::Result<()> { /// # fn main() -> saphyr_serde::Result<()> {
/// let big = i64::MAX as u64 + 10; /// let big = i64::MAX as u64 + 10;
/// let v: serde_yaml::Value = serde_yaml::from_str(r#" /// let v: saphyr_serde::Value = saphyr_serde::from_str(r#"
/// a: 64 /// a: 64
/// b: 9223372036854775817 /// b: 9223372036854775817
/// c: 256.0 /// c: 256.0
@ -146,7 +146,7 @@ impl Number {
pub fn as_i64(&self) -> Option<i64> { pub fn as_i64(&self) -> Option<i64> {
match self.n { match self.n {
N::PosInt(n) => { N::PosInt(n) => {
if n <= i64::max_value() as u64 { if n <= i64::MAX as u64 {
Some(n as i64) Some(n as i64)
} else { } else {
None None
@ -161,8 +161,8 @@ impl Number {
/// None otherwise. /// None otherwise.
/// ///
/// ``` /// ```
/// # fn main() -> serde_yaml::Result<()> { /// # fn main() -> saphyr_serde::Result<()> {
/// let v: serde_yaml::Value = serde_yaml::from_str(r#" /// let v: saphyr_serde::Value = saphyr_serde::from_str(r#"
/// a: 64 /// a: 64
/// b: -64 /// b: -64
/// c: 256.0 /// c: 256.0
@ -185,8 +185,8 @@ impl Number {
/// Represents the number as f64 if possible. Returns None otherwise. /// Represents the number as f64 if possible. Returns None otherwise.
/// ///
/// ``` /// ```
/// # fn main() -> serde_yaml::Result<()> { /// # fn main() -> saphyr_serde::Result<()> {
/// let v: serde_yaml::Value = serde_yaml::from_str(r#" /// let v: saphyr_serde::Value = saphyr_serde::from_str(r#"
/// a: 256.0 /// a: 256.0
/// b: 64 /// b: 64
/// c: -64 /// c: -64
@ -200,14 +200,14 @@ impl Number {
/// ``` /// ```
/// ///
/// ``` /// ```
/// # fn main() -> serde_yaml::Result<()> { /// # fn main() -> saphyr_serde::Result<()> {
/// let v: serde_yaml::Value = serde_yaml::from_str(".inf")?; /// let v: saphyr_serde::Value = saphyr_serde::from_str(".inf")?;
/// assert_eq!(v.as_f64(), Some(f64::INFINITY)); /// assert_eq!(v.as_f64(), Some(f64::INFINITY));
/// ///
/// let v: serde_yaml::Value = serde_yaml::from_str("-.inf")?; /// let v: saphyr_serde::Value = saphyr_serde::from_str("-.inf")?;
/// assert_eq!(v.as_f64(), Some(f64::NEG_INFINITY)); /// assert_eq!(v.as_f64(), Some(f64::NEG_INFINITY));
/// ///
/// let v: serde_yaml::Value = serde_yaml::from_str(".nan")?; /// let v: saphyr_serde::Value = saphyr_serde::from_str(".nan")?;
/// assert!(v.as_f64().unwrap().is_nan()); /// assert!(v.as_f64().unwrap().is_nan());
/// # Ok(()) /// # Ok(())
/// # } /// # }
@ -224,7 +224,7 @@ impl Number {
/// Returns true if this value is NaN and false otherwise. /// Returns true if this value is NaN and false otherwise.
/// ///
/// ``` /// ```
/// # use serde_yaml::Number; /// # use saphyr_serde::Number;
/// # /// #
/// assert!(!Number::from(256.0).is_nan()); /// assert!(!Number::from(256.0).is_nan());
/// ///
@ -248,7 +248,7 @@ impl Number {
/// false otherwise. /// false otherwise.
/// ///
/// ``` /// ```
/// # use serde_yaml::Number; /// # use saphyr_serde::Number;
/// # /// #
/// assert!(!Number::from(256.0).is_infinite()); /// assert!(!Number::from(256.0).is_infinite());
/// ///
@ -271,7 +271,7 @@ impl Number {
/// Returns true if this number is neither infinite nor NaN. /// Returns true if this number is neither infinite nor NaN.
/// ///
/// ``` /// ```
/// # use serde_yaml::Number; /// # use saphyr_serde::Number;
/// # /// #
/// assert!(Number::from(256.0).is_finite()); /// assert!(Number::from(256.0).is_finite());
/// ///

View file

@ -28,7 +28,7 @@ type Result<T, E = Error> = std::result::Result<T, E>;
/// ///
/// fn main() -> Result<()> { /// fn main() -> Result<()> {
/// let mut buffer = Vec::new(); /// let mut buffer = Vec::new();
/// let mut ser = serde_yaml::Serializer::new(&mut buffer); /// let mut ser = saphyr_serde::Serializer::new(&mut buffer);
/// ///
/// let mut object = BTreeMap::new(); /// let mut object = BTreeMap::new();
/// object.insert("k", 107); /// object.insert("k", 107);

View file

@ -27,7 +27,7 @@ impl From<bool> for Value {
/// # Examples /// # Examples
/// ///
/// ``` /// ```
/// use serde_yaml::Value; /// use saphyr_serde::Value;
/// ///
/// let b = false; /// let b = false;
/// let x: Value = b.into(); /// let x: Value = b.into();
@ -43,7 +43,7 @@ impl From<String> for Value {
/// # Examples /// # Examples
/// ///
/// ``` /// ```
/// use serde_yaml::Value; /// use saphyr_serde::Value;
/// ///
/// let s: String = "lorem".to_string(); /// let s: String = "lorem".to_string();
/// let x: Value = s.into(); /// let x: Value = s.into();
@ -59,7 +59,7 @@ impl<'a> From<&'a str> for Value {
/// # Examples /// # Examples
/// ///
/// ``` /// ```
/// use serde_yaml::Value; /// use saphyr_serde::Value;
/// ///
/// let s: &str = "lorem"; /// let s: &str = "lorem";
/// let x: Value = s.into(); /// let x: Value = s.into();
@ -77,7 +77,7 @@ impl<'a> From<Cow<'a, str>> for Value {
/// # Examples /// # Examples
/// ///
/// ``` /// ```
/// use serde_yaml::Value; /// use saphyr_serde::Value;
/// use std::borrow::Cow; /// use std::borrow::Cow;
/// ///
/// let s: Cow<str> = Cow::Borrowed("lorem"); /// let s: Cow<str> = Cow::Borrowed("lorem");
@ -85,7 +85,7 @@ impl<'a> From<Cow<'a, str>> for Value {
/// ``` /// ```
/// ///
/// ``` /// ```
/// use serde_yaml::Value; /// use saphyr_serde::Value;
/// use std::borrow::Cow; /// use std::borrow::Cow;
/// ///
/// let s: Cow<str> = Cow::Owned("lorem".to_string()); /// let s: Cow<str> = Cow::Owned("lorem".to_string());
@ -102,7 +102,7 @@ impl From<Mapping> for Value {
/// # Examples /// # Examples
/// ///
/// ``` /// ```
/// use serde_yaml::{Mapping, Value}; /// use saphyr_serde::{Mapping, Value};
/// ///
/// let mut m = Mapping::new(); /// let mut m = Mapping::new();
/// m.insert("Lorem".into(), "ipsum".into()); /// m.insert("Lorem".into(), "ipsum".into());
@ -119,7 +119,7 @@ impl<T: Into<Value>> From<Vec<T>> for Value {
/// # Examples /// # Examples
/// ///
/// ``` /// ```
/// use serde_yaml::Value; /// use saphyr_serde::Value;
/// ///
/// let v = vec!["lorem", "ipsum", "dolor"]; /// let v = vec!["lorem", "ipsum", "dolor"];
/// let x: Value = v.into(); /// let x: Value = v.into();
@ -135,7 +135,7 @@ impl<'a, T: Clone + Into<Value>> From<&'a [T]> for Value {
/// # Examples /// # Examples
/// ///
/// ``` /// ```
/// use serde_yaml::Value; /// use saphyr_serde::Value;
/// ///
/// let v: &[&str] = &["lorem", "ipsum", "dolor"]; /// let v: &[&str] = &["lorem", "ipsum", "dolor"];
/// let x: Value = v.into(); /// let x: Value = v.into();
@ -151,14 +151,14 @@ impl<T: Into<Value>> FromIterator<T> for Value {
/// # Examples /// # Examples
/// ///
/// ``` /// ```
/// use serde_yaml::Value; /// use saphyr_serde::Value;
/// ///
/// let v = std::iter::repeat(42).take(5); /// let v = std::iter::repeat(42).take(5);
/// let x: Value = v.collect(); /// let x: Value = v.collect();
/// ``` /// ```
/// ///
/// ``` /// ```
/// use serde_yaml::Value; /// use saphyr_serde::Value;
/// ///
/// let v: Vec<_> = vec!["lorem", "ipsum", "dolor"]; /// let v: Vec<_> = vec!["lorem", "ipsum", "dolor"];
/// let x: Value = v.into_iter().collect(); /// let x: Value = v.into_iter().collect();
@ -166,7 +166,7 @@ impl<T: Into<Value>> FromIterator<T> for Value {
/// ///
/// ``` /// ```
/// use std::iter::FromIterator; /// use std::iter::FromIterator;
/// use serde_yaml::Value; /// use saphyr_serde::Value;
/// ///
/// let x: Value = Value::from_iter(vec!["lorem", "ipsum", "dolor"]); /// let x: Value = Value::from_iter(vec!["lorem", "ipsum", "dolor"]);
/// ``` /// ```

View file

@ -3,11 +3,11 @@ use crate::{mapping, private, Mapping, Value};
use std::fmt::{self, Debug}; use std::fmt::{self, Debug};
use std::ops; use std::ops;
/// A type that can be used to index into a `serde_yaml::Value`. See the `get` /// A type that can be used to index into a `saphyr_serde::Value`. See the `get`
/// and `get_mut` methods of `Value`. /// and `get_mut` methods of `Value`.
/// ///
/// This trait is sealed and cannot be implemented for types outside of /// This trait is sealed and cannot be implemented for types outside of
/// `serde_yaml`. /// `saphyr_serde`.
pub trait Index: private::Sealed { pub trait Index: private::Sealed {
/// Return None if the key is not already in the sequence or object. /// Return None if the key is not already in the sequence or object.
#[doc(hidden)] #[doc(hidden)]
@ -29,14 +29,14 @@ impl Index for usize {
fn index_into<'v>(&self, v: &'v Value) -> Option<&'v Value> { fn index_into<'v>(&self, v: &'v Value) -> Option<&'v Value> {
match v.untag_ref() { match v.untag_ref() {
Value::Sequence(vec) => vec.get(*self), Value::Sequence(vec) => vec.get(*self),
Value::Mapping(vec) => vec.get(&Value::Number((*self).into())), Value::Mapping(vec) => vec.get(Value::Number((*self).into())),
_ => None, _ => None,
} }
} }
fn index_into_mut<'v>(&self, v: &'v mut Value) -> Option<&'v mut Value> { fn index_into_mut<'v>(&self, v: &'v mut Value) -> Option<&'v mut Value> {
match v.untag_mut() { match v.untag_mut() {
Value::Sequence(vec) => vec.get_mut(*self), Value::Sequence(vec) => vec.get_mut(*self),
Value::Mapping(vec) => vec.get_mut(&Value::Number((*self).into())), Value::Mapping(vec) => vec.get_mut(Value::Number((*self).into())),
_ => None, _ => None,
} }
} }
@ -202,7 +202,7 @@ where
{ {
type Output = Value; type Output = Value;
/// Index into a `serde_yaml::Value` using the syntax `value[0]` or /// Index into a `saphyr_serde::Value` using the syntax `value[0]` or
/// `value["k"]`. /// `value["k"]`.
/// ///
/// Returns `Value::Null` if the type of `self` does not match the type of /// Returns `Value::Null` if the type of `self` does not match the type of
@ -216,16 +216,16 @@ where
/// # Examples /// # Examples
/// ///
/// ``` /// ```
/// # use serde_yaml::Value; /// # use saphyr_serde::Value;
/// # /// #
/// # fn main() -> serde_yaml::Result<()> { /// # fn main() -> saphyr_serde::Result<()> {
/// let data: serde_yaml::Value = serde_yaml::from_str(r#"{ x: { y: [z, zz] } }"#)?; /// let data: saphyr_serde::Value = saphyr_serde::from_str(r#"{ x: { y: [z, zz] } }"#)?;
/// ///
/// assert_eq!(data["x"]["y"], serde_yaml::from_str::<Value>(r#"["z", "zz"]"#).unwrap()); /// assert_eq!(data["x"]["y"], saphyr_serde::from_str::<Value>(r#"["z", "zz"]"#).unwrap());
/// assert_eq!(data["x"]["y"][0], serde_yaml::from_str::<Value>(r#""z""#).unwrap()); /// assert_eq!(data["x"]["y"][0], saphyr_serde::from_str::<Value>(r#""z""#).unwrap());
/// ///
/// assert_eq!(data["a"], serde_yaml::from_str::<Value>(r#"null"#).unwrap()); // returns null for undefined values /// assert_eq!(data["a"], saphyr_serde::from_str::<Value>(r#"null"#).unwrap()); // returns null for undefined values
/// assert_eq!(data["a"]["b"], serde_yaml::from_str::<Value>(r#"null"#).unwrap()); // does not panic /// assert_eq!(data["a"]["b"], saphyr_serde::from_str::<Value>(r#"null"#).unwrap()); // does not panic
/// # Ok(()) /// # Ok(())
/// # } /// # }
/// ``` /// ```
@ -239,7 +239,7 @@ impl<I> ops::IndexMut<I> for Value
where where
I: Index, I: Index,
{ {
/// Write into a `serde_yaml::Value` using the syntax `value[0] = ...` or /// Write into a `saphyr_serde::Value` using the syntax `value[0] = ...` or
/// `value["k"] = ...`. /// `value["k"] = ...`.
/// ///
/// If the index is a number, the value must be a sequence of length bigger /// If the index is a number, the value must be a sequence of length bigger
@ -254,20 +254,20 @@ where
/// # Examples /// # Examples
/// ///
/// ``` /// ```
/// # fn main() -> serde_yaml::Result<()> { /// # fn main() -> saphyr_serde::Result<()> {
/// let mut data: serde_yaml::Value = serde_yaml::from_str(r#"{x: 0}"#)?; /// let mut data: saphyr_serde::Value = saphyr_serde::from_str(r#"{x: 0}"#)?;
/// ///
/// // replace an existing key /// // replace an existing key
/// data["x"] = serde_yaml::from_str(r#"1"#)?; /// data["x"] = saphyr_serde::from_str(r#"1"#)?;
/// ///
/// // insert a new key /// // insert a new key
/// data["y"] = serde_yaml::from_str(r#"[false, false, false]"#)?; /// data["y"] = saphyr_serde::from_str(r#"[false, false, false]"#)?;
/// ///
/// // replace a value in a sequence /// // replace a value in a sequence
/// data["y"][0] = serde_yaml::from_str(r#"true"#)?; /// data["y"][0] = saphyr_serde::from_str(r#"true"#)?;
/// ///
/// // inserted a deeply nested key /// // inserted a deeply nested key
/// data["a"]["b"]["c"]["d"] = serde_yaml::from_str(r#"true"#)?; /// data["a"]["b"]["c"]["d"] = saphyr_serde::from_str(r#"true"#)?;
/// ///
/// println!("{:?}", data); /// println!("{:?}", data);
/// # Ok(()) /// # Ok(())

View file

@ -33,10 +33,10 @@ pub enum Value {
/// Represents a YAML string. /// Represents a YAML string.
String(String), String(String),
/// Represents a YAML sequence in which the elements are /// Represents a YAML sequence in which the elements are
/// `serde_yaml::Value`. /// `saphyr_serde::Value`.
Sequence(Sequence), Sequence(Sequence),
/// Represents a YAML mapping in which the keys and values are both /// Represents a YAML mapping in which the keys and values are both
/// `serde_yaml::Value`. /// `saphyr_serde::Value`.
Mapping(Mapping), Mapping(Mapping),
/// A representation of YAML's `!Tag` syntax, used for enums. /// A representation of YAML's `!Tag` syntax, used for enums.
Tagged(Box<TaggedValue>), Tagged(Box<TaggedValue>),
@ -49,9 +49,8 @@ pub enum Value {
/// # Examples /// # Examples
/// ///
/// ``` /// ```
/// # use serde_derive::Deserialize;
/// use serde::Deserialize; /// use serde::Deserialize;
/// use serde_yaml::Value; /// use saphyr_serde::Value;
/// ///
/// #[derive(Deserialize)] /// #[derive(Deserialize)]
/// struct Settings { /// struct Settings {
@ -60,9 +59,9 @@ pub enum Value {
/// extras: Value, /// extras: Value,
/// } /// }
/// ///
/// # fn try_main() -> Result<(), serde_yaml::Error> { /// # fn try_main() -> Result<(), saphyr_serde::Error> {
/// let data = r#" { "level": 42 } "#; /// let data = r#" { "level": 42 } "#;
/// let s: Settings = serde_yaml::from_str(data)?; /// let s: Settings = saphyr_serde::from_str(data)?;
/// ///
/// assert_eq!(s.level, 42); /// assert_eq!(s.level, 42);
/// assert_eq!(s.extras, Value::Null); /// assert_eq!(s.extras, Value::Null);
@ -78,18 +77,18 @@ impl Default for Value {
} }
} }
/// A YAML sequence in which the elements are `serde_yaml::Value`. /// A YAML sequence in which the elements are `saphyr_serde::Value`.
pub type Sequence = Vec<Value>; pub type Sequence = Vec<Value>;
/// Convert a `T` into `serde_yaml::Value` which is an enum that can represent /// Convert a `T` into `saphyr_serde::Value` which is an enum that can represent
/// any valid YAML data. /// any valid YAML data.
/// ///
/// This conversion can fail if `T`'s implementation of `Serialize` decides to /// This conversion can fail if `T`'s implementation of `Serialize` decides to
/// return an error. /// return an error.
/// ///
/// ``` /// ```
/// # use serde_yaml::Value; /// # use saphyr_serde::Value;
/// let val = serde_yaml::to_value("s").unwrap(); /// let val = saphyr_serde::to_value("s").unwrap();
/// assert_eq!(val, Value::String("s".to_owned())); /// assert_eq!(val, Value::String("s".to_owned()));
/// ``` /// ```
pub fn to_value<T>(value: T) -> Result<Value, Error> pub fn to_value<T>(value: T) -> Result<Value, Error>
@ -99,7 +98,7 @@ where
value.serialize(Serializer) value.serialize(Serializer)
} }
/// Interpret a `serde_yaml::Value` as an instance of type `T`. /// Interpret a `saphyr_serde::Value` as an instance of type `T`.
/// ///
/// This conversion can fail if the structure of the Value does not match the /// 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 /// structure expected by `T`, for example if `T` is a struct type but the Value
@ -110,9 +109,9 @@ where
/// type. /// type.
/// ///
/// ``` /// ```
/// # use serde_yaml::Value; /// # use saphyr_serde::Value;
/// let val = Value::String("foo".to_owned()); /// let val = Value::String("foo".to_owned());
/// let s: String = serde_yaml::from_value(val).unwrap(); /// let s: String = saphyr_serde::from_value(val).unwrap();
/// assert_eq!("foo", s); /// assert_eq!("foo", s);
/// ``` /// ```
pub fn from_value<T>(value: Value) -> Result<T, Error> pub fn from_value<T>(value: Value) -> Result<T, Error>
@ -133,14 +132,14 @@ impl Value {
/// or the given index is not within the bounds of the sequence. /// or the given index is not within the bounds of the sequence.
/// ///
/// ``` /// ```
/// # fn main() -> serde_yaml::Result<()> { /// # fn main() -> saphyr_serde::Result<()> {
/// use serde_yaml::Value; /// use saphyr_serde::Value;
/// ///
/// let object: Value = serde_yaml::from_str(r#"{ A: 65, B: 66, C: 67 }"#)?; /// let object: Value = saphyr_serde::from_str(r#"{ A: 65, B: 66, C: 67 }"#)?;
/// let x = object.get("A").unwrap(); /// let x = object.get("A").unwrap();
/// assert_eq!(x, 65); /// assert_eq!(x, 65);
/// ///
/// let sequence: Value = serde_yaml::from_str(r#"[ "A", "B", "C" ]"#)?; /// let sequence: Value = saphyr_serde::from_str(r#"[ "A", "B", "C" ]"#)?;
/// let x = sequence.get(2).unwrap(); /// let x = sequence.get(2).unwrap();
/// assert_eq!(x, &Value::String("C".into())); /// assert_eq!(x, &Value::String("C".into()));
/// ///
@ -154,10 +153,10 @@ impl Value {
/// `None`. /// `None`.
/// ///
/// ``` /// ```
/// # use serde_yaml::Value; /// # use saphyr_serde::Value;
/// # /// #
/// # fn main() -> serde_yaml::Result<()> { /// # fn main() -> saphyr_serde::Result<()> {
/// let object: Value = serde_yaml::from_str(r#" /// let object: Value = saphyr_serde::from_str(r#"
/// A: [a, á, à] /// A: [a, á, à]
/// B: [b, b́] /// B: [b, b́]
/// C: [c, ć, ć̣, ḉ] /// C: [c, ć, ć̣, ḉ]
@ -195,14 +194,14 @@ impl Value {
/// to return `Some(())`. /// to return `Some(())`.
/// ///
/// ``` /// ```
/// # use serde_yaml::Value; /// # use saphyr_serde::Value;
/// let v: Value = serde_yaml::from_str("null").unwrap(); /// let v: Value = saphyr_serde::from_str("null").unwrap();
/// assert!(v.is_null()); /// assert!(v.is_null());
/// ``` /// ```
/// ///
/// ``` /// ```
/// # use serde_yaml::Value; /// # use saphyr_serde::Value;
/// let v: Value = serde_yaml::from_str("false").unwrap(); /// let v: Value = saphyr_serde::from_str("false").unwrap();
/// assert!(!v.is_null()); /// assert!(!v.is_null());
/// ``` /// ```
pub fn is_null(&self) -> bool { pub fn is_null(&self) -> bool {
@ -216,14 +215,14 @@ impl Value {
/// If the `Value` is a Null, returns (). Returns None otherwise. /// If the `Value` is a Null, returns (). Returns None otherwise.
/// ///
/// ``` /// ```
/// # use serde_yaml::Value; /// # use saphyr_serde::Value;
/// let v: Value = serde_yaml::from_str("null").unwrap(); /// let v: Value = saphyr_serde::from_str("null").unwrap();
/// assert_eq!(v.as_null(), Some(())); /// assert_eq!(v.as_null(), Some(()));
/// ``` /// ```
/// ///
/// ``` /// ```
/// # use serde_yaml::Value; /// # use saphyr_serde::Value;
/// let v: Value = serde_yaml::from_str("false").unwrap(); /// let v: Value = saphyr_serde::from_str("false").unwrap();
/// assert_eq!(v.as_null(), None); /// assert_eq!(v.as_null(), None);
/// ``` /// ```
pub fn as_null(&self) -> Option<()> { pub fn as_null(&self) -> Option<()> {
@ -239,14 +238,14 @@ impl Value {
/// guaranteed to return the boolean value. /// guaranteed to return the boolean value.
/// ///
/// ``` /// ```
/// # use serde_yaml::Value; /// # use saphyr_serde::Value;
/// let v: Value = serde_yaml::from_str("true").unwrap(); /// let v: Value = saphyr_serde::from_str("true").unwrap();
/// assert!(v.is_bool()); /// assert!(v.is_bool());
/// ``` /// ```
/// ///
/// ``` /// ```
/// # use serde_yaml::Value; /// # use saphyr_serde::Value;
/// let v: Value = serde_yaml::from_str("42").unwrap(); /// let v: Value = saphyr_serde::from_str("42").unwrap();
/// assert!(!v.is_bool()); /// assert!(!v.is_bool());
/// ``` /// ```
pub fn is_bool(&self) -> bool { pub fn is_bool(&self) -> bool {
@ -257,14 +256,14 @@ impl Value {
/// otherwise. /// otherwise.
/// ///
/// ``` /// ```
/// # use serde_yaml::Value; /// # use saphyr_serde::Value;
/// let v: Value = serde_yaml::from_str("true").unwrap(); /// let v: Value = saphyr_serde::from_str("true").unwrap();
/// assert_eq!(v.as_bool(), Some(true)); /// assert_eq!(v.as_bool(), Some(true));
/// ``` /// ```
/// ///
/// ``` /// ```
/// # use serde_yaml::Value; /// # use saphyr_serde::Value;
/// let v: Value = serde_yaml::from_str("42").unwrap(); /// let v: Value = saphyr_serde::from_str("42").unwrap();
/// assert_eq!(v.as_bool(), None); /// assert_eq!(v.as_bool(), None);
/// ``` /// ```
pub fn as_bool(&self) -> Option<bool> { pub fn as_bool(&self) -> Option<bool> {
@ -277,14 +276,14 @@ impl Value {
/// Returns true if the `Value` is a Number. Returns false otherwise. /// Returns true if the `Value` is a Number. Returns false otherwise.
/// ///
/// ``` /// ```
/// # use serde_yaml::Value; /// # use saphyr_serde::Value;
/// let v: Value = serde_yaml::from_str("5").unwrap(); /// let v: Value = saphyr_serde::from_str("5").unwrap();
/// assert!(v.is_number()); /// assert!(v.is_number());
/// ``` /// ```
/// ///
/// ``` /// ```
/// # use serde_yaml::Value; /// # use saphyr_serde::Value;
/// let v: Value = serde_yaml::from_str("true").unwrap(); /// let v: Value = saphyr_serde::from_str("true").unwrap();
/// assert!(!v.is_number()); /// assert!(!v.is_number());
/// ``` /// ```
pub fn is_number(&self) -> bool { pub fn is_number(&self) -> bool {
@ -301,14 +300,14 @@ impl Value {
/// return the integer value. /// return the integer value.
/// ///
/// ``` /// ```
/// # use serde_yaml::Value; /// # use saphyr_serde::Value;
/// let v: Value = serde_yaml::from_str("1337").unwrap(); /// let v: Value = saphyr_serde::from_str("1337").unwrap();
/// assert!(v.is_i64()); /// assert!(v.is_i64());
/// ``` /// ```
/// ///
/// ``` /// ```
/// # use serde_yaml::Value; /// # use saphyr_serde::Value;
/// let v: Value = serde_yaml::from_str("null").unwrap(); /// let v: Value = saphyr_serde::from_str("null").unwrap();
/// assert!(!v.is_i64()); /// assert!(!v.is_i64());
/// ``` /// ```
pub fn is_i64(&self) -> bool { pub fn is_i64(&self) -> bool {
@ -319,14 +318,14 @@ impl Value {
/// None otherwise. /// None otherwise.
/// ///
/// ``` /// ```
/// # use serde_yaml::Value; /// # use saphyr_serde::Value;
/// let v: Value = serde_yaml::from_str("1337").unwrap(); /// let v: Value = saphyr_serde::from_str("1337").unwrap();
/// assert_eq!(v.as_i64(), Some(1337)); /// assert_eq!(v.as_i64(), Some(1337));
/// ``` /// ```
/// ///
/// ``` /// ```
/// # use serde_yaml::Value; /// # use saphyr_serde::Value;
/// let v: Value = serde_yaml::from_str("false").unwrap(); /// let v: Value = saphyr_serde::from_str("false").unwrap();
/// assert_eq!(v.as_i64(), None); /// assert_eq!(v.as_i64(), None);
/// ``` /// ```
pub fn as_i64(&self) -> Option<i64> { pub fn as_i64(&self) -> Option<i64> {
@ -343,14 +342,14 @@ impl Value {
/// return the integer value. /// return the integer value.
/// ///
/// ``` /// ```
/// # use serde_yaml::Value; /// # use saphyr_serde::Value;
/// let v: Value = serde_yaml::from_str("1337").unwrap(); /// let v: Value = saphyr_serde::from_str("1337").unwrap();
/// assert!(v.is_u64()); /// assert!(v.is_u64());
/// ``` /// ```
/// ///
/// ``` /// ```
/// # use serde_yaml::Value; /// # use saphyr_serde::Value;
/// let v: Value = serde_yaml::from_str("null").unwrap(); /// let v: Value = saphyr_serde::from_str("null").unwrap();
/// assert!(!v.is_u64()); /// assert!(!v.is_u64());
/// ``` /// ```
pub fn is_u64(&self) -> bool { pub fn is_u64(&self) -> bool {
@ -361,14 +360,14 @@ impl Value {
/// None otherwise. /// None otherwise.
/// ///
/// ``` /// ```
/// # use serde_yaml::Value; /// # use saphyr_serde::Value;
/// let v: Value = serde_yaml::from_str("1337").unwrap(); /// let v: Value = saphyr_serde::from_str("1337").unwrap();
/// assert_eq!(v.as_u64(), Some(1337)); /// assert_eq!(v.as_u64(), Some(1337));
/// ``` /// ```
/// ///
/// ``` /// ```
/// # use serde_yaml::Value; /// # use saphyr_serde::Value;
/// let v: Value = serde_yaml::from_str("false").unwrap(); /// let v: Value = saphyr_serde::from_str("false").unwrap();
/// assert_eq!(v.as_u64(), None); /// assert_eq!(v.as_u64(), None);
/// ``` /// ```
pub fn as_u64(&self) -> Option<u64> { pub fn as_u64(&self) -> Option<u64> {
@ -387,14 +386,14 @@ impl Value {
/// `is_u64` return false but this is not a guarantee in the future. /// `is_u64` return false but this is not a guarantee in the future.
/// ///
/// ``` /// ```
/// # use serde_yaml::Value; /// # use saphyr_serde::Value;
/// let v: Value = serde_yaml::from_str("256.01").unwrap(); /// let v: Value = saphyr_serde::from_str("256.01").unwrap();
/// assert!(v.is_f64()); /// assert!(v.is_f64());
/// ``` /// ```
/// ///
/// ``` /// ```
/// # use serde_yaml::Value; /// # use saphyr_serde::Value;
/// let v: Value = serde_yaml::from_str("true").unwrap(); /// let v: Value = saphyr_serde::from_str("true").unwrap();
/// assert!(!v.is_f64()); /// assert!(!v.is_f64());
/// ``` /// ```
pub fn is_f64(&self) -> bool { pub fn is_f64(&self) -> bool {
@ -408,14 +407,14 @@ impl Value {
/// None otherwise. /// None otherwise.
/// ///
/// ``` /// ```
/// # use serde_yaml::Value; /// # use saphyr_serde::Value;
/// let v: Value = serde_yaml::from_str("13.37").unwrap(); /// let v: Value = saphyr_serde::from_str("13.37").unwrap();
/// assert_eq!(v.as_f64(), Some(13.37)); /// assert_eq!(v.as_f64(), Some(13.37));
/// ``` /// ```
/// ///
/// ``` /// ```
/// # use serde_yaml::Value; /// # use saphyr_serde::Value;
/// let v: Value = serde_yaml::from_str("false").unwrap(); /// let v: Value = saphyr_serde::from_str("false").unwrap();
/// assert_eq!(v.as_f64(), None); /// assert_eq!(v.as_f64(), None);
/// ``` /// ```
pub fn as_f64(&self) -> Option<f64> { pub fn as_f64(&self) -> Option<f64> {
@ -431,14 +430,14 @@ impl Value {
/// to return the string slice. /// to return the string slice.
/// ///
/// ``` /// ```
/// # use serde_yaml::Value; /// # use saphyr_serde::Value;
/// let v: Value = serde_yaml::from_str("'lorem ipsum'").unwrap(); /// let v: Value = saphyr_serde::from_str("'lorem ipsum'").unwrap();
/// assert!(v.is_string()); /// assert!(v.is_string());
/// ``` /// ```
/// ///
/// ``` /// ```
/// # use serde_yaml::Value; /// # use saphyr_serde::Value;
/// let v: Value = serde_yaml::from_str("42").unwrap(); /// let v: Value = saphyr_serde::from_str("42").unwrap();
/// assert!(!v.is_string()); /// assert!(!v.is_string());
/// ``` /// ```
pub fn is_string(&self) -> bool { pub fn is_string(&self) -> bool {
@ -449,14 +448,14 @@ impl Value {
/// otherwise. /// otherwise.
/// ///
/// ``` /// ```
/// # use serde_yaml::Value; /// # use saphyr_serde::Value;
/// let v: Value = serde_yaml::from_str("'lorem ipsum'").unwrap(); /// let v: Value = saphyr_serde::from_str("'lorem ipsum'").unwrap();
/// assert_eq!(v.as_str(), Some("lorem ipsum")); /// assert_eq!(v.as_str(), Some("lorem ipsum"));
/// ``` /// ```
/// ///
/// ``` /// ```
/// # use serde_yaml::Value; /// # use saphyr_serde::Value;
/// let v: Value = serde_yaml::from_str("false").unwrap(); /// let v: Value = saphyr_serde::from_str("false").unwrap();
/// assert_eq!(v.as_str(), None); /// assert_eq!(v.as_str(), None);
/// ``` /// ```
pub fn as_str(&self) -> Option<&str> { pub fn as_str(&self) -> Option<&str> {
@ -469,14 +468,14 @@ impl Value {
/// Returns true if the `Value` is a sequence. Returns false otherwise. /// Returns true if the `Value` is a sequence. Returns false otherwise.
/// ///
/// ``` /// ```
/// # use serde_yaml::Value; /// # use saphyr_serde::Value;
/// let v: Value = serde_yaml::from_str("[1, 2, 3]").unwrap(); /// let v: Value = saphyr_serde::from_str("[1, 2, 3]").unwrap();
/// assert!(v.is_sequence()); /// assert!(v.is_sequence());
/// ``` /// ```
/// ///
/// ``` /// ```
/// # use serde_yaml::Value; /// # use saphyr_serde::Value;
/// let v: Value = serde_yaml::from_str("true").unwrap(); /// let v: Value = saphyr_serde::from_str("true").unwrap();
/// assert!(!v.is_sequence()); /// assert!(!v.is_sequence());
/// ``` /// ```
pub fn is_sequence(&self) -> bool { pub fn is_sequence(&self) -> bool {
@ -487,14 +486,14 @@ impl Value {
/// Returns None otherwise. /// Returns None otherwise.
/// ///
/// ``` /// ```
/// # use serde_yaml::{Value, Number}; /// # use saphyr_serde::{Value, Number};
/// let v: Value = serde_yaml::from_str("[1, 2]").unwrap(); /// let v: Value = saphyr_serde::from_str("[1, 2]").unwrap();
/// assert_eq!(v.as_sequence(), Some(&vec![Value::Number(Number::from(1)), Value::Number(Number::from(2))])); /// assert_eq!(v.as_sequence(), Some(&vec![Value::Number(Number::from(1)), Value::Number(Number::from(2))]));
/// ``` /// ```
/// ///
/// ``` /// ```
/// # use serde_yaml::Value; /// # use saphyr_serde::Value;
/// let v: Value = serde_yaml::from_str("false").unwrap(); /// let v: Value = saphyr_serde::from_str("false").unwrap();
/// assert_eq!(v.as_sequence(), None); /// assert_eq!(v.as_sequence(), None);
/// ``` /// ```
pub fn as_sequence(&self) -> Option<&Sequence> { pub fn as_sequence(&self) -> Option<&Sequence> {
@ -508,16 +507,16 @@ impl Value {
/// possible. Returns None otherwise. /// possible. Returns None otherwise.
/// ///
/// ``` /// ```
/// # use serde_yaml::{Value, Number}; /// # use saphyr_serde::{Value, Number};
/// let mut v: Value = serde_yaml::from_str("[1]").unwrap(); /// let mut v: Value = saphyr_serde::from_str("[1]").unwrap();
/// let s = v.as_sequence_mut().unwrap(); /// let s = v.as_sequence_mut().unwrap();
/// s.push(Value::Number(Number::from(2))); /// s.push(Value::Number(Number::from(2)));
/// assert_eq!(s, &vec![Value::Number(Number::from(1)), Value::Number(Number::from(2))]); /// assert_eq!(s, &vec![Value::Number(Number::from(1)), Value::Number(Number::from(2))]);
/// ``` /// ```
/// ///
/// ``` /// ```
/// # use serde_yaml::Value; /// # use saphyr_serde::Value;
/// let mut v: Value = serde_yaml::from_str("false").unwrap(); /// let mut v: Value = saphyr_serde::from_str("false").unwrap();
/// assert_eq!(v.as_sequence_mut(), None); /// assert_eq!(v.as_sequence_mut(), None);
/// ``` /// ```
pub fn as_sequence_mut(&mut self) -> Option<&mut Sequence> { pub fn as_sequence_mut(&mut self) -> Option<&mut Sequence> {
@ -530,14 +529,14 @@ impl Value {
/// Returns true if the `Value` is a mapping. Returns false otherwise. /// Returns true if the `Value` is a mapping. Returns false otherwise.
/// ///
/// ``` /// ```
/// # use serde_yaml::Value; /// # use saphyr_serde::Value;
/// let v: Value = serde_yaml::from_str("a: 42").unwrap(); /// let v: Value = saphyr_serde::from_str("a: 42").unwrap();
/// assert!(v.is_mapping()); /// assert!(v.is_mapping());
/// ``` /// ```
/// ///
/// ``` /// ```
/// # use serde_yaml::Value; /// # use saphyr_serde::Value;
/// let v: Value = serde_yaml::from_str("true").unwrap(); /// let v: Value = saphyr_serde::from_str("true").unwrap();
/// assert!(!v.is_mapping()); /// assert!(!v.is_mapping());
/// ``` /// ```
pub fn is_mapping(&self) -> bool { pub fn is_mapping(&self) -> bool {
@ -548,8 +547,8 @@ impl Value {
/// Returns None otherwise. /// Returns None otherwise.
/// ///
/// ``` /// ```
/// # use serde_yaml::{Value, Mapping, Number}; /// # use saphyr_serde::{Value, Mapping, Number};
/// let v: Value = serde_yaml::from_str("a: 42").unwrap(); /// let v: Value = saphyr_serde::from_str("a: 42").unwrap();
/// ///
/// let mut expected = Mapping::new(); /// let mut expected = Mapping::new();
/// expected.insert(Value::String("a".into()),Value::Number(Number::from(42))); /// expected.insert(Value::String("a".into()),Value::Number(Number::from(42)));
@ -558,8 +557,8 @@ impl Value {
/// ``` /// ```
/// ///
/// ``` /// ```
/// # use serde_yaml::Value; /// # use saphyr_serde::Value;
/// let v: Value = serde_yaml::from_str("false").unwrap(); /// let v: Value = saphyr_serde::from_str("false").unwrap();
/// assert_eq!(v.as_mapping(), None); /// assert_eq!(v.as_mapping(), None);
/// ``` /// ```
pub fn as_mapping(&self) -> Option<&Mapping> { pub fn as_mapping(&self) -> Option<&Mapping> {
@ -573,8 +572,8 @@ impl Value {
/// Returns None otherwise. /// Returns None otherwise.
/// ///
/// ``` /// ```
/// # use serde_yaml::{Value, Mapping, Number}; /// # use saphyr_serde::{Value, Mapping, Number};
/// let mut v: Value = serde_yaml::from_str("a: 42").unwrap(); /// let mut v: Value = saphyr_serde::from_str("a: 42").unwrap();
/// let m = v.as_mapping_mut().unwrap(); /// let m = v.as_mapping_mut().unwrap();
/// m.insert(Value::String("b".into()), Value::Number(Number::from(21))); /// m.insert(Value::String("b".into()), Value::Number(Number::from(21)));
/// ///
@ -586,8 +585,8 @@ impl Value {
/// ``` /// ```
/// ///
/// ``` /// ```
/// # use serde_yaml::{Value, Mapping}; /// # use saphyr_serde::{Value, Mapping};
/// let mut v: Value = serde_yaml::from_str("false").unwrap(); /// let mut v: Value = saphyr_serde::from_str("false").unwrap();
/// assert_eq!(v.as_mapping_mut(), None); /// assert_eq!(v.as_mapping_mut(), None);
/// ``` /// ```
pub fn as_mapping_mut(&mut self) -> Option<&mut Mapping> { pub fn as_mapping_mut(&mut self) -> Option<&mut Mapping> {
@ -603,7 +602,7 @@ impl Value {
/// <https://yaml.org/type/merge.html>. /// <https://yaml.org/type/merge.html>.
/// ///
/// ``` /// ```
/// use serde_yaml::Value; /// use saphyr_serde::Value;
/// ///
/// let config = "\ /// let config = "\
/// tasks: /// tasks:
@ -617,7 +616,7 @@ impl Value {
/// args: start /// args: start
/// "; /// ";
/// ///
/// let mut value: Value = serde_yaml::from_str(config).unwrap(); /// let mut value: Value = saphyr_serde::from_str(config).unwrap();
/// value.apply_merge().unwrap(); /// value.apply_merge().unwrap();
/// ///
/// assert_eq!(value["tasks"]["start"]["command"], "webpack"); /// assert_eq!(value["tasks"]["start"]["command"], "webpack");

View file

@ -6,7 +6,7 @@ impl PartialEq<str> for Value {
/// # Examples /// # Examples
/// ///
/// ``` /// ```
/// # use serde_yaml::Value; /// # use saphyr_serde::Value;
/// assert!(Value::String("lorem".into()) == *"lorem"); /// assert!(Value::String("lorem".into()) == *"lorem");
/// ``` /// ```
fn eq(&self, other: &str) -> bool { fn eq(&self, other: &str) -> bool {
@ -20,7 +20,7 @@ impl<'a> PartialEq<&'a str> for Value {
/// # Examples /// # Examples
/// ///
/// ``` /// ```
/// # use serde_yaml::Value; /// # use saphyr_serde::Value;
/// assert!(Value::String("lorem".into()) == "lorem"); /// assert!(Value::String("lorem".into()) == "lorem");
/// ``` /// ```
fn eq(&self, other: &&str) -> bool { fn eq(&self, other: &&str) -> bool {
@ -34,7 +34,7 @@ impl PartialEq<String> for Value {
/// # Examples /// # Examples
/// ///
/// ``` /// ```
/// # use serde_yaml::Value; /// # use saphyr_serde::Value;
/// assert!(Value::String("lorem".into()) == "lorem".to_string()); /// assert!(Value::String("lorem".into()) == "lorem".to_string());
/// ``` /// ```
fn eq(&self, other: &String) -> bool { fn eq(&self, other: &String) -> bool {
@ -48,7 +48,7 @@ impl PartialEq<bool> for Value {
/// # Examples /// # Examples
/// ///
/// ``` /// ```
/// # use serde_yaml::Value; /// # use saphyr_serde::Value;
/// assert!(Value::Bool(true) == true); /// assert!(Value::Bool(true) == true);
/// ``` /// ```
fn eq(&self, other: &bool) -> bool { fn eq(&self, other: &bool) -> bool {

View file

@ -33,22 +33,22 @@ impl Serialize for Value {
/// Serializer whose output is a `Value`. /// Serializer whose output is a `Value`.
/// ///
/// This is the serializer that backs [`serde_yaml::to_value`][crate::to_value]. /// This is the serializer that backs [`saphyr_serde::to_value`][crate::to_value].
/// Unlike the main serde_yaml serializer which goes from some serializable /// Unlike the main saphyr_serde serializer which goes from some serializable
/// value of type `T` to YAML text, this one goes from `T` to /// value of type `T` to YAML text, this one goes from `T` to
/// `serde_yaml::Value`. /// `saphyr_serde::Value`.
/// ///
/// The `to_value` function is implementable as: /// The `to_value` function is implementable as:
/// ///
/// ``` /// ```
/// use serde::Serialize; /// use serde::Serialize;
/// use serde_yaml::{Error, Value}; /// use saphyr_serde::{Error, Value};
/// ///
/// pub fn to_value<T>(input: T) -> Result<Value, Error> /// pub fn to_value<T>(input: T) -> Result<Value, Error>
/// where /// where
/// T: Serialize, /// T: Serialize,
/// { /// {
/// input.serialize(serde_yaml::value::Serializer) /// input.serialize(saphyr_serde::value::Serializer)
/// } /// }
/// ``` /// ```
pub struct Serializer; pub struct Serializer;

View file

@ -24,7 +24,7 @@ pub struct Tag {
/// A `Tag` + `Value` representing a tagged YAML scalar, sequence, or mapping. /// A `Tag` + `Value` representing a tagged YAML scalar, sequence, or mapping.
/// ///
/// ``` /// ```
/// use serde_yaml::value::TaggedValue; /// use saphyr_serde::value::TaggedValue;
/// use std::collections::BTreeMap; /// use std::collections::BTreeMap;
/// ///
/// let yaml = " /// let yaml = "
@ -37,7 +37,7 @@ pub struct Tag {
/// k: v /// k: v
/// "; /// ";
/// ///
/// let data: BTreeMap<String, TaggedValue> = serde_yaml::from_str(yaml).unwrap(); /// let data: BTreeMap<String, TaggedValue> = saphyr_serde::from_str(yaml).unwrap();
/// assert!(data["scalar"].tag == "Thing"); /// assert!(data["scalar"].tag == "Thing");
/// assert!(data["sequence_flow"].tag == "Thing"); /// assert!(data["sequence_flow"].tag == "Thing");
/// assert!(data["sequence_block"].tag == "Thing"); /// assert!(data["sequence_block"].tag == "Thing");
@ -62,7 +62,7 @@ impl Tag {
/// have to be. The following are equivalent: /// have to be. The following are equivalent:
/// ///
/// ``` /// ```
/// use serde_yaml::value::Tag; /// use saphyr_serde::value::Tag;
/// ///
/// assert_eq!(Tag::new("!Thing"), Tag::new("Thing")); /// assert_eq!(Tag::new("!Thing"), Tag::new("Thing"));
/// ///

View file

@ -6,7 +6,6 @@
/// # Example /// # Example
/// ///
/// ``` /// ```
/// # use serde_derive::{Deserialize, Serialize};
/// use serde::{Deserialize, Serialize}; /// use serde::{Deserialize, Serialize};
/// ///
/// #[derive(Serialize, Deserialize, PartialEq, Debug)] /// #[derive(Serialize, Deserialize, PartialEq, Debug)]
@ -19,17 +18,16 @@
/// ///
/// #[derive(Serialize, Deserialize, PartialEq, Debug)] /// #[derive(Serialize, Deserialize, PartialEq, Debug)]
/// struct Struct { /// struct Struct {
/// #[serde(with = "serde_yaml::with::singleton_map")] /// #[serde(with = "saphyr_serde::with::singleton_map")]
/// w: Enum, /// w: Enum,
/// #[serde(with = "serde_yaml::with::singleton_map")] /// #[serde(with = "saphyr_serde::with::singleton_map")]
/// x: Enum, /// x: Enum,
/// #[serde(with = "serde_yaml::with::singleton_map")] /// #[serde(with = "saphyr_serde::with::singleton_map")]
/// y: Enum, /// y: Enum,
/// #[serde(with = "serde_yaml::with::singleton_map")] /// #[serde(with = "saphyr_serde::with::singleton_map")]
/// z: Enum, /// z: Enum,
/// } /// }
/// ///
/// fn main() {
/// let object = Struct { /// let object = Struct {
/// w: Enum::Unit, /// w: Enum::Unit,
/// x: Enum::Newtype(1), /// x: Enum::Newtype(1),
@ -37,12 +35,11 @@
/// z: Enum::Struct { value: 1 }, /// z: Enum::Struct { value: 1 },
/// }; /// };
/// ///
/// let yaml = serde_yaml::to_string(&object).unwrap(); /// let yaml = saphyr_serde::to_string(&object).unwrap();
/// print!("{}", yaml); /// print!("{}", yaml);
/// ///
/// let deserialized: Struct = serde_yaml::from_str(&yaml).unwrap(); /// let deserialized: Struct = saphyr_serde::from_str(&yaml).unwrap();
/// assert_eq!(object, deserialized); /// assert_eq!(object, deserialized);
/// }
/// ``` /// ```
/// ///
/// The representation using `singleton_map` on all the fields is: /// The representation using `singleton_map` on all the fields is:
@ -840,7 +837,6 @@ pub mod singleton_map {
/// # Example /// # Example
/// ///
/// ``` /// ```
/// # use serde_derive::{Deserialize, Serialize};
/// use serde::{Deserialize, Serialize}; /// use serde::{Deserialize, Serialize};
/// ///
/// #[derive(Serialize, Deserialize, PartialEq, Debug)] /// #[derive(Serialize, Deserialize, PartialEq, Debug)]
@ -858,11 +854,10 @@ pub mod singleton_map {
/// struct Outer { /// struct Outer {
/// tagged_style: Inner, /// tagged_style: Inner,
/// ///
/// #[serde(with = "serde_yaml::with::singleton_map_recursive")] /// #[serde(with = "saphyr_serde::with::singleton_map_recursive")]
/// singleton_map_style: Inner, /// singleton_map_style: Inner,
/// } /// }
/// ///
/// fn main() {
/// let object = Outer { /// let object = Outer {
/// tagged_style: Inner { /// tagged_style: Inner {
/// a: Enum::Int(0), /// a: Enum::Int(0),
@ -874,12 +869,11 @@ pub mod singleton_map {
/// }, /// },
/// }; /// };
/// ///
/// let yaml = serde_yaml::to_string(&object).unwrap(); /// let yaml = saphyr_serde::to_string(&object).unwrap();
/// print!("{}", yaml); /// print!("{}", yaml);
/// ///
/// let deserialized: Outer = serde_yaml::from_str(&yaml).unwrap(); /// let deserialized: Outer = saphyr_serde::from_str(&yaml).unwrap();
/// assert_eq!(object, deserialized); /// assert_eq!(object, deserialized);
/// }
/// ``` /// ```
/// ///
/// The serialized output is: /// The serialized output is:
@ -900,7 +894,6 @@ pub mod singleton_map {
/// call, without `serde(with = …)`, as follows. /// call, without `serde(with = …)`, as follows.
/// ///
/// ``` /// ```
/// # use serde_derive::{Deserialize, Serialize};
/// # use serde::{Deserialize, Serialize}; /// # use serde::{Deserialize, Serialize};
/// # /// #
/// # #[derive(Serialize, Deserialize, PartialEq, Debug)] /// # #[derive(Serialize, Deserialize, PartialEq, Debug)]
@ -923,12 +916,12 @@ pub mod singleton_map {
/// }; /// };
/// ///
/// let mut buf = Vec::new(); /// let mut buf = Vec::new();
/// let mut serializer = serde_yaml::Serializer::new(&mut buf); /// let mut serializer = saphyr_serde::Serializer::new(&mut buf);
/// serde_yaml::with::singleton_map_recursive::serialize(&object, &mut serializer).unwrap(); /// saphyr_serde::with::singleton_map_recursive::serialize(&object, &mut serializer).unwrap();
/// io::stdout().write_all(&buf).unwrap(); /// io::stdout().write_all(&buf).unwrap();
/// ///
/// let deserializer = serde_yaml::Deserializer::from_slice(&buf); /// let deserializer = saphyr_serde::Deserializer::from_slice(&buf);
/// let deserialized: Inner = serde_yaml::with::singleton_map_recursive::deserialize(deserializer).unwrap(); /// let deserialized: Inner = saphyr_serde::with::singleton_map_recursive::deserialize(deserializer).unwrap();
/// assert_eq!(object, deserialized); /// assert_eq!(object, deserialized);
/// } /// }
/// ``` /// ```

View file

@ -7,8 +7,8 @@
)] )]
use indoc::indoc; use indoc::indoc;
use serde_derive::Deserialize; use saphyr_serde::{Deserializer, Number, Value};
use serde_yaml::{Deserializer, Number, Value}; use serde::Deserialize;
use std::collections::BTreeMap; use std::collections::BTreeMap;
use std::fmt::Debug; use std::fmt::Debug;
@ -16,17 +16,17 @@ fn test_de<T>(yaml: &str, expected: &T)
where where
T: serde::de::DeserializeOwned + PartialEq + Debug, T: serde::de::DeserializeOwned + PartialEq + Debug,
{ {
let deserialized: T = serde_yaml::from_str(yaml).unwrap(); let deserialized: T = saphyr_serde::from_str(yaml).unwrap();
assert_eq!(*expected, deserialized); assert_eq!(*expected, deserialized);
let value: Value = serde_yaml::from_str(yaml).unwrap(); let value: Value = saphyr_serde::from_str(yaml).unwrap();
let deserialized = T::deserialize(&value).unwrap(); let deserialized = T::deserialize(&value).unwrap();
assert_eq!(*expected, deserialized); assert_eq!(*expected, deserialized);
let deserialized: T = serde_yaml::from_value(value).unwrap(); let deserialized: T = saphyr_serde::from_value(value).unwrap();
assert_eq!(*expected, deserialized); assert_eq!(*expected, deserialized);
serde_yaml::from_str::<serde::de::IgnoredAny>(yaml).unwrap(); saphyr_serde::from_str::<serde::de::IgnoredAny>(yaml).unwrap();
let mut deserializer = Deserializer::from_str(yaml); let mut deserializer = Deserializer::from_str(yaml);
let document = deserializer.next().unwrap(); let document = deserializer.next().unwrap();
@ -39,11 +39,11 @@ fn test_de_no_value<'de, T>(yaml: &'de str, expected: &T)
where where
T: serde::de::Deserialize<'de> + PartialEq + Debug, T: serde::de::Deserialize<'de> + PartialEq + Debug,
{ {
let deserialized: T = serde_yaml::from_str(yaml).unwrap(); let deserialized: T = saphyr_serde::from_str(yaml).unwrap();
assert_eq!(*expected, deserialized); assert_eq!(*expected, deserialized);
serde_yaml::from_str::<serde_yaml::Value>(yaml).unwrap(); saphyr_serde::from_str::<saphyr_serde::Value>(yaml).unwrap();
serde_yaml::from_str::<serde::de::IgnoredAny>(yaml).unwrap(); saphyr_serde::from_str::<serde::de::IgnoredAny>(yaml).unwrap();
} }
fn test_de_seed<'de, T, S>(yaml: &'de str, seed: S, expected: &T) fn test_de_seed<'de, T, S>(yaml: &'de str, seed: S, expected: &T)
@ -54,8 +54,8 @@ where
let deserialized: T = seed.deserialize(Deserializer::from_str(yaml)).unwrap(); let deserialized: T = seed.deserialize(Deserializer::from_str(yaml)).unwrap();
assert_eq!(*expected, deserialized); assert_eq!(*expected, deserialized);
serde_yaml::from_str::<serde_yaml::Value>(yaml).unwrap(); saphyr_serde::from_str::<saphyr_serde::Value>(yaml).unwrap();
serde_yaml::from_str::<serde::de::IgnoredAny>(yaml).unwrap(); saphyr_serde::from_str::<serde::de::IgnoredAny>(yaml).unwrap();
} }
#[test] #[test]
@ -282,12 +282,12 @@ fn test_i128_big() {
let yaml = indoc! {" let yaml = indoc! {"
-9223372036854775809 -9223372036854775809
"}; "};
assert_eq!(expected, serde_yaml::from_str::<i128>(yaml).unwrap()); assert_eq!(expected, saphyr_serde::from_str::<i128>(yaml).unwrap());
let octal = indoc! {" let octal = indoc! {"
-0o1000000000000000000001 -0o1000000000000000000001
"}; "};
assert_eq!(expected, serde_yaml::from_str::<i128>(octal).unwrap()); assert_eq!(expected, saphyr_serde::from_str::<i128>(octal).unwrap());
} }
#[test] #[test]
@ -296,12 +296,12 @@ fn test_u128_big() {
let yaml = indoc! {" let yaml = indoc! {"
18446744073709551616 18446744073709551616
"}; "};
assert_eq!(expected, serde_yaml::from_str::<u128>(yaml).unwrap()); assert_eq!(expected, saphyr_serde::from_str::<u128>(yaml).unwrap());
let octal = indoc! {" let octal = indoc! {"
0o2000000000000000000000 0o2000000000000000000000
"}; "};
assert_eq!(expected, serde_yaml::from_str::<u128>(octal).unwrap()); assert_eq!(expected, saphyr_serde::from_str::<u128>(octal).unwrap());
} }
#[test] #[test]
@ -326,7 +326,7 @@ fn test_number_alias_as_string() {
fn test_de_mapping() { fn test_de_mapping() {
#[derive(Debug, Deserialize, PartialEq)] #[derive(Debug, Deserialize, PartialEq)]
struct Data { struct Data {
pub substructure: serde_yaml::Mapping, pub substructure: saphyr_serde::Mapping,
} }
let yaml = indoc! {" let yaml = indoc! {"
substructure: substructure:
@ -335,15 +335,15 @@ fn test_de_mapping() {
"}; "};
let mut expected = Data { let mut expected = Data {
substructure: serde_yaml::Mapping::new(), substructure: saphyr_serde::Mapping::new(),
}; };
expected.substructure.insert( expected.substructure.insert(
serde_yaml::Value::String("a".to_owned()), saphyr_serde::Value::String("a".to_owned()),
serde_yaml::Value::String("foo".to_owned()), saphyr_serde::Value::String("foo".to_owned()),
); );
expected.substructure.insert( expected.substructure.insert(
serde_yaml::Value::String("b".to_owned()), saphyr_serde::Value::String("b".to_owned()),
serde_yaml::Value::String("bar".to_owned()), saphyr_serde::Value::String("bar".to_owned()),
); );
test_de(yaml, &expected); test_de(yaml, &expected);
@ -399,7 +399,7 @@ fn test_bomb() {
expected: "string".to_owned(), expected: "string".to_owned(),
}; };
assert_eq!(expected, serde_yaml::from_str::<Data>(yaml).unwrap()); assert_eq!(expected, saphyr_serde::from_str::<Data>(yaml).unwrap());
} }
#[test] #[test]
@ -429,7 +429,7 @@ fn test_numbers() {
("0.1", "0.1"), ("0.1", "0.1"),
]; ];
for &(yaml, expected) in &cases { for &(yaml, expected) in &cases {
let value = serde_yaml::from_str::<Value>(yaml).unwrap(); let value = saphyr_serde::from_str::<Value>(yaml).unwrap();
match value { match value {
Value::Number(number) => assert_eq!(number.to_string(), expected), Value::Number(number) => assert_eq!(number.to_string(), expected),
_ => panic!("expected number. input={:?}, result={:?}", yaml, value), _ => panic!("expected number. input={:?}, result={:?}", yaml, value),
@ -442,7 +442,7 @@ fn test_numbers() {
"-0x+1", "-0x-1", "++0x1", "+-0x1", "-+0x1", "--0x1", "-0x+1", "-0x-1", "++0x1", "+-0x1", "-+0x1", "--0x1",
]; ];
for yaml in &cases { for yaml in &cases {
let value = serde_yaml::from_str::<Value>(yaml).unwrap(); let value = saphyr_serde::from_str::<Value>(yaml).unwrap();
match value { match value {
Value::String(string) => assert_eq!(string, *yaml), Value::String(string) => assert_eq!(string, *yaml),
_ => panic!("expected string. input={:?}, result={:?}", yaml, value), _ => panic!("expected string. input={:?}, result={:?}", yaml, value),
@ -453,10 +453,10 @@ fn test_numbers() {
#[test] #[test]
fn test_nan() { fn test_nan() {
// There is no negative NaN in YAML. // There is no negative NaN in YAML.
assert!(serde_yaml::from_str::<f32>(".nan") assert!(saphyr_serde::from_str::<f32>(".nan")
.unwrap() .unwrap()
.is_sign_positive()); .is_sign_positive());
assert!(serde_yaml::from_str::<f64>(".nan") assert!(saphyr_serde::from_str::<f64>(".nan")
.unwrap() .unwrap()
.is_sign_positive()); .is_sign_positive());
} }
@ -557,23 +557,23 @@ fn test_no_required_fields() {
for document in ["", "# comment\n"] { for document in ["", "# comment\n"] {
let expected = NoRequiredFields { optional: None }; let expected = NoRequiredFields { optional: None };
let deserialized: NoRequiredFields = serde_yaml::from_str(document).unwrap(); let deserialized: NoRequiredFields = saphyr_serde::from_str(document).unwrap();
assert_eq!(expected, deserialized); assert_eq!(expected, deserialized);
let expected = Vec::<String>::new(); let expected = Vec::<String>::new();
let deserialized: Vec<String> = serde_yaml::from_str(document).unwrap(); let deserialized: Vec<String> = saphyr_serde::from_str(document).unwrap();
assert_eq!(expected, deserialized); assert_eq!(expected, deserialized);
let expected = BTreeMap::new(); let expected = BTreeMap::new();
let deserialized: BTreeMap<char, usize> = serde_yaml::from_str(document).unwrap(); let deserialized: BTreeMap<char, usize> = saphyr_serde::from_str(document).unwrap();
assert_eq!(expected, deserialized); assert_eq!(expected, deserialized);
let expected = None; let expected = None;
let deserialized: Option<String> = serde_yaml::from_str(document).unwrap(); let deserialized: Option<String> = saphyr_serde::from_str(document).unwrap();
assert_eq!(expected, deserialized); assert_eq!(expected, deserialized);
let expected = Value::Null; let expected = Value::Null;
let deserialized: Value = serde_yaml::from_str(document).unwrap(); let deserialized: Value = saphyr_serde::from_str(document).unwrap();
assert_eq!(expected, deserialized); assert_eq!(expected, deserialized);
} }
} }
@ -587,12 +587,12 @@ fn test_empty_scalar() {
let yaml = "thing:\n"; let yaml = "thing:\n";
let expected = Struct { let expected = Struct {
thing: serde_yaml::Sequence::new(), thing: saphyr_serde::Sequence::new(),
}; };
test_de(yaml, &expected); test_de(yaml, &expected);
let expected = Struct { let expected = Struct {
thing: serde_yaml::Mapping::new(), thing: saphyr_serde::Mapping::new(),
}; };
test_de(yaml, &expected); test_de(yaml, &expected);
} }

View file

@ -1,12 +1,11 @@
#![allow(clippy::zero_sized_map_values)] #![allow(clippy::zero_sized_map_values)]
use indoc::indoc; use indoc::indoc;
use serde::de::Deserialize; use saphyr_serde::value::{Tag, TaggedValue};
use saphyr_serde::{Deserializer, Value};
#[cfg(not(miri))] #[cfg(not(miri))]
use serde::de::{SeqAccess, Visitor}; use serde::de::{SeqAccess, Visitor};
use serde_derive::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use serde_yaml::value::{Tag, TaggedValue};
use serde_yaml::{Deserializer, Value};
#[cfg(not(miri))] #[cfg(not(miri))]
use std::collections::BTreeMap; use std::collections::BTreeMap;
#[cfg(not(miri))] #[cfg(not(miri))]
@ -17,7 +16,7 @@ fn test_error<'de, T>(yaml: &'de str, expected: &str)
where where
T: Deserialize<'de> + Debug, T: Deserialize<'de> + Debug,
{ {
let result = serde_yaml::from_str::<T>(yaml); let result = saphyr_serde::from_str::<T>(yaml);
assert_eq!(expected, result.unwrap_err().to_string()); assert_eq!(expected, result.unwrap_err().to_string());
let mut deserializer = Deserializer::from_str(yaml); let mut deserializer = Deserializer::from_str(yaml);
@ -188,15 +187,15 @@ fn test_serialize_nested_enum() {
let expected = "serializing nested enums in YAML is not supported yet"; let expected = "serializing nested enums in YAML is not supported yet";
let e = Outer::Inner(Inner::Newtype(0)); let e = Outer::Inner(Inner::Newtype(0));
let error = serde_yaml::to_string(&e).unwrap_err(); let error = saphyr_serde::to_string(&e).unwrap_err();
assert_eq!(error.to_string(), expected); assert_eq!(error.to_string(), expected);
let e = Outer::Inner(Inner::Tuple(0, 0)); let e = Outer::Inner(Inner::Tuple(0, 0));
let error = serde_yaml::to_string(&e).unwrap_err(); let error = saphyr_serde::to_string(&e).unwrap_err();
assert_eq!(error.to_string(), expected); assert_eq!(error.to_string(), expected);
let e = Outer::Inner(Inner::Struct { x: 0 }); let e = Outer::Inner(Inner::Struct { x: 0 });
let error = serde_yaml::to_string(&e).unwrap_err(); let error = saphyr_serde::to_string(&e).unwrap_err();
assert_eq!(error.to_string(), expected); assert_eq!(error.to_string(), expected);
let e = Value::Tagged(Box::new(TaggedValue { let e = Value::Tagged(Box::new(TaggedValue {
@ -206,7 +205,7 @@ fn test_serialize_nested_enum() {
value: Value::Null, value: Value::Null,
})), })),
})); }));
let error = serde_yaml::to_string(&e).unwrap_err(); let error = saphyr_serde::to_string(&e).unwrap_err();
assert_eq!(error.to_string(), expected); assert_eq!(error.to_string(), expected);
} }

View file

@ -6,9 +6,9 @@
)] )]
use indoc::indoc; use indoc::indoc;
use saphyr_serde::{Mapping, Number, Value};
use serde::ser::SerializeMap; use serde::ser::SerializeMap;
use serde_derive::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use serde_yaml::{Mapping, Number, Value};
use std::collections::BTreeMap; use std::collections::BTreeMap;
use std::fmt::Debug; use std::fmt::Debug;
use std::iter; use std::iter;
@ -17,24 +17,24 @@ fn test_serde<T>(thing: &T, yaml: &str)
where where
T: serde::Serialize + serde::de::DeserializeOwned + PartialEq + Debug, T: serde::Serialize + serde::de::DeserializeOwned + PartialEq + Debug,
{ {
let serialized = serde_yaml::to_string(&thing).unwrap(); let serialized = saphyr_serde::to_string(&thing).unwrap();
assert_eq!(yaml, serialized); assert_eq!(yaml, serialized);
let value = serde_yaml::to_value(thing).unwrap(); let value = saphyr_serde::to_value(thing).unwrap();
let serialized = serde_yaml::to_string(&value).unwrap(); let serialized = saphyr_serde::to_string(&value).unwrap();
assert_eq!(yaml, serialized); assert_eq!(yaml, serialized);
let deserialized: T = serde_yaml::from_str(yaml).unwrap(); let deserialized: T = saphyr_serde::from_str(yaml).unwrap();
assert_eq!(*thing, deserialized); assert_eq!(*thing, deserialized);
let value: Value = serde_yaml::from_str(yaml).unwrap(); let value: Value = saphyr_serde::from_str(yaml).unwrap();
let deserialized = T::deserialize(&value).unwrap(); let deserialized = T::deserialize(&value).unwrap();
assert_eq!(*thing, deserialized); assert_eq!(*thing, deserialized);
let deserialized: T = serde_yaml::from_value(value).unwrap(); let deserialized: T = saphyr_serde::from_value(value).unwrap();
assert_eq!(*thing, deserialized); assert_eq!(*thing, deserialized);
serde_yaml::from_str::<serde::de::IgnoredAny>(yaml).unwrap(); saphyr_serde::from_str::<serde::de::IgnoredAny>(yaml).unwrap();
} }
#[test] #[test]
@ -122,7 +122,7 @@ fn test_float() {
"}; "};
test_serde(&thing, yaml); test_serde(&thing, yaml);
let float: f64 = serde_yaml::from_str(indoc! {" let float: f64 = saphyr_serde::from_str(indoc! {"
.nan .nan
"}) "})
.unwrap(); .unwrap();
@ -149,7 +149,7 @@ fn test_float32() {
"}; "};
test_serde(&thing, yaml); test_serde(&thing, yaml);
let single_float: f32 = serde_yaml::from_str(indoc! {" let single_float: f32 = saphyr_serde::from_str(indoc! {"
.nan .nan
"}) "})
.unwrap(); .unwrap();
@ -162,19 +162,19 @@ fn test_char() {
let yaml = indoc! {" let yaml = indoc! {"
'.' '.'
"}; "};
assert_eq!(yaml, serde_yaml::to_string(&ch).unwrap()); assert_eq!(yaml, saphyr_serde::to_string(&ch).unwrap());
let ch = '#'; let ch = '#';
let yaml = indoc! {" let yaml = indoc! {"
'#' '#'
"}; "};
assert_eq!(yaml, serde_yaml::to_string(&ch).unwrap()); assert_eq!(yaml, saphyr_serde::to_string(&ch).unwrap());
let ch = '-'; let ch = '-';
let yaml = indoc! {" let yaml = indoc! {"
'-' '-'
"}; "};
assert_eq!(yaml, serde_yaml::to_string(&ch).unwrap()); assert_eq!(yaml, saphyr_serde::to_string(&ch).unwrap());
} }
#[test] #[test]
@ -220,7 +220,7 @@ fn test_map_key_value() {
let yaml = indoc! {" let yaml = indoc! {"
k: v k: v
"}; "};
assert_eq!(yaml, serde_yaml::to_string(&Map).unwrap()); assert_eq!(yaml, saphyr_serde::to_string(&Map).unwrap());
} }
#[test] #[test]

View file

@ -5,18 +5,17 @@
)] )]
use indoc::indoc; use indoc::indoc;
use saphyr_serde::{Number, Value};
use serde::de::IntoDeserializer; use serde::de::IntoDeserializer;
use serde::Deserialize; use serde::{Deserialize, Serialize};
use serde_derive::{Deserialize, Serialize};
use serde_yaml::{Number, Value};
#[test] #[test]
fn test_nan() { fn test_nan() {
let pos_nan = serde_yaml::from_str::<Value>(".nan").unwrap(); let pos_nan = saphyr_serde::from_str::<Value>(".nan").unwrap();
assert!(pos_nan.is_f64()); assert!(pos_nan.is_f64());
assert_eq!(pos_nan, pos_nan); assert_eq!(pos_nan, pos_nan);
let neg_fake_nan = serde_yaml::from_str::<Value>("-.nan").unwrap(); let neg_fake_nan = saphyr_serde::from_str::<Value>("-.nan").unwrap();
assert!(neg_fake_nan.is_string()); assert!(neg_fake_nan.is_string());
let significand_mask = 0xF_FFFF_FFFF_FFFF; let significand_mask = 0xF_FFFF_FFFF_FFFF;
@ -27,7 +26,7 @@ fn test_nan() {
#[test] #[test]
fn test_digits() { fn test_digits() {
let num_string = serde_yaml::from_str::<Value>("01").unwrap(); let num_string = saphyr_serde::from_str::<Value>("01").unwrap();
assert!(num_string.is_string()); assert!(num_string.is_string());
} }
@ -39,15 +38,15 @@ fn test_into_deserializer() {
second: u32, second: u32,
} }
let value = serde_yaml::from_str::<Value>("xyz").unwrap(); let value = saphyr_serde::from_str::<Value>("xyz").unwrap();
let s = String::deserialize(value.into_deserializer()).unwrap(); let s = String::deserialize(value.into_deserializer()).unwrap();
assert_eq!(s, "xyz"); assert_eq!(s, "xyz");
let value = serde_yaml::from_str::<Value>("- first\n- second\n- third").unwrap(); let value = saphyr_serde::from_str::<Value>("- first\n- second\n- third").unwrap();
let arr = Vec::<String>::deserialize(value.into_deserializer()).unwrap(); let arr = Vec::<String>::deserialize(value.into_deserializer()).unwrap();
assert_eq!(arr, &["first", "second", "third"]); assert_eq!(arr, &["first", "second", "third"]);
let value = serde_yaml::from_str::<Value>("first: abc\nsecond: 99").unwrap(); let value = saphyr_serde::from_str::<Value>("first: abc\nsecond: 99").unwrap();
let test = Test::deserialize(value.into_deserializer()).unwrap(); let test = Test::deserialize(value.into_deserializer()).unwrap();
assert_eq!( assert_eq!(
test, test,
@ -91,7 +90,7 @@ fn test_merge() {
label: center/big label: center/big
"}; "};
let mut value: Value = serde_yaml::from_str(yaml).unwrap(); let mut value: Value = saphyr_serde::from_str(yaml).unwrap();
value.apply_merge().unwrap(); value.apply_merge().unwrap();
for i in 5..=7 { for i in 5..=7 {
assert_eq!(value[4], value[i]); assert_eq!(value[4], value[i]);
@ -112,7 +111,7 @@ fn test_debug() {
Tagged: !tag true Tagged: !tag true
"}; "};
let value: Value = serde_yaml::from_str(yaml).unwrap(); let value: Value = saphyr_serde::from_str(yaml).unwrap();
let debug = format!("{:#?}", value); let debug = format!("{:#?}", value);
let expected = indoc! {r#" let expected = indoc! {r#"
@ -143,11 +142,11 @@ fn test_tagged() {
Variant(usize), Variant(usize),
} }
let value = serde_yaml::to_value(&Enum::Variant(0)).unwrap(); let value = saphyr_serde::to_value(Enum::Variant(0)).unwrap();
let deserialized: serde_yaml::Value = serde_yaml::from_value(value.clone()).unwrap(); let deserialized: saphyr_serde::Value = saphyr_serde::from_value(value.clone()).unwrap();
assert_eq!(value, deserialized); assert_eq!(value, deserialized);
let serialized = serde_yaml::to_value(&value).unwrap(); let serialized = saphyr_serde::to_value(&value).unwrap();
assert_eq!(value, serialized); assert_eq!(value, serialized);
} }