diff --git a/tools/generate-readme/src/main.rs b/tools/generate-readme/src/main.rs index 230d002fb9..8bb0b4dd6c 100644 --- a/tools/generate-readme/src/main.rs +++ b/tools/generate-readme/src/main.rs @@ -43,15 +43,23 @@ struct RenderError { } fn format_readme(readme: &str) -> Result { - // This regex is used to strip code links like: + // This regex is used to strip code links without url after, like: // // /// Here is a link to [`Vec`]. // // These links don't work in a Markdown file, and so we remove the `[` and `]` // characters to convert them to non-link code snippets. - let body = Regex::new(r"\[(`[^`]*`)\]") - .expect("static regex must compile") - .replace_all(readme, |caps: &Captures| caps[1].to_string()); + let re = Regex::new(r"\[(`[^`]*`)\](\([^)]*\))?").expect("static regex must compile"); + + let body = re.replace_all(readme, |caps: &Captures| { + if caps.get(2).is_some() { + // There is a following `(...)`: keep the whole original text + caps[0].to_string() + } else { + // No `(...)`: strip the surrounding [ ] + caps[1].to_string() + } + }); if body.trim().is_empty() { return Err("generate-readme: `cargo readme --no-license` produced an empty README body" .to_string()); diff --git a/zerocopy/Cargo.lock b/zerocopy/Cargo.lock index 0876f9e8b3..edb697c51d 100644 --- a/zerocopy/Cargo.lock +++ b/zerocopy/Cargo.lock @@ -397,6 +397,8 @@ dependencies = [ "rand", "regex", "rustversion", + "serde", + "serde_json", "static_assertions", "testutil", "zerocopy-derive", diff --git a/zerocopy/Cargo.toml b/zerocopy/Cargo.toml index 246af69d54..eb5538dc7a 100644 --- a/zerocopy/Cargo.toml +++ b/zerocopy/Cargo.toml @@ -97,13 +97,19 @@ pinned-nightly = "nightly-2026-09-30" [package.metadata.docs.rs] all-features = true -rustdoc-args = ["--cfg", "doc_cfg", "--generate-link-to-definition", "--extend-css", "rustdoc/style.css"] +rustdoc-args = [ + "--cfg", + "doc_cfg", + "--generate-link-to-definition", + "--extend-css", + "rustdoc/style.css", +] targets = [ "x86_64-unknown-linux-gnu", "x86_64-apple-darwin", "x86_64-pc-windows-msvc", "i686-unknown-linux-gnu", - "i686-pc-windows-msvc" + "i686-pc-windows-msvc", ] [package.metadata.playground] @@ -122,11 +128,13 @@ std = ["alloc"] __internal_use_only_features_that_work_on_stable = [ "alloc", "derive", + "serde", "simd", "std", ] [dependencies] +serde = { version = "1.0.144", default-features = false, optional = true } zerocopy-derive = { version = "=0.8.66", path = "zerocopy-derive", optional = true } # The "associated proc macro pattern" ensures that the versions of zerocopy and @@ -158,5 +166,6 @@ regex = "1.0" rustversion = "1.0" static_assertions = "1.1" testutil = { path = "testutil" } +serde_json = "1.0.143" # In tests, unlike in production, zerocopy-derive is not optional zerocopy-derive = { version = "=0.8.66", path = "zerocopy-derive" } diff --git a/zerocopy/README.md b/zerocopy/README.md index 9cb313d182..fc6cc6281e 100644 --- a/zerocopy/README.md +++ b/zerocopy/README.md @@ -121,6 +121,10 @@ for network parsing. derives as `use zerocopy_derive::*` rather than by name (e.g., `use zerocopy_derive::FromBytes`). +- **`serde`** + Provides [`serde`](https://github.com/serde-rs/serde) `Serialize` and `Deserialize` impls for + the `byteorder` numeric wrappers by delegating to their underlying primitive types. + - **`simd`** When the `simd` feature is enabled, `FromZeros`, `FromBytes`, and `IntoBytes` impls are emitted for all stable SIMD types which exist on the diff --git a/zerocopy/src/byteorder.rs b/zerocopy/src/byteorder.rs index 4de9981f0a..7e1d6652ed 100644 --- a/zerocopy/src/byteorder.rs +++ b/zerocopy/src/byteorder.rs @@ -654,6 +654,36 @@ example of how it can be used for parsing UDP packets. } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "serde")))] + #[cfg(feature = "serde")] + impl serde::Serialize for $name + where + $native: serde::Serialize, + { + #[inline(always)] + fn serialize(&self, serializer: S) -> Result + where + S: serde::Serializer, + { + $native::serialize(&self.get(), serializer) + } + } + + #[cfg_attr(doc_cfg, doc(cfg(feature = "serde")))] + #[cfg(feature = "serde")] + impl<'de, O: ByteOrder> serde::Deserialize<'de> for $name + where + $native: serde::Deserialize<'de>, + { + #[inline(always)] + fn deserialize(deserializer: D) -> Result + where + D: serde::Deserializer<'de>, + { + $native::deserialize(deserializer).map(Self::from) + } + } + $( impl From<$name> for $larger_native { #[inline(always)] @@ -1650,3 +1680,104 @@ mod tests { assert_eq!(val_be_i16.cmp(&val_be_i16), core::cmp::Ordering::Equal); } } + +#[cfg(all(test, feature = "serde"))] +mod serialization_tests { + use core::fmt::Debug; + + use serde::{Deserialize, Serialize}; + + use crate::{ + byteorder::{Isize, Usize, F32, F64, I128, I16, I32, I64, U128, U16, U32, U64}, + BigEndian, LittleEndian, + }; + + fn assert_roundtrip( + to_serialize: WrapperType, + primitive_value: Option, + ) where + WrapperType: Serialize + for<'de> Deserialize<'de> + PartialEq + Debug, + PrimitiveType: Serialize + for<'de> Deserialize<'de> + PartialEq + Debug, + { + let serialized_value = + serde_json::to_string(&to_serialize).expect("Serialization to json should succeed"); + let deserialized_wrapper = serde_json::from_str(&serialized_value) + .expect("Deserialization from json to wrapper type should succeed"); + assert_eq!(to_serialize, deserialized_wrapper); + + if let Some(primitive_value) = primitive_value { + let deserialized_primitive = serde_json::from_str(&serialized_value) + .expect("Deserialization from json to primitive type should succeed"); + assert_eq!(primitive_value, deserialized_primitive); + } + } + + macro_rules! assert_serialization_roundtrip { + ($prim:ty, $wrapper:ident, $value:expr) => {{ + let primitive_value: $prim = $value; + assert_roundtrip($wrapper::::new(primitive_value), Some(primitive_value)); + assert_roundtrip($wrapper::::new(primitive_value), Some(primitive_value)); + }}; + } + + #[test] + fn serialize_native_primitives() { + assert_serialization_roundtrip!(u16, U16, 0xABCDu16); + assert_serialization_roundtrip!(i16, I16, -123i16); + assert_serialization_roundtrip!(u32, U32, 0x89AB_CDEFu32); + assert_serialization_roundtrip!(i32, I32, -0x1234_5678i32); + assert_serialization_roundtrip!(u64, U64, 0x0123_4567_89AB_CDEFu64); + assert_serialization_roundtrip!(i64, I64, -0x0123_4567_89AB_CDEFi64); + assert_serialization_roundtrip!(u128, U128, 0x1234u128); + assert_serialization_roundtrip!(i128, I128, -0x1234i128); + assert_serialization_roundtrip!(usize, Usize, 0xBEEFusize); + assert_serialization_roundtrip!(isize, Isize, -12isize); + assert_serialization_roundtrip!(f32, F32, 1.25f32); + assert_serialization_roundtrip!(f64, F64, -0.75f64); + } + + #[derive(Serialize, Deserialize, PartialEq, Debug)] + struct SerializableStruct + where + WrapperTypeA: PartialEq + Debug, + WrapperTypeB: PartialEq + Debug, + { + value_a: WrapperTypeA, + value_b: [WrapperTypeB; 2], + value_c: (WrapperTypeA, WrapperTypeB), + } + + macro_rules! assert_struct_serialization_roundtrip { + ($prim:ty, $wrapper:ident, $value:expr) => {{ + let primitive_value: $prim = $value; + let test_struct = SerializableStruct { + value_a: $wrapper::::new(primitive_value), + value_b: [ + $wrapper::::new(primitive_value), + $wrapper::::new(primitive_value), + ], + value_c: ( + $wrapper::::new(primitive_value), + $wrapper::::new(primitive_value), + ), + }; + assert_roundtrip(test_struct, None::<$prim>); + }}; + } + + #[test] + fn serialize_struct() { + assert_struct_serialization_roundtrip!(u16, U16, 0xABCDu16); + assert_struct_serialization_roundtrip!(i16, I16, -123i16); + assert_struct_serialization_roundtrip!(u32, U32, 0x89AB_CDEFu32); + assert_struct_serialization_roundtrip!(i32, I32, -0x1234_5678i32); + assert_struct_serialization_roundtrip!(u64, U64, 0x0123_4567_89AB_CDEFu64); + assert_struct_serialization_roundtrip!(i64, I64, -0x0123_4567_89AB_CDEFi64); + assert_struct_serialization_roundtrip!(u128, U128, 0x1234u128); + assert_struct_serialization_roundtrip!(i128, I128, -0x1234i128); + assert_struct_serialization_roundtrip!(usize, Usize, 0xBEEFusize); + assert_struct_serialization_roundtrip!(isize, Isize, -12isize); + assert_struct_serialization_roundtrip!(f32, F32, 1.25f32); + assert_struct_serialization_roundtrip!(f64, F64, -0.75f64); + } +} diff --git a/zerocopy/src/lib.rs b/zerocopy/src/lib.rs index 7aa69baa54..7f0d6cf6df 100644 --- a/zerocopy/src/lib.rs +++ b/zerocopy/src/lib.rs @@ -123,9 +123,13 @@ //! derives as `use zerocopy_derive::*` rather than by name (e.g., `use //! zerocopy_derive::FromBytes`). //! +//! - **`serde`** +//! Provides [`serde`](https://github.com/serde-rs/serde) `Serialize` and `Deserialize` impls for +//! the `byteorder` numeric wrappers by delegating to their underlying primitive types. +//! //! - **`simd`** -//! When the `simd` feature is enabled, `FromZeros`, `FromBytes`, and -//! `IntoBytes` impls are emitted for all stable SIMD types which exist on the +//! When the `simd` feature is enabled, [`FromZeros`], [`FromBytes`], and +//! [`IntoBytes`] impls are emitted for all stable SIMD types which exist on the //! target platform. Note that the layout of SIMD types is not yet stabilized, //! so these impls may be removed in the future if layout changes make them //! invalid. For more information, see the Unsafe Code Guidelines Reference diff --git a/zerocopy/src/pointer/ptr.rs b/zerocopy/src/pointer/ptr.rs index 2a492171d6..d558299903 100644 --- a/zerocopy/src/pointer/ptr.rs +++ b/zerocopy/src/pointer/ptr.rs @@ -1582,10 +1582,10 @@ mod tests { } test!(ZstDst, 8, 0, Some(0)); - test!(ZstDst, 7, 0, None); + test!(ZstDst, 7, 0, None::); test!(ZstDst, 8, usize::MAX, Some(usize::MAX)); - test!(ZstDst, 7, usize::MAX, None); + test!(ZstDst, 7, usize::MAX, None::); #[derive(KnownLayout, Immutable)] #[repr(C)] @@ -1595,15 +1595,15 @@ mod tests { } test!(Dst, 8, 0, Some(0)); - test!(Dst, 7, 0, None); + test!(Dst, 7, 0, None::); test!(Dst, 9, 1, Some(1)); - test!(Dst, 8, 1, None); + test!(Dst, 8, 1, None::); // If we didn't properly check for overflow, this would cause the // metadata to overflow to 0, and thus the cast would spuriously // succeed. - test!(Dst, 8, usize::MAX - 8 + 1, None); + test!(Dst, 8, usize::MAX - 8 + 1, None::); } #[test]