From 0cdfa5446a40d7d1f43b932fefcdd1a6d4d403de Mon Sep 17 00:00:00 2001 From: funman300 Date: Mon, 8 Jun 2026 10:49:53 -0700 Subject: [PATCH] feat(card_game): add optional serde feature for Deck, Suit, Rank, Card MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adds a `serde` Cargo feature that gates #[derive(Serialize, Deserialize)] on the four primitive types: Deck, Suit, Rank, and Card. - Deck / Suit / Rank: plain enum derives — serialize as variant name strings - Card: newtype over NonZeroU8 with #[serde(transparent)], serializes as the raw packed byte (deck<<6 | suit<<4 | rank) Without the feature the crate remains no_std-compatible and pulls no additional dependencies. With it, serde 1.x (derive only, no std) is added as an optional dep. Downstream consumers enable with: card_game = { ..., features = ["serde"] } --- card_game/Cargo.toml | 4 ++++ card_game/src/lib.rs | 5 +++++ 2 files changed, 9 insertions(+) diff --git a/card_game/Cargo.toml b/card_game/Cargo.toml index 051d596..7423e64 100644 --- a/card_game/Cargo.toml +++ b/card_game/Cargo.toml @@ -8,8 +8,12 @@ description = "Card game library." authors = ["Rhys Lloyd "] keywords = ["card", "cards", "solitaire", "klondike"] +[features] +serde = ["dep:serde"] + [dependencies] arrayvec = { version = "0.7.6", registry = "Quaternions", features = ["len_u8"], default-features = false } +serde = { version = "1", optional = true, default-features = false, features = ["derive"] } [lints] workspace = true diff --git a/card_game/src/lib.rs b/card_game/src/lib.rs index ab698e0..fcf94fa 100644 --- a/card_game/src/lib.rs +++ b/card_game/src/lib.rs @@ -28,6 +28,7 @@ pub trait Game: Clone { /// card_game supports up to 4 identifiably separate decks. #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub enum Deck { Deck1 = 0b00, Deck2 = 0b01, @@ -48,6 +49,7 @@ impl Deck { } #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub enum Suit { Spades = 0b00, Hearts = 0b01, @@ -77,6 +79,7 @@ impl Suit { } #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub enum Rank { Ace = 1, Two = 2, @@ -146,6 +149,8 @@ impl Rank { /// 2 bits for suit ID /// 4 bits for card Value #[derive(Clone, Debug, Eq, Hash, PartialEq)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +#[cfg_attr(feature = "serde", serde(transparent))] pub struct Card(core::num::NonZeroU8); impl Card { pub const fn new(deck: Deck, suit: Suit, rank: Rank) -> Self {