diff options
author | Android Build Coastguard Worker <android-build-coastguard-worker@google.com> | 2023-07-07 05:14:28 +0000 |
---|---|---|
committer | Android Build Coastguard Worker <android-build-coastguard-worker@google.com> | 2023-07-07 05:14:28 +0000 |
commit | 4d414b9a4aff7163d017ddd9d5e16e50e25b4f4e (patch) | |
tree | e20d9e63a28336194d5b0911fb192bace5528181 | |
parent | d95c85422a07ca720ec26ac59122456a3c0901df (diff) | |
parent | a805a8f39c291e6e3d5595861041d2fb8d26d1b0 (diff) | |
download | serde-4d414b9a4aff7163d017ddd9d5e16e50e25b4f4e.tar.gz |
Snap for 10453563 from a805a8f39c291e6e3d5595861041d2fb8d26d1b0 to mainline-sdkext-releaseaml_sdk_341710000aml_sdk_341510000aml_sdk_341410000aml_sdk_341110080aml_sdk_341110000aml_sdk_341010000aml_sdk_340912010android14-mainline-sdkext-release
Change-Id: I498661eb1963929bcc79e68159c1f1afc2170416
-rw-r--r-- | .cargo_vcs_info.json | 2 | ||||
-rw-r--r-- | Android.bp | 31 | ||||
-rw-r--r-- | Cargo.toml | 46 | ||||
-rw-r--r-- | Cargo.toml.orig | 21 | ||||
-rw-r--r-- | METADATA | 14 | ||||
-rw-r--r-- | README.md | 4 | ||||
-rw-r--r-- | TEST_MAPPING | 74 | ||||
-rw-r--r-- | build.rs | 38 | ||||
-rw-r--r-- | cargo2android.json | 4 | ||||
-rw-r--r-- | cargo2android_nostd.bp | 25 | ||||
-rw-r--r-- | crates-io.md | 2 | ||||
-rw-r--r-- | src/de/format.rs | 2 | ||||
-rw-r--r-- | src/de/ignored_any.rs | 2 | ||||
-rw-r--r-- | src/de/impls.rs | 57 | ||||
-rw-r--r-- | src/de/mod.rs | 34 | ||||
-rw-r--r-- | src/de/value.rs | 99 | ||||
-rw-r--r-- | src/lib.rs | 70 | ||||
-rw-r--r-- | src/private/de.rs | 25 | ||||
-rw-r--r-- | src/private/ser.rs | 8 | ||||
-rw-r--r-- | src/ser/impls.rs | 85 | ||||
-rw-r--r-- | src/ser/mod.rs | 18 |
21 files changed, 460 insertions, 201 deletions
diff --git a/.cargo_vcs_info.json b/.cargo_vcs_info.json index 5f68c60..e57ffb4 100644 --- a/.cargo_vcs_info.json +++ b/.cargo_vcs_info.json @@ -1,6 +1,6 @@ { "git": { - "sha1": "02bd79a0bada78dd88d050f6478806f001f41fb0" + "sha1": "ccf9c6fc072378ea8c4f15df1024e258d35d6e61" }, "path_in_vcs": "serde" }
\ No newline at end of file @@ -43,7 +43,7 @@ rust_library { host_supported: true, crate_name: "serde", cargo_env_compat: true, - cargo_pkg_version: "1.0.136", + cargo_pkg_version: "1.0.152", srcs: ["src/lib.rs"], edition: "2015", features: [ @@ -58,16 +58,43 @@ rust_library { "//apex_available:platform", "//apex_available:anyapex", ], + product_available: true, vendor_available: true, min_sdk_version: "29", } +rust_library_rlib { + name: "libserde_nostd", + crate_name: "serde", + cargo_env_compat: true, + cargo_pkg_version: "1.0.152", + srcs: ["src/lib.rs"], + edition: "2015", + prefer_rlib: true, + no_stdlibs: true, + stdlibs: [ + "liballoc.rust_sysroot", + "libcompiler_builtins.rust_sysroot", + "libcore.rust_sysroot", + ], + features: [ + "alloc", + "derive", + "serde_derive", + ], + proc_macros: ["libserde_derive"], + apex_available: [ + "//apex_available:platform", + "//apex_available:anyapex", + ], +} + rust_test { name: "serde_test_src_lib", host_supported: true, crate_name: "serde", cargo_env_compat: true, - cargo_pkg_version: "1.0.136", + cargo_pkg_version: "1.0.152", srcs: ["src/lib.rs"], test_suites: ["general-tests"], auto_gen_config: true, @@ -10,28 +10,54 @@ # See Cargo.toml.orig for the original contents. [package] -rust-version = "1.15" +rust-version = "1.13" name = "serde" -version = "1.0.136" -authors = ["Erick Tryzelaar <erick.tryzelaar@gmail.com>", "David Tolnay <dtolnay@gmail.com>"] +version = "1.0.152" +authors = [ + "Erick Tryzelaar <erick.tryzelaar@gmail.com>", + "David Tolnay <dtolnay@gmail.com>", +] build = "build.rs" -include = ["build.rs", "src/**/*.rs", "crates-io.md", "README.md", "LICENSE-APACHE", "LICENSE-MIT"] +include = [ + "build.rs", + "src/**/*.rs", + "crates-io.md", + "README.md", + "LICENSE-APACHE", + "LICENSE-MIT", +] description = "A generic serialization/deserialization framework" homepage = "https://serde.rs" -documentation = "https://docs.serde.rs/serde/" +documentation = "https://docs.rs/serde" readme = "crates-io.md" -keywords = ["serde", "serialization", "no_std"] -categories = ["encoding"] +keywords = [ + "serde", + "serialization", + "no_std", +] +categories = [ + "encoding", + "no-std", +] license = "MIT OR Apache-2.0" repository = "https://github.com/serde-rs/serde" + +[package.metadata.playground] +features = [ + "derive", + "rc", +] + [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] -[package.metadata.playground] -features = ["derive", "rc"] +[lib] +doc-scrape-examples = false + [dependencies.serde_derive] -version = "=1.0.136" +version = "=1.0.152" optional = true + [dev-dependencies.serde_derive] version = "1.0" diff --git a/Cargo.toml.orig b/Cargo.toml.orig index 2cf4ca4..9c3bc58 100644 --- a/Cargo.toml.orig +++ b/Cargo.toml.orig @@ -1,25 +1,28 @@ [package] name = "serde" -version = "1.0.136" # remember to update html_root_url and serde_derive dependency +version = "1.0.152" # remember to update html_root_url and serde_derive dependency authors = ["Erick Tryzelaar <erick.tryzelaar@gmail.com>", "David Tolnay <dtolnay@gmail.com>"] -rust-version = "1.15" -license = "MIT OR Apache-2.0" +build = "build.rs" +categories = ["encoding", "no-std"] description = "A generic serialization/deserialization framework" +documentation = "https://docs.rs/serde" homepage = "https://serde.rs" -repository = "https://github.com/serde-rs/serde" -documentation = "https://docs.serde.rs/serde/" +include = ["build.rs", "src/**/*.rs", "crates-io.md", "README.md", "LICENSE-APACHE", "LICENSE-MIT"] keywords = ["serde", "serialization", "no_std"] -categories = ["encoding"] +license = "MIT OR Apache-2.0" readme = "crates-io.md" -include = ["build.rs", "src/**/*.rs", "crates-io.md", "README.md", "LICENSE-APACHE", "LICENSE-MIT"] -build = "build.rs" +repository = "https://github.com/serde-rs/serde" +rust-version = "1.13" [dependencies] -serde_derive = { version = "=1.0.136", optional = true, path = "../serde_derive" } +serde_derive = { version = "=1.0.152", optional = true, path = "../serde_derive" } [dev-dependencies] serde_derive = { version = "1.0", path = "../serde_derive" } +[lib] +doc-scrape-examples = false + [package.metadata.playground] features = ["derive", "rc"] @@ -1,3 +1,7 @@ +# This project was upgraded with external_updater. +# Usage: tools/external_updater/updater.sh update rust/crates/serde +# For more info, check https://cs.android.com/android/platform/superproject/+/master:tools/external_updater/README.md + name: "serde" description: "A generic serialization/deserialization framework" third_party { @@ -7,13 +11,13 @@ third_party { } url { type: ARCHIVE - value: "https://static.crates.io/crates/serde/serde-1.0.136.crate" + value: "https://static.crates.io/crates/serde/serde-1.0.152.crate" } - version: "1.0.136" + version: "1.0.152" license_type: NOTICE last_upgrade_date { - year: 2022 - month: 3 - day: 1 + year: 2023 + month: 2 + day: 6 } } @@ -1,6 +1,6 @@ # Serde   [![Build Status]][actions] [![Latest Version]][crates.io] [![serde: rustc 1.13+]][Rust 1.13] [![serde_derive: rustc 1.31+]][Rust 1.31] -[Build Status]: https://img.shields.io/github/workflow/status/serde-rs/serde/CI/master +[Build Status]: https://img.shields.io/github/actions/workflow/status/serde-rs/serde/ci.yml?branch=master [actions]: https://github.com/serde-rs/serde/actions?query=branch%3Amaster [Latest Version]: https://img.shields.io/crates/v/serde.svg [crates.io]: https://crates.io/crates/serde @@ -19,7 +19,7 @@ You may be looking for: - [Data formats supported by Serde](https://serde.rs/#data-formats) - [Setting up `#[derive(Serialize, Deserialize)]`](https://serde.rs/derive.html) - [Examples](https://serde.rs/examples.html) -- [API documentation](https://docs.serde.rs/serde/) +- [API documentation](https://docs.rs/serde) - [Release notes](https://github.com/serde-rs/serde/releases) ## Serde in action diff --git a/TEST_MAPPING b/TEST_MAPPING index bec5d80..ed20f35 100644 --- a/TEST_MAPPING +++ b/TEST_MAPPING @@ -11,9 +11,18 @@ "path": "external/rust/crates/bytes" }, { + "path": "external/rust/crates/coset" + }, + { "path": "external/rust/crates/either" }, { + "path": "external/rust/crates/hashbrown" + }, + { + "path": "external/rust/crates/hashlink" + }, + { "path": "external/rust/crates/rand_chacha" }, { @@ -39,82 +48,61 @@ }, { "path": "external/rust/crates/url" - } - ], - "presubmit": [ - { - "name": "ZipFuseTest" - }, - { - "name": "apkdmverity.test" - }, - { - "name": "authfs_device_test_src_lib" - }, - { - "name": "diced_test" - }, - { - "name": "diced_vendor_test" }, { - "name": "keystore2_test" + "path": "packages/modules/Virtualization/apkdmverity" }, { - "name": "keystore2_test_utils_test" + "path": "packages/modules/Virtualization/authfs" }, { - "name": "legacykeystore_test" + "path": "packages/modules/Virtualization/avmd" }, { - "name": "libcert_request_validator_tests" + "path": "packages/modules/Virtualization/encryptedstore" }, { - "name": "microdroid_manager_test" + "path": "packages/modules/Virtualization/libs/apkverify" }, { - "name": "serde_test_src_lib" + "path": "packages/modules/Virtualization/libs/devicemapper" }, { - "name": "virtualizationservice_device_test" - } - ], - "presubmit-rust": [ - { - "name": "ZipFuseTest" - }, - { - "name": "apkdmverity.test" + "path": "packages/modules/Virtualization/microdroid_manager" }, { - "name": "authfs_device_test_src_lib" + "path": "packages/modules/Virtualization/virtualizationmanager" }, { - "name": "diced_test" + "path": "packages/modules/Virtualization/vm" }, { - "name": "diced_vendor_test" + "path": "packages/modules/Virtualization/zipfuse" }, { - "name": "keystore2_test" + "path": "system/keymint/derive" }, { - "name": "keystore2_test_utils_test" + "path": "system/keymint/hal" }, { - "name": "legacykeystore_test" + "path": "system/security/diced" }, { - "name": "libcert_request_validator_tests" + "path": "system/security/keystore2" }, { - "name": "microdroid_manager_test" - }, + "path": "system/security/keystore2/legacykeystore" + } + ], + "presubmit": [ { "name": "serde_test_src_lib" - }, + } + ], + "presubmit-rust": [ { - "name": "virtualizationservice_device_test" + "name": "serde_test_src_lib" } ] } @@ -6,6 +6,8 @@ use std::str::{self, FromStr}; // opening a GitHub issue if your build environment requires some way to enable // these cfgs other than by executing our build script. fn main() { + println!("cargo:rerun-if-changed=build.rs"); + let minor = match rustc_minor_version() { Some(minor) => minor, None => return, @@ -89,24 +91,28 @@ fn main() { println!("cargo:rustc-cfg=no_core_try_from"); println!("cargo:rustc-cfg=no_num_nonzero_signed"); println!("cargo:rustc-cfg=no_systemtime_checked_add"); + println!("cargo:rustc-cfg=no_relaxed_trait_bounds"); } - // Whitelist of archs that support std::sync::atomic module. Ideally we - // would use #[cfg(target_has_atomic = "...")] but it is not stable yet. - // Instead this is based on rustc's compiler/rustc_target/src/spec/*.rs. - let has_atomic64 = target.starts_with("x86_64") - || target.starts_with("i686") - || target.starts_with("aarch64") - || target.starts_with("powerpc64") - || target.starts_with("sparc64") - || target.starts_with("mips64el") - || target.starts_with("riscv64"); - let has_atomic32 = has_atomic64 || emscripten; - if minor < 34 || !has_atomic64 { - println!("cargo:rustc-cfg=no_std_atomic64"); - } - if minor < 34 || !has_atomic32 { - println!("cargo:rustc-cfg=no_std_atomic"); + // Support for #[cfg(target_has_atomic = "...")] stabilized in Rust 1.60. + if minor < 60 { + println!("cargo:rustc-cfg=no_target_has_atomic"); + // Allowlist of archs that support std::sync::atomic module. This is + // based on rustc's compiler/rustc_target/src/spec/*.rs. + let has_atomic64 = target.starts_with("x86_64") + || target.starts_with("i686") + || target.starts_with("aarch64") + || target.starts_with("powerpc64") + || target.starts_with("sparc64") + || target.starts_with("mips64el") + || target.starts_with("riscv64"); + let has_atomic32 = has_atomic64 || emscripten; + if minor < 34 || !has_atomic64 { + println!("cargo:rustc-cfg=no_std_atomic64"); + } + if minor < 34 || !has_atomic32 { + println!("cargo:rustc-cfg=no_std_atomic"); + } } } diff --git a/cargo2android.json b/cargo2android.json index a6c47ed..89a0f3e 100644 --- a/cargo2android.json +++ b/cargo2android.json @@ -1,7 +1,5 @@ { - "apex-available": [ - "//apex_available:anyapex" - ], + "add-toplevel-block": "cargo2android_nostd.bp", "cfg-blocklist": [ "std_atomic64" ], diff --git a/cargo2android_nostd.bp b/cargo2android_nostd.bp new file mode 100644 index 0000000..d0e88d9 --- /dev/null +++ b/cargo2android_nostd.bp @@ -0,0 +1,25 @@ +rust_library_rlib { + name: "libserde_nostd", + crate_name: "serde", + cargo_env_compat: true, + cargo_pkg_version: "1.0.152", + srcs: ["src/lib.rs"], + edition: "2015", + prefer_rlib: true, + no_stdlibs: true, + stdlibs: [ + "liballoc.rust_sysroot", + "libcompiler_builtins.rust_sysroot", + "libcore.rust_sysroot", + ], + features: [ + "alloc", + "derive", + "serde_derive", + ], + proc_macros: ["libserde_derive"], + apex_available: [ + "//apex_available:platform", + "//apex_available:anyapex", + ], +} diff --git a/crates-io.md b/crates-io.md index b57bc5f..6e0ec28 100644 --- a/crates-io.md +++ b/crates-io.md @@ -10,7 +10,7 @@ You may be looking for: - [Data formats supported by Serde](https://serde.rs/#data-formats) - [Setting up `#[derive(Serialize, Deserialize)]`](https://serde.rs/derive.html) - [Examples](https://serde.rs/examples.html) -- [API documentation](https://docs.serde.rs/serde/) +- [API documentation](https://docs.rs/serde) - [Release notes](https://github.com/serde-rs/serde/releases) ## Serde in action diff --git a/src/de/format.rs b/src/de/format.rs index 58ec096..f14580b 100644 --- a/src/de/format.rs +++ b/src/de/format.rs @@ -1,7 +1,7 @@ use lib::fmt::{self, Write}; use lib::str; -pub struct Buf<'a> { +pub(super) struct Buf<'a> { bytes: &'a mut [u8], offset: usize, } diff --git a/src/de/ignored_any.rs b/src/de/ignored_any.rs index 1d50f5e..9ed438e 100644 --- a/src/de/ignored_any.rs +++ b/src/de/ignored_any.rs @@ -228,7 +228,7 @@ impl<'de> Visitor<'de> for IgnoredAny { where A: EnumAccess<'de>, { - data.variant::<IgnoredAny>()?.1.newtype_variant() + try!(data.variant::<IgnoredAny>()).1.newtype_variant() } } diff --git a/src/de/impls.rs b/src/de/impls.rs index c5aaca7..a257d9e 100644 --- a/src/de/impls.rs +++ b/src/de/impls.rs @@ -733,7 +733,7 @@ impl<'de> Deserialize<'de> for CString { macro_rules! forwarded_impl { ( $(#[doc = $doc:tt])* - ( $($id: ident),* ), $ty: ty, $func: expr + ($($id:ident),*), $ty:ty, $func:expr ) => { $(#[doc = $doc])* impl<'de $(, $id : Deserialize<'de>,)*> Deserialize<'de> for $ty { @@ -793,7 +793,6 @@ where T::deserialize(deserializer).map(Some) } - #[doc(hidden)] fn __private_visit_untagged_option<D>(self, deserializer: D) -> Result<Self::Value, ()> where D: Deserializer<'de>, @@ -861,7 +860,7 @@ impl<'de, T: ?Sized> Deserialize<'de> for PhantomData<T> { #[cfg(any(feature = "std", feature = "alloc"))] macro_rules! seq_impl { ( - $ty:ident < T $(: $tbound1:ident $(+ $tbound2:ident)*)* $(, $typaram:ident : $bound1:ident $(+ $bound2:ident)*)* >, + $ty:ident <T $(: $tbound1:ident $(+ $tbound2:ident)*)* $(, $typaram:ident : $bound1:ident $(+ $bound2:ident)*)*>, $access:ident, $clear:expr, $with_capacity:expr, @@ -1354,7 +1353,7 @@ tuple_impls! { #[cfg(any(feature = "std", feature = "alloc"))] macro_rules! map_impl { ( - $ty:ident < K $(: $kbound1:ident $(+ $kbound2:ident)*)*, V $(, $typaram:ident : $bound1:ident $(+ $bound2:ident)*)* >, + $ty:ident <K $(: $kbound1:ident $(+ $kbound2:ident)*)*, V $(, $typaram:ident : $bound1:ident $(+ $bound2:ident)*)*>, $access:ident, $with_capacity:expr ) => { @@ -1441,15 +1440,15 @@ macro_rules! parse_ip_impl { #[cfg(feature = "std")] macro_rules! variant_identifier { ( - $name_kind: ident ( $($variant: ident; $bytes: expr; $index: expr),* ) - $expecting_message: expr, - $variants_name: ident + $name_kind:ident ($($variant:ident; $bytes:expr; $index:expr),*) + $expecting_message:expr, + $variants_name:ident ) => { enum $name_kind { - $( $variant ),* + $($variant),* } - static $variants_name: &'static [&'static str] = &[ $( stringify!($variant) ),*]; + static $variants_name: &'static [&'static str] = &[$(stringify!($variant)),*]; impl<'de> Deserialize<'de> for $name_kind { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> @@ -1516,12 +1515,12 @@ macro_rules! variant_identifier { #[cfg(feature = "std")] macro_rules! deserialize_enum { ( - $name: ident $name_kind: ident ( $($variant: ident; $bytes: expr; $index: expr),* ) - $expecting_message: expr, - $deserializer: expr + $name:ident $name_kind:ident ($($variant:ident; $bytes:expr; $index:expr),*) + $expecting_message:expr, + $deserializer:expr ) => { - variant_identifier!{ - $name_kind ( $($variant; $bytes; $index),* ) + variant_identifier! { + $name_kind ($($variant; $bytes; $index),*) $expecting_message, VARIANTS } @@ -2012,7 +2011,7 @@ impl<'de> Deserialize<'de> for Duration { b"nanos" => Ok(Field::Nanos), _ => { let value = ::__private::from_utf8_lossy(value); - Err(Error::unknown_field(&value, FIELDS)) + Err(Error::unknown_field(&*value, FIELDS)) } } } @@ -2269,14 +2268,14 @@ where where D: Deserializer<'de>, { - let (start, end) = deserializer.deserialize_struct( + let (start, end) = try!(deserializer.deserialize_struct( "Range", range::FIELDS, range::RangeVisitor { expecting: "struct Range", phantom: PhantomData, }, - )?; + )); Ok(start..end) } } @@ -2290,14 +2289,14 @@ where where D: Deserializer<'de>, { - let (start, end) = deserializer.deserialize_struct( + let (start, end) = try!(deserializer.deserialize_struct( "RangeInclusive", range::FIELDS, range::RangeVisitor { expecting: "struct RangeInclusive", phantom: PhantomData, }, - )?; + )); Ok(RangeInclusive::new(start, end)) } } @@ -2352,7 +2351,7 @@ mod range { b"end" => Ok(Field::End), _ => { let value = ::__private::from_utf8_lossy(value); - Err(Error::unknown_field(&value, FIELDS)) + Err(Error::unknown_field(&*value, FIELDS)) } } } @@ -2663,8 +2662,9 @@ where #[cfg(all(feature = "std", not(no_std_atomic)))] macro_rules! atomic_impl { - ($($ty:ident)*) => { + ($($ty:ident $size:expr)*) => { $( + #[cfg(any(no_target_has_atomic, target_has_atomic = $size))] impl<'de> Deserialize<'de> for $ty { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where @@ -2679,14 +2679,21 @@ macro_rules! atomic_impl { #[cfg(all(feature = "std", not(no_std_atomic)))] atomic_impl! { - AtomicBool - AtomicI8 AtomicI16 AtomicI32 AtomicIsize - AtomicU8 AtomicU16 AtomicU32 AtomicUsize + AtomicBool "8" + AtomicI8 "8" + AtomicI16 "16" + AtomicI32 "32" + AtomicIsize "ptr" + AtomicU8 "8" + AtomicU16 "16" + AtomicU32 "32" + AtomicUsize "ptr" } #[cfg(all(feature = "std", not(no_std_atomic64)))] atomic_impl! { - AtomicI64 AtomicU64 + AtomicI64 "64" + AtomicU64 "64" } #[cfg(feature = "std")] diff --git a/src/de/mod.rs b/src/de/mod.rs index 4ae4773..ca29ec6 100644 --- a/src/de/mod.rs +++ b/src/de/mod.rs @@ -30,7 +30,7 @@ //! # The Deserializer trait //! //! [`Deserializer`] implementations are provided by third-party crates, for -//! example [`serde_json`], [`serde_yaml`] and [`bincode`]. +//! example [`serde_json`], [`serde_yaml`] and [`postcard`]. //! //! A partial list of well-maintained formats is given on the [Serde //! website][data formats]. @@ -104,7 +104,7 @@ //! [`Deserialize`]: ../trait.Deserialize.html //! [`Deserializer`]: ../trait.Deserializer.html //! [`LinkedHashMap<K, V>`]: https://docs.rs/linked-hash-map/*/linked_hash_map/struct.LinkedHashMap.html -//! [`bincode`]: https://github.com/servo/bincode +//! [`postcard`]: https://github.com/jamesmunns/postcard //! [`linked-hash-map`]: https://crates.io/crates/linked-hash-map //! [`serde_derive`]: https://crates.io/crates/serde_derive //! [`serde_json`]: https://github.com/serde-rs/json @@ -501,8 +501,8 @@ impl<'a> Display for Expected + 'a { /// by Serde. /// /// Serde provides `Deserialize` implementations for many Rust primitive and -/// standard library types. The complete list is [here][de]. All of these can -/// be deserialized using Serde out of the box. +/// standard library types. The complete list is [here][crate::de]. All of these +/// can be deserialized using Serde out of the box. /// /// Additionally, Serde provides a procedural macro called `serde_derive` to /// automatically generate `Deserialize` implementations for structs and enums @@ -518,7 +518,6 @@ impl<'a> Display for Expected + 'a { /// `LinkedHashMap<K, V>` type that is deserializable by Serde because the crate /// provides an implementation of `Deserialize` for it. /// -/// [de]: https://docs.serde.rs/serde/de/index.html /// [derive]: https://serde.rs/derive.html /// [impl-deserialize]: https://serde.rs/impl-deserialize.html /// @@ -565,7 +564,7 @@ pub trait Deserialize<'de>: Sized { D: Deserializer<'de>, { // Default implementation just delegates to `deserialize` impl. - *place = Deserialize::deserialize(deserializer)?; + *place = try!(Deserialize::deserialize(deserializer)); Ok(()) } } @@ -708,6 +707,11 @@ impl<T> DeserializeOwned for T where T: for<'de> Deserialize<'de> {} /// where /// A: SeqAccess<'de>, /// { +/// // Decrease the number of reallocations if there are many elements +/// if let Some(size_hint) = seq.size_hint() { +/// self.0.reserve(size_hint); +/// } +/// /// // Visit each element in the inner array and push it onto /// // the existing vector. /// while let Some(elem) = seq.next_element()? { @@ -857,10 +861,10 @@ where /// The `Deserializer` trait supports two entry point styles which enables /// different kinds of deserialization. /// -/// 1. The `deserialize` method. Self-describing data formats like JSON are able -/// to look at the serialized data and tell what it represents. For example -/// the JSON deserializer may see an opening curly brace (`{`) and know that -/// it is seeing a map. If the data format supports +/// 1. The `deserialize_any` method. Self-describing data formats like JSON are +/// able to look at the serialized data and tell what it represents. For +/// example the JSON deserializer may see an opening curly brace (`{`) and +/// know that it is seeing a map. If the data format supports /// `Deserializer::deserialize_any`, it will drive the Visitor using whatever /// type it sees in the input. JSON uses this approach when deserializing /// `serde_json::Value` which is an enum that can represent any JSON @@ -869,7 +873,7 @@ where /// `Deserializer::deserialize_any`. /// /// 2. The various `deserialize_*` methods. Non-self-describing formats like -/// Bincode need to be told what is in the input in order to deserialize it. +/// Postcard need to be told what is in the input in order to deserialize it. /// The `deserialize_*` methods are hints to the deserializer for how to /// interpret the next piece of input. Non-self-describing formats are not /// able to deserialize something like `serde_json::Value` which relies on @@ -879,7 +883,7 @@ where /// `Deserializer::deserialize_any` unless you need to be told by the /// Deserializer what type is in the input. Know that relying on /// `Deserializer::deserialize_any` means your data type will be able to -/// deserialize from self-describing formats only, ruling out Bincode and many +/// deserialize from self-describing formats only, ruling out Postcard and many /// others. /// /// [Serde data model]: https://serde.rs/data-model.html @@ -910,7 +914,7 @@ pub trait Deserializer<'de>: Sized { /// `Deserializer::deserialize_any` unless you need to be told by the /// Deserializer what type is in the input. Know that relying on /// `Deserializer::deserialize_any` means your data type will be able to - /// deserialize from self-describing formats only, ruling out Bincode and + /// deserialize from self-describing formats only, ruling out Postcard and /// many others. fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error> where @@ -1151,7 +1155,7 @@ pub trait Deserializer<'de>: Sized { /// Some types have a human-readable form that may be somewhat expensive to /// construct, as well as a binary form that is compact and efficient. /// Generally text-based formats like JSON and YAML will prefer to use the - /// human-readable one and binary formats like Bincode will prefer the + /// human-readable one and binary formats like Postcard will prefer the /// compact one. /// /// ```edition2018 @@ -1555,7 +1559,7 @@ pub trait Visitor<'de>: Sized { /// `Deserializer`. /// /// This enables zero-copy deserialization of bytes in some formats. For - /// example Bincode data containing bytes can be deserialized with zero + /// example Postcard data containing bytes can be deserialized with zero /// copying into a `&'a [u8]` as long as the input data outlives `'a`. /// /// The default implementation forwards to `visit_bytes`. diff --git a/src/de/value.rs b/src/de/value.rs index 1b154c3..5d88862 100644 --- a/src/de/value.rs +++ b/src/de/value.rs @@ -128,9 +128,7 @@ where type Deserializer = UnitDeserializer<E>; fn into_deserializer(self) -> UnitDeserializer<E> { - UnitDeserializer { - marker: PhantomData, - } + UnitDeserializer::new() } } @@ -141,6 +139,15 @@ pub struct UnitDeserializer<E> { impl_copy_clone!(UnitDeserializer); +impl<E> UnitDeserializer<E> { + #[allow(missing_docs)] + pub fn new() -> Self { + UnitDeserializer { + marker: PhantomData, + } + } +} + impl<'de, E> de::Deserializer<'de> for UnitDeserializer<E> where E: de::Error, @@ -236,8 +243,15 @@ macro_rules! primitive_deserializer { type Deserializer = $name<E>; fn into_deserializer(self) -> $name<E> { + $name::new(self) + } + } + + impl<E> $name<E> { + #[allow(missing_docs)] + pub fn new(value: $ty) -> Self { $name { - value: self, + value: value, marker: PhantomData, } } @@ -308,8 +322,15 @@ where type Deserializer = U32Deserializer<E>; fn into_deserializer(self) -> U32Deserializer<E> { + U32Deserializer::new(self) + } +} + +impl<E> U32Deserializer<E> { + #[allow(missing_docs)] + pub fn new(value: u32) -> Self { U32Deserializer { - value: self, + value: value, marker: PhantomData, } } @@ -390,8 +411,15 @@ where type Deserializer = StrDeserializer<'a, E>; fn into_deserializer(self) -> StrDeserializer<'a, E> { + StrDeserializer::new(self) + } +} + +impl<'a, E> StrDeserializer<'a, E> { + #[allow(missing_docs)] + pub fn new(value: &'a str) -> Self { StrDeserializer { - value: self, + value: value, marker: PhantomData, } } @@ -561,8 +589,16 @@ where type Deserializer = StringDeserializer<E>; fn into_deserializer(self) -> StringDeserializer<E> { + StringDeserializer::new(self) + } +} + +#[cfg(any(feature = "std", feature = "alloc"))] +impl<E> StringDeserializer<E> { + #[allow(missing_docs)] + pub fn new(value: String) -> Self { StringDeserializer { - value: self, + value: value, marker: PhantomData, } } @@ -604,7 +640,7 @@ where } #[cfg(any(feature = "std", feature = "alloc"))] -impl<'de, 'a, E> de::EnumAccess<'de> for StringDeserializer<E> +impl<'de, E> de::EnumAccess<'de> for StringDeserializer<E> where E: de::Error, { @@ -656,8 +692,16 @@ where type Deserializer = CowStrDeserializer<'a, E>; fn into_deserializer(self) -> CowStrDeserializer<'a, E> { + CowStrDeserializer::new(self) + } +} + +#[cfg(any(feature = "std", feature = "alloc"))] +impl<'a, E> CowStrDeserializer<'a, E> { + #[allow(missing_docs)] + pub fn new(value: Cow<'a, str>) -> Self { CowStrDeserializer { - value: self, + value: value, marker: PhantomData, } } @@ -1457,7 +1501,7 @@ where where T: de::DeserializeSeed<'de>, { - match self.map.next_key_seed(seed)? { + match try!(self.map.next_key_seed(seed)) { Some(key) => Ok((key, private::map_as_enum(self.map))), None => Err(de::Error::invalid_type(de::Unexpected::Map, &"enum")), } @@ -1466,6 +1510,41 @@ where //////////////////////////////////////////////////////////////////////////////// +/// A deserializer holding an `EnumAccess`. +#[derive(Clone, Debug)] +pub struct EnumAccessDeserializer<A> { + access: A, +} + +impl<A> EnumAccessDeserializer<A> { + /// Construct a new `EnumAccessDeserializer<A>`. + pub fn new(access: A) -> Self { + EnumAccessDeserializer { access: access } + } +} + +impl<'de, A> de::Deserializer<'de> for EnumAccessDeserializer<A> +where + A: de::EnumAccess<'de>, +{ + type Error = A::Error; + + fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error> + where + V: de::Visitor<'de>, + { + visitor.visit_enum(self.access) + } + + forward_to_deserialize_any! { + bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string + bytes byte_buf option unit unit_struct newtype_struct seq tuple + tuple_struct map struct enum identifier ignored_any + } +} + +//////////////////////////////////////////////////////////////////////////////// + mod private { use lib::*; @@ -31,8 +31,7 @@ //! for Serde by the community. //! //! - [JSON], the ubiquitous JavaScript Object Notation used by many HTTP APIs. -//! - [Bincode], a compact binary format -//! used for IPC within the Servo rendering engine. +//! - [Postcard], a no\_std and embedded-systems friendly compact binary format. //! - [CBOR], a Concise Binary Object Representation designed for small message //! size without the need for version negotiation. //! - [YAML], a self-proclaimed human-friendly configuration language that ain't @@ -45,7 +44,6 @@ //! - [Avro], a binary format used within Apache Hadoop, with support for schema //! definition. //! - [JSON5], a superset of JSON including some productions from ES5. -//! - [Postcard], a no\_std and embedded-systems friendly compact binary format. //! - [URL] query strings, in the x-www-form-urlencoded format. //! - [Envy], a way to deserialize environment variables into Rust structs. //! *(deserialization only)* @@ -54,44 +52,52 @@ //! - [S-expressions], the textual representation of code and data used by the //! Lisp language family. //! - [D-Bus]'s binary wire format. -//! - [FlexBuffers], the schemaless cousin of Google's FlatBuffers zero-copy serialization format. +//! - [FlexBuffers], the schemaless cousin of Google's FlatBuffers zero-copy +//! serialization format. +//! - [Bencode], a simple binary format used in the BitTorrent protocol. +//! - [Token streams], for processing Rust procedural macro input. +//! *(deserialization only)* //! - [DynamoDB Items], the format used by [rusoto_dynamodb] to transfer data to //! and from DynamoDB. +//! - [Hjson], a syntax extension to JSON designed around human reading and +//! editing. *(deserialization only)* //! //! [JSON]: https://github.com/serde-rs/json -//! [Bincode]: https://github.com/servo/bincode +//! [Postcard]: https://github.com/jamesmunns/postcard //! [CBOR]: https://github.com/enarx/ciborium //! [YAML]: https://github.com/dtolnay/serde-yaml //! [MessagePack]: https://github.com/3Hren/msgpack-rust -//! [TOML]: https://github.com/alexcrichton/toml-rs +//! [TOML]: https://docs.rs/toml //! [Pickle]: https://github.com/birkenfeld/serde-pickle //! [RON]: https://github.com/ron-rs/ron -//! [BSON]: https://github.com/zonyitoo/bson-rs -//! [Avro]: https://github.com/flavray/avro-rs +//! [BSON]: https://github.com/mongodb/bson-rust +//! [Avro]: https://docs.rs/apache-avro //! [JSON5]: https://github.com/callum-oakley/json5-rs -//! [Postcard]: https://github.com/jamesmunns/postcard //! [URL]: https://docs.rs/serde_qs //! [Envy]: https://github.com/softprops/envy //! [Envy Store]: https://github.com/softprops/envy-store //! [Cargo]: https://doc.rust-lang.org/cargo/reference/manifest.html -//! [AWS Parameter Store]: https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-paramstore.html +//! [AWS Parameter Store]: https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-parameter-store.html //! [S-expressions]: https://github.com/rotty/lexpr-rs //! [D-Bus]: https://docs.rs/zvariant //! [FlexBuffers]: https://github.com/google/flatbuffers/tree/master/rust/flexbuffers +//! [Bencode]: https://github.com/P3KI/bendy +//! [Token streams]: https://github.com/oxidecomputer/serde_tokenstream //! [DynamoDB Items]: https://docs.rs/serde_dynamo //! [rusoto_dynamodb]: https://docs.rs/rusoto_dynamodb +//! [Hjson]: https://github.com/Canop/deser-hjson //////////////////////////////////////////////////////////////////////////////// // Serde types in rustdoc of other crates get linked to here. -#![doc(html_root_url = "https://docs.rs/serde/1.0.136")] +#![doc(html_root_url = "https://docs.rs/serde/1.0.152")] // Support using Serde without the standard library! #![cfg_attr(not(feature = "std"), no_std)] // Unstable functionality only if the user asks for it. For tracking and // discussion of these features please refer to this issue: // // https://github.com/serde-rs/serde/issues/812 -#![cfg_attr(feature = "unstable", feature(never_type))] +#![cfg_attr(feature = "unstable", feature(error_in_core, never_type))] #![allow(unknown_lints, bare_trait_objects, deprecated)] #![cfg_attr(feature = "cargo-clippy", allow(renamed_and_removed_lints))] // Ignored clippy and clippy_pedantic lints @@ -103,10 +109,8 @@ // clippy bug: https://github.com/rust-lang/rust-clippy/issues/7768 semicolon_if_nothing_returned, // not available in our oldest supported compiler - checked_conversions, empty_enum, - redundant_field_names, - redundant_static_lifetimes, + type_repetition_in_bounds, // https://github.com/rust-lang/rust-clippy/issues/8772 // integer and float ser/de requires these sorts of casts cast_possible_truncation, cast_possible_wrap, @@ -120,9 +124,11 @@ use_self, zero_prefixed_literal, // correctly used + derive_partial_eq_without_eq, enum_glob_use, - let_underscore_drop, + explicit_auto_deref, map_err_ignore, + new_without_default, result_unit_err, wildcard_imports, // not practical @@ -239,18 +245,44 @@ mod lib { #[cfg(not(no_range_inclusive))] pub use self::core::ops::RangeInclusive; - #[cfg(all(feature = "std", not(no_std_atomic)))] + #[cfg(all(feature = "std", no_target_has_atomic, not(no_std_atomic)))] pub use std::sync::atomic::{ AtomicBool, AtomicI16, AtomicI32, AtomicI8, AtomicIsize, AtomicU16, AtomicU32, AtomicU8, AtomicUsize, Ordering, }; - #[cfg(all(feature = "std", not(no_std_atomic64)))] + #[cfg(all(feature = "std", no_target_has_atomic, not(no_std_atomic64)))] pub use std::sync::atomic::{AtomicI64, AtomicU64}; + #[cfg(all(feature = "std", not(no_target_has_atomic)))] + pub use std::sync::atomic::Ordering; + #[cfg(all(feature = "std", not(no_target_has_atomic), target_has_atomic = "8"))] + pub use std::sync::atomic::{AtomicBool, AtomicI8, AtomicU8}; + #[cfg(all(feature = "std", not(no_target_has_atomic), target_has_atomic = "16"))] + pub use std::sync::atomic::{AtomicI16, AtomicU16}; + #[cfg(all(feature = "std", not(no_target_has_atomic), target_has_atomic = "32"))] + pub use std::sync::atomic::{AtomicI32, AtomicU32}; + #[cfg(all(feature = "std", not(no_target_has_atomic), target_has_atomic = "64"))] + pub use std::sync::atomic::{AtomicI64, AtomicU64}; + #[cfg(all(feature = "std", not(no_target_has_atomic), target_has_atomic = "ptr"))] + pub use std::sync::atomic::{AtomicIsize, AtomicUsize}; + #[cfg(any(feature = "std", not(no_core_duration)))] pub use self::core::time::Duration; } +// None of this crate's error handling needs the `From::from` error conversion +// performed implicitly by the `?` operator or the standard library's `try!` +// macro. This simplified macro gives a 5.5% improvement in compile time +// compared to standard `try!`, and 9% improvement compared to `?`. +macro_rules! try { + ($expr:expr) => { + match $expr { + Ok(val) => val, + Err(err) => return Err(err), + } + }; +} + //////////////////////////////////////////////////////////////////////////////// #[macro_use] @@ -280,7 +312,7 @@ use self::__private as private; #[path = "de/seed.rs"] mod seed; -#[cfg(not(feature = "std"))] +#[cfg(not(any(feature = "std", feature = "unstable")))] mod std_error; // Re-export #[derive(Serialize, Deserialize)]. diff --git a/src/private/de.rs b/src/private/de.rs index f0697d6..e9c693d 100644 --- a/src/private/de.rs +++ b/src/private/de.rs @@ -1262,6 +1262,17 @@ mod content { { match self.content { Content::Unit => visitor.visit_unit(), + + // Allow deserializing newtype variant containing unit. + // + // #[derive(Deserialize)] + // #[serde(tag = "result")] + // enum Response<T> { + // Success(T), + // } + // + // We want {"result":"Success"} to deserialize into Response<()>. + Content::Map(ref v) if v.is_empty() => visitor.visit_unit(), _ => Err(self.invalid_type(&visitor)), } } @@ -1799,7 +1810,7 @@ mod content { V: Visitor<'de>, E: de::Error, { - let map = content.iter().map(|&(ref k, ref v)| { + let map = content.iter().map(|(k, v)| { ( ContentRefDeserializer::new(k), ContentRefDeserializer::new(v), @@ -2096,7 +2107,7 @@ mod content { let (variant, value) = match *self.content { Content::Map(ref value) => { let mut iter = value.iter(); - let &(ref variant, ref value) = match iter.next() { + let (variant, value) = match iter.next() { Some(v) => v, None => { return Err(de::Error::invalid_value( @@ -2243,7 +2254,7 @@ mod content { V: de::Visitor<'de>, { match self.value { - Some(&Content::Seq(ref v)) => { + Some(Content::Seq(v)) => { de::Deserializer::deserialize_any(SeqRefDeserializer::new(v), visitor) } Some(other) => Err(de::Error::invalid_type( @@ -2266,10 +2277,10 @@ mod content { V: de::Visitor<'de>, { match self.value { - Some(&Content::Map(ref v)) => { + Some(Content::Map(v)) => { de::Deserializer::deserialize_any(MapRefDeserializer::new(v), visitor) } - Some(&Content::Seq(ref v)) => { + Some(Content::Seq(v)) => { de::Deserializer::deserialize_any(SeqRefDeserializer::new(v), visitor) } Some(other) => Err(de::Error::invalid_type( @@ -2392,7 +2403,7 @@ mod content { T: de::DeserializeSeed<'de>, { match self.iter.next() { - Some(&(ref key, ref value)) => { + Some((key, value)) => { self.value = Some(value); seed.deserialize(ContentRefDeserializer::new(key)).map(Some) } @@ -2697,7 +2708,7 @@ where #[cfg(any(feature = "std", feature = "alloc"))] macro_rules! forward_to_deserialize_other { - ($($func:ident ( $($arg:ty),* ))*) => { + ($($func:ident ($($arg:ty),*))*) => { $( fn $func<V>(self, $(_: $arg,)* _visitor: V) -> Result<V::Value, Self::Error> where diff --git a/src/private/ser.rs b/src/private/ser.rs index 6ee9993..528e8c1 100644 --- a/src/private/ser.rs +++ b/src/private/ser.rs @@ -51,7 +51,6 @@ enum Unsupported { String, ByteArray, Optional, - Unit, #[cfg(any(feature = "std", feature = "alloc"))] UnitStruct, Sequence, @@ -70,7 +69,6 @@ impl Display for Unsupported { Unsupported::String => formatter.write_str("a string"), Unsupported::ByteArray => formatter.write_str("a byte array"), Unsupported::Optional => formatter.write_str("an optional"), - Unsupported::Unit => formatter.write_str("unit"), #[cfg(any(feature = "std", feature = "alloc"))] Unsupported::UnitStruct => formatter.write_str("unit struct"), Unsupported::Sequence => formatter.write_str("a sequence"), @@ -184,7 +182,9 @@ where } fn serialize_unit(self) -> Result<Self::Ok, Self::Error> { - Err(self.bad_type(Unsupported::Unit)) + let mut map = try!(self.delegate.serialize_map(Some(1))); + try!(map.serialize_entry(self.tag, self.variant_name)); + map.end() } fn serialize_unit_struct(self, _: &'static str) -> Result<Self::Ok, Self::Error> { @@ -525,7 +525,7 @@ mod content { Content::Map(ref entries) => { use ser::SerializeMap; let mut map = try!(serializer.serialize_map(Some(entries.len()))); - for &(ref k, ref v) in entries { + for (k, v) in entries { try!(map.serialize_entry(k, v)); } map.end() diff --git a/src/ser/impls.rs b/src/ser/impls.rs index 7219f51..da26772 100644 --- a/src/ser/impls.rs +++ b/src/ser/impls.rs @@ -182,9 +182,27 @@ where } } -#[cfg(any(feature = "std", feature = "alloc"))] +#[cfg(all(any(feature = "std", feature = "alloc"), not(no_relaxed_trait_bounds)))] macro_rules! seq_impl { - ($ty:ident < T $(: $tbound1:ident $(+ $tbound2:ident)*)* $(, $typaram:ident : $bound:ident)* >) => { + ($ty:ident <T $(: $tbound1:ident $(+ $tbound2:ident)*)* $(, $typaram:ident : $bound:ident)*>) => { + impl<T $(, $typaram)*> Serialize for $ty<T $(, $typaram)*> + where + T: Serialize, + { + #[inline] + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where + S: Serializer, + { + serializer.collect_seq(self) + } + } + } +} + +#[cfg(all(any(feature = "std", feature = "alloc"), no_relaxed_trait_bounds))] +macro_rules! seq_impl { + ($ty:ident <T $(: $tbound1:ident $(+ $tbound2:ident)*)* $(, $typaram:ident : $bound:ident)*>) => { impl<T $(, $typaram)*> Serialize for $ty<T $(, $typaram)*> where T: Serialize $(+ $tbound1 $(+ $tbound2)*)*, @@ -347,9 +365,28 @@ tuple_impls! { //////////////////////////////////////////////////////////////////////////////// -#[cfg(any(feature = "std", feature = "alloc"))] +#[cfg(all(any(feature = "std", feature = "alloc"), not(no_relaxed_trait_bounds)))] macro_rules! map_impl { - ($ty:ident < K $(: $kbound1:ident $(+ $kbound2:ident)*)*, V $(, $typaram:ident : $bound:ident)* >) => { + ($ty:ident <K $(: $kbound1:ident $(+ $kbound2:ident)*)*, V $(, $typaram:ident : $bound:ident)*>) => { + impl<K, V $(, $typaram)*> Serialize for $ty<K, V $(, $typaram)*> + where + K: Serialize, + V: Serialize, + { + #[inline] + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where + S: Serializer, + { + serializer.collect_map(self) + } + } + } +} + +#[cfg(all(any(feature = "std", feature = "alloc"), no_relaxed_trait_bounds))] +macro_rules! map_impl { + ($ty:ident <K $(: $kbound1:ident $(+ $kbound2:ident)*)*, V $(, $typaram:ident : $bound:ident)*>) => { impl<K, V $(, $typaram)*> Serialize for $ty<K, V $(, $typaram)*> where K: Serialize $(+ $kbound1 $(+ $kbound2)*)*, @@ -465,7 +502,7 @@ where //////////////////////////////////////////////////////////////////////////////// macro_rules! nonzero_integers { - ( $( $T: ident, )+ ) => { + ($($T:ident,)+) => { $( #[cfg(not(no_num_nonzero))] impl Serialize for num::$T { @@ -522,7 +559,7 @@ where } } -impl<T> Serialize for RefCell<T> +impl<T: ?Sized> Serialize for RefCell<T> where T: Serialize, { @@ -538,7 +575,7 @@ where } #[cfg(feature = "std")] -impl<T> Serialize for Mutex<T> +impl<T: ?Sized> Serialize for Mutex<T> where T: Serialize, { @@ -554,7 +591,7 @@ where } #[cfg(feature = "std")] -impl<T> Serialize for RwLock<T> +impl<T: ?Sized> Serialize for RwLock<T> where T: Serialize, { @@ -614,9 +651,10 @@ impl Serialize for SystemTime { S: Serializer, { use super::SerializeStruct; - let duration_since_epoch = self - .duration_since(UNIX_EPOCH) - .map_err(|_| S::Error::custom("SystemTime must be later than UNIX_EPOCH"))?; + let duration_since_epoch = match self.duration_since(UNIX_EPOCH) { + Ok(duration_since_epoch) => duration_since_epoch, + Err(_) => return Err(S::Error::custom("SystemTime must be later than UNIX_EPOCH")), + }; let mut state = try!(serializer.serialize_struct("SystemTime", 2)); try!(state.serialize_field("secs_since_epoch", &duration_since_epoch.as_secs())); try!(state.serialize_field("nanos_since_epoch", &duration_since_epoch.subsec_nanos())); @@ -735,8 +773,9 @@ impl Serialize for net::Ipv4Addr { // Skip over delimiters that we initialized buf with written += format_u8(*oct, &mut buf[written + 1..]) + 1; } - // We've only written ASCII bytes to the buffer, so it is valid UTF-8 - serializer.serialize_str(unsafe { str::from_utf8_unchecked(&buf[..written]) }) + // Safety: We've only written ASCII bytes to the buffer, so it is valid UTF-8 + let buf = unsafe { str::from_utf8_unchecked(&buf[..written]) }; + serializer.serialize_str(buf) } else { self.octets().serialize(serializer) } @@ -908,15 +947,16 @@ where #[cfg(all(feature = "std", not(no_std_atomic)))] macro_rules! atomic_impl { - ($($ty:ident)*) => { + ($($ty:ident $size:expr)*) => { $( + #[cfg(any(no_target_has_atomic, target_has_atomic = $size))] impl Serialize for $ty { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { // Matches the atomic ordering used in libcore for the Debug impl - self.load(Ordering::SeqCst).serialize(serializer) + self.load(Ordering::Relaxed).serialize(serializer) } } )* @@ -925,12 +965,19 @@ macro_rules! atomic_impl { #[cfg(all(feature = "std", not(no_std_atomic)))] atomic_impl! { - AtomicBool - AtomicI8 AtomicI16 AtomicI32 AtomicIsize - AtomicU8 AtomicU16 AtomicU32 AtomicUsize + AtomicBool "8" + AtomicI8 "8" + AtomicI16 "16" + AtomicI32 "32" + AtomicIsize "ptr" + AtomicU8 "8" + AtomicU16 "16" + AtomicU32 "32" + AtomicUsize "ptr" } #[cfg(all(feature = "std", not(no_std_atomic64)))] atomic_impl! { - AtomicI64 AtomicU64 + AtomicI64 "64" + AtomicU64 "64" } diff --git a/src/ser/mod.rs b/src/ser/mod.rs index dcf836b..5c45426 100644 --- a/src/ser/mod.rs +++ b/src/ser/mod.rs @@ -30,7 +30,7 @@ //! # The Serializer trait //! //! [`Serializer`] implementations are provided by third-party crates, for -//! example [`serde_json`], [`serde_yaml`] and [`bincode`]. +//! example [`serde_json`], [`serde_yaml`] and [`postcard`]. //! //! A partial list of well-maintained formats is given on the [Serde //! website][data formats]. @@ -99,7 +99,7 @@ //! [`LinkedHashMap<K, V>`]: https://docs.rs/linked-hash-map/*/linked_hash_map/struct.LinkedHashMap.html //! [`Serialize`]: ../trait.Serialize.html //! [`Serializer`]: ../trait.Serializer.html -//! [`bincode`]: https://github.com/servo/bincode +//! [`postcard`]: https://github.com/jamesmunns/postcard //! [`linked-hash-map`]: https://crates.io/crates/linked-hash-map //! [`serde_derive`]: https://crates.io/crates/serde_derive //! [`serde_json`]: https://github.com/serde-rs/json @@ -115,10 +115,13 @@ mod impossible; pub use self::impossible::Impossible; +#[cfg(all(feature = "unstable", not(feature = "std")))] +#[doc(inline)] +pub use core::error::Error as StdError; #[cfg(feature = "std")] #[doc(no_inline)] pub use std::error::Error as StdError; -#[cfg(not(feature = "std"))] +#[cfg(not(any(feature = "std", feature = "unstable")))] #[doc(no_inline)] pub use std_error::Error as StdError; @@ -191,8 +194,8 @@ declare_error_trait!(Error: Sized + Debug + Display); /// by Serde. /// /// Serde provides `Serialize` implementations for many Rust primitive and -/// standard library types. The complete list is [here][ser]. All of these can -/// be serialized using Serde out of the box. +/// standard library types. The complete list is [here][crate::ser]. All of +/// these can be serialized using Serde out of the box. /// /// Additionally, Serde provides a procedural macro called [`serde_derive`] to /// automatically generate `Serialize` implementations for structs and enums in @@ -212,7 +215,6 @@ declare_error_trait!(Error: Sized + Debug + Display); /// [`linked-hash-map`]: https://crates.io/crates/linked-hash-map /// [`serde_derive`]: https://crates.io/crates/serde_derive /// [derive section of the manual]: https://serde.rs/derive.html -/// [ser]: https://docs.serde.rs/serde/ser/index.html pub trait Serialize { /// Serialize this value into the given Serde serializer. /// @@ -314,7 +316,7 @@ pub trait Serialize { /// - For example the `E::S` in `enum E { S { r: u8, g: u8, b: u8 } }`. /// /// Many Serde serializers produce text or binary data as output, for example -/// JSON or Bincode. This is not a requirement of the `Serializer` trait, and +/// JSON or Postcard. This is not a requirement of the `Serializer` trait, and /// there are serializers that do not produce text or binary output. One example /// is the `serde_json::value::Serializer` (distinct from the main `serde_json` /// serializer) that produces a `serde_json::Value` data structure in memory as @@ -1423,7 +1425,7 @@ pub trait Serializer: Sized { /// Some types have a human-readable form that may be somewhat expensive to /// construct, as well as a binary form that is compact and efficient. /// Generally text-based formats like JSON and YAML will prefer to use the - /// human-readable one and binary formats like Bincode will prefer the + /// human-readable one and binary formats like Postcard will prefer the /// compact one. /// /// ```edition2018 |