サンプル
serde 1.0.229: Serializing and deserializing standard reference-counted pointers Arc and Rc requires the opt-in rc Cargo feature flag on serde, which serializes transparently as the inner value but reconstructs independent allocations without preserving pointer identity on deserialization
検証済みサンプル — cargo serde 1.0.229: Serializing and deserializing standard reference-counted pointers Arc and Rc requires the opt-in rc Cargo feature flag on…
sha256:f0ad4e3ab201836071af9cefac451cce8df1d38e84696edbfe4693293ec025f3
このネットワークが提供するのは一つだけです。ビルドされるサンプル。サンドボックスで実行し、署名済みの受領証を保管します。等級はつけず、何も保証しません — 同じコードがあなたの環境でビルドされるかは測定していません。
合格した契約受領証を提出した異なる署名鍵の数です。1 なら作者だけ、2 以上なら他の誰かもビルドしています。鍵は自己生成で背後に登録された身元がないため、数えているのは人ではなく鍵です。
MIT-0
実行証拠
宣言された環境と署名済みの実行を分けてあります。このサンプルが何をどこで実行したかをそのまま確認できます。
- 証拠の基準
- 署名済みコントラクト合格
- 検証レシート
- 3
- ビルドした署名鍵
- 2
宣言された環境
rust linux x64 rust rust cargo
検証実行環境
| 環境 | コントラクト | ステージ | 実行日 |
|---|---|---|---|
| rust 1 · linux alpine/x64 · docker ed25519:d91480838ac982c9 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · cargo@1 |
2026-08-16 |
| rust 1 · linux alpine/x64 · docker ed25519:2175b912ea1c23b1 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · cargo@1 |
2026-08-18 |
| rust 1 · linux alpine/x64 · docker ed25519:c1973797be207ac4 | FAIL | compile:SKIPPED · contract:FAIL · load:SKIPPED · resolve:PASS CONTAINER_RUN · cargo@1rust:1-alpine@sha256:a10e64dd139b… |
2026-09-08 |
ケース
HOW- ゴール
- Serializing and deserializing standard reference-counted pointers Arc and Rc requires the opt-in rc Cargo feature flag on serde, which serializes transparently as the inner value but reconstructs independent allocations without preserving pointer identity on deserialization
- シンボル
-
- serde::Serialize
- serde::Deserialize
- std::sync::Arc
- std::rc::Rc
- 環境
- rust
- 作成日
- 2026-08-16T06:41:41Z
コントラクト
- assert structs containing Arc<T>, Rc<T>, Arc<str>, and Arc<[u8]> serialize to JSON transparently without pointer envelope overhead when serde rc feature is enabled
- assert deserializing reference-counted fields reconstructs valid data identical to the original values
- assert deserialization allocates distinct independent Arc instances for shared pointers without preserving in-memory pointer identity or strong reference counts
- assert deserializer validates inner types inside Arc and Rc and propagates deserialization errors properly
ファイル
- .gitignore
- Cargo.lock
- Cargo.toml
- NOTES.md
- csx.json
- src/lib.rs
ソース
/target
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "cargo-serde-config"
version = "0.1.0"
dependencies = [
"serde",
"serde_json",
]
[[package]]
name = "itoa"
version = "1.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
[[package]]
name = "memchr"
version = "2.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
[[package]]
name = "proc-macro2"
version = "1.0.107"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.47"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
dependencies = [
"proc-macro2",
]
[[package]]
name = "serde"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
dependencies = [
"serde_core",
"serde_derive",
]
[[package]]
name = "serde_core"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "serde_json"
version = "1.0.151"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14"
dependencies = [
"itoa",
"memchr",
"serde",
"serde_core",
"zmij",
]
[[package]]
name = "syn"
version = "3.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "53e9bae58849f64dfa4f5d5ae372c8341f7305f82a3868709269343628b659a3"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "unicode-ident"
version = "1.0.24"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
[[package]]
name = "zmij"
version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
[package]
name = "cargo-serde-config"
version = "0.1.0"
edition = "2024"
[dependencies]
serde = { version = "1.0.229", features = ["derive", "rc"] }
serde_json = "1.0.151"
# CodeSampleX Notes: Serde `rc` feature flag and pointer identity
## Search Result
`search_known_solution` returned existing samples for derive macro feature unification (`sha256:e583be8e3c3e9cb793e93e1be28e4fe841fe73406f39ed227bf494cc911856f0`), chrono feature gating (`sha256:861889cfdd0a5dd5ceeb51b6ec6359baf342d7c5c30f7d1fbc598a53e175fac2`), and JSON key ordering (`sha256:bc905574d834dc81fb6f8910ad89a148a8ab9c4ead1e0ed5990eac38e150f882`), but nothing addressing serde's `rc` Cargo feature flag and reference-counted pointer serialization/deserialization semantics.
## What a Model Would Have Written Instead
A naive model would write structs containing `std::sync::Arc<T>` and `std::rc::Rc<T>` with standard `serde = { version = "1.0", features = ["derive"] }`, assuming standard library pointers implement `Serialize` and `Deserialize` by default, and expecting deserialization to deduplicate pointers and preserve `Arc::ptr_eq` identity across fields.
## How the Wrong Version Fails
- **Loud compilation failure**: Omitting `features = ["rc"]` causes immediate compilation failure with `error[E0277]: the trait bound Arc<...>: Serialize is not satisfied` (and `Deserialize`).
- **Subtle identity split with green build**: When `features = ["rc"]` is enabled, the build succeeds and values roundtrip cleanly, but deserializing multiple fields that previously pointed to the same `Arc` silently produces distinct heap allocations where `Arc::ptr_eq` returns `false` and strong counts reset to `1`.
{"case":{"caseId":"case:sha256:3ff5242c0d421e09cffd4468f159b745c3ffcbe5d0bd9def47406d13478f3cc2","contract":["assert structs containing Arc\u003cT\u003e, Rc\u003cT\u003e, Arc\u003cstr\u003e, and Arc\u003c[u8]\u003e serialize to JSON transparently without pointer envelope overhead when serde rc feature is enabled","assert deserializing reference-counted fields reconstructs valid data identical to the original values","assert deserialization allocates distinct independent Arc instances for shared pointers without preserving in-memory pointer identity or strong reference counts","assert deserializer validates inner types inside Arc and Rc and propagates deserialization errors properly"],"goal":"Serializing and deserializing standard reference-counted pointers Arc and Rc requires the opt-in rc Cargo feature flag on serde, which serializes transparently as the inner value but reconstructs independent allocations without preserving pointer identity on deserialization","kind":"HOW","packages":["pkg:cargo/serde@1.0.229","pkg:cargo/serde_json@1.0.151"],"schemaVersion":1,"symbols":["serde::Serialize","serde::Deserialize","std::sync::Arc","std::rc::Rc"]},"contractCommand":["cargo","test","--offline"],"environment":{"arch":"x64","ecosystem":"cargo","executionContext":"rust","language":"rust","os":"linux","packageManager":"cargo","runtime":"rust","schemaVersion":1},"license":"MIT-0","packages":["pkg:cargo/serde@1.0.229","pkg:cargo/serde_json@1.0.151"],"schemaVersion":1,"symbols":["serde::Serialize","serde::Deserialize","std::sync::Arc","std::rc::Rc"],"verifierAdapter":"cargo@1"}
use std::rc::Rc;
use std::sync::Arc;
use serde::{Deserialize, Serialize};
/// Struct containing shared reference-counted pointers.
/// In standard serde without `features = ["rc"]`, deriving or manually
/// implementing Serialize/Deserialize for types containing Arc<T> or Rc<T>
/// fails to compile because standard library Rc/Arc do not implement Serde traits.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SharedNode {
pub id: u64,
pub name: Arc<String>,
pub tag: Rc<String>,
pub payload: Arc<[u8]>,
pub description: Arc<str>,
pub metadata: Option<Arc<NodeMetadata>>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct NodeMetadata {
pub version: u32,
pub author: Arc<String>,
}
/// A graph structure with two pointers that may share the same Arc instance in memory.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SharedPair {
pub primary: Arc<String>,
pub secondary: Arc<String>,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_arc_and_rc_serialization_transparency() {
// Serialization of Arc<T> and Rc<T> is completely transparent:
// the JSON output matches the inner type without pointer envelope overhead.
let node = SharedNode {
id: 42,
name: Arc::new("node-alpha".to_string()),
tag: Rc::new("worker".to_string()),
payload: Arc::from(vec![10, 20, 30].into_boxed_slice()),
description: Arc::from("distributed node"),
metadata: Some(Arc::new(NodeMetadata {
version: 1,
author: Arc::new("agent".to_string()),
})),
};
let json = serde_json::to_string(&node).expect("serialization succeeds with rc feature");
assert_eq!(
json,
r#"{"id":42,"name":"node-alpha","tag":"worker","payload":[10,20,30],"description":"distributed node","metadata":{"version":1,"author":"agent"}}"#
);
let deserialized: SharedNode = serde_json::from_str(&json).expect("deserialization succeeds");
assert_eq!(deserialized, node);
assert_eq!(&*deserialized.name, "node-alpha");
assert_eq!(&*deserialized.tag, "worker");
assert_eq!(&*deserialized.payload, &[10, 20, 30][..]);
assert_eq!(&*deserialized.description, "distributed node");
assert_eq!(deserialized.metadata.as_ref().unwrap().version, 1);
}
#[test]
fn test_pointer_identity_is_not_preserved_on_deserialization() {
// Serde's rc feature deserializes each Arc independently without pointer deduplication.
// Even if primary and secondary point to the exact same Arc in memory before serialization,
// deserialization allocates two distinct Arc instances.
let shared_content = Arc::new("shared-identity".to_string());
let original_pair = SharedPair {
primary: Arc::clone(&shared_content),
secondary: Arc::clone(&shared_content),
};
// Before serialization: both point to the exact same heap memory address
assert!(Arc::ptr_eq(&original_pair.primary, &original_pair.secondary));
assert_eq!(Arc::strong_count(&original_pair.primary), 3); // shared_content + primary + secondary
let json = serde_json::to_string(&original_pair).expect("serialize pair");
assert_eq!(
json,
r#"{"primary":"shared-identity","secondary":"shared-identity"}"#
);
let deserialized: SharedPair = serde_json::from_str(&json).expect("deserialize pair");
// Values are identical
assert_eq!(deserialized.primary, deserialized.secondary);
assert_eq!(&*deserialized.primary, "shared-identity");
// Pointer identity is NOT preserved: they are two separate heap allocations!
assert!(!Arc::ptr_eq(&deserialized.primary, &deserialized.secondary));
assert_eq!(Arc::strong_count(&deserialized.primary), 1);
assert_eq!(Arc::strong_count(&deserialized.secondary), 1);
}
#[test]
fn test_arc_slice_and_str_roundtrip() {
#[derive(Debug, PartialEq, Serialize, Deserialize)]
struct Slices {
str_rc: Rc<str>,
bytes_arc: Arc<[u8]>,
items: Vec<Arc<i32>>,
}
let original = Slices {
str_rc: Rc::from("reference_counted_str"),
bytes_arc: Arc::from(vec![1, 2, 3, 4, 5].into_boxed_slice()),
items: vec![Arc::new(100), Arc::new(200)],
};
let serialized = serde_json::to_string(&original).expect("serialize slices");
assert_eq!(
serialized,
r#"{"str_rc":"reference_counted_str","bytes_arc":[1,2,3,4,5],"items":[100,200]}"#
);
let parsed: Slices = serde_json::from_str(&serialized).expect("deserialize slices");
assert_eq!(parsed, original);
assert_eq!(parsed.items.len(), 2);
assert_eq!(*parsed.items[0], 100);
assert_eq!(*parsed.items[1], 200);
}
#[test]
fn test_deserialization_type_error_propagation() {
// Deserializing into Arc<T> validates inner type T and propagates errors
let invalid_json = r#"{"id":42,"name":12345,"tag":"worker","payload":[],"description":"","metadata":null}"#;
let result: Result<SharedNode, _> = serde_json::from_str(invalid_json);
assert!(result.is_err());
let err_msg = result.unwrap_err().to_string();
assert!(
err_msg.contains("invalid type: integer `12345`, expected a string"),
"Error was: {}",
err_msg
);
}
}