CodeSampleX

샘플

zerocopy 0.8.56: zerocopy::KnownLayout

검증된 샘플 — cargo zerocopy 0.8.56: zerocopy::KnownLayout. rust 1 · linux alpine/x64 · docker에서 contract를 실행해 통과했습니다: KnownLayout is implemented for primitive…

sha256:b5549482a19832598380dcc28980513b095bfd3f32e583e4184fca10ea426dda

이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다. 통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다. MIT-0

실행 증거

선언된 환경과 서명된 실행을 분리해 두었습니다. 이 샘플이 무엇을 어디서 실행했는지 그대로 볼 수 있습니다.

증거 기준
서명된 컨트랙트 통과
검증 영수증
1
빌드한 서명 키
1
선언된 환경 linux · alpine · musl x64 cargo

검증 실행 환경

환경 컨트랙트 단계 실행일
rust 1 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · cargo@1rust:1-alpine@sha256:a10e64dd139b…
2026-09-20

케이스

HOW
목표
verify zerocopy::KnownLayout in pkg:cargo/zerocopy@0.8.56
패키지
심벌
  • zerocopy::KnownLayout
생성일
2026-09-20T10:12:58Z

컨트랙트

  1. KnownLayout is implemented for primitive sized types and slices
  2. KnownLayout can be derived for repr(C) sized structs with PointerMetadata of ()
  3. KnownLayout can be derived for repr(C) slice DST structs with PointerMetadata of usize
  4. size_for_metadata accurately calculates size including alignment rounding for slice DSTs
  5. size_for_metadata returns None when size calculation overflows usize
  6. Ref::from_prefix_with_elems safely accesses slice DST fields with KnownLayout

파일

  • Cargo.lock
  • Cargo.toml
  • NOTES.md
  • PROMPT.md
  • csx.json
  • spec.json
  • src/lib.rs
  • test/contract.rs

소스 아티팩트 내려받기 (tar.gz)

소스

Cargo.lock
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4

[[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 = "sample-zerocopy-knownlayout"
version = "1.0.0"
dependencies = [
 "zerocopy",
]

[[package]]
name = "syn"
version = "2.0.119"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"
dependencies = [
 "proc-macro2",
 "quote",
 "unicode-ident",
]

[[package]]
name = "unicode-ident"
version = "1.0.26"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954"

[[package]]
name = "zerocopy"
version = "0.8.56"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "556764e583adb45a9f8d413c2a147fa7e8d821e48e12b14fd560b607998b75eb"
dependencies = [
 "zerocopy-derive",
]

[[package]]
name = "zerocopy-derive"
version = "0.8.56"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f2ab42fc20575779bd240faa45f94a74256f755c0fa9e89f0ede20d91d0cdfc1"
dependencies = [
 "proc-macro2",
 "quote",
 "syn",
]
Cargo.toml
[package]
name = "sample-zerocopy-knownlayout"
version = "1.0.0"
edition = "2021"
publish = false

[dependencies]
zerocopy = { version = "=0.8.56", features = ["derive"] }

[[bin]]
name = "contract"
path = "test/contract.rs"
NOTES.md
# zerocopy 0.8.56 KnownLayout API Contracts

## What `search_known_solution` answered
`search_known_solution` returned NO_SAFE_MATCH (DECISION: UNKNOWN — no safe verified match). No existing verified sample in the network proved `zerocopy::KnownLayout` in `pkg:cargo/zerocopy@0.8.56`.

## What a model would have written instead
A model might attempt to manually implement `KnownLayout` (which is an unsafe trait guarded by hidden methods that only allow the derive macro to implement) instead of using `#[derive(KnownLayout)]`.
Furthermore, a model might assume that `size_for_metadata` for dynamically sized types (slice DSTs) is a naive calculation `offset + count * elem_size`, forgetting that the total size must be rounded up to the struct's alignment (e.g. 8 bytes header + 10 bytes payload with align 4 yields 20 bytes, not 18 bytes).

## How the wrong version fails
1. Manual trait implementation fails to compile because only `zerocopy-derive` is permitted to implement `KnownLayout`.
2. Asserting `size_for_metadata(10) == Some(18)` causes a test panic because the actual layout computation rounds up to the struct alignment (20).
PROMPT.md
Clean-room public code sample — generation instructions

Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.

A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.

Goal: verify zerocopy::KnownLayout in pkg:cargo/zerocopy@0.8.56
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:cargo/zerocopy@0.8.56
Demonstrate these symbols/APIs:
  - zerocopy::KnownLayout

Rules:
  - One focused purpose; the smallest project that proves the goal.
  - Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
  - Pin every dependency with a lockfile so resolution is reproducible.
  - No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
  - No personal names, emails, company names, or project identifiers of any kind.
  - No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
  - Keep it under 200 files and 256KB packed.
csx.json
{"case":{"caseId":"case:sha256:e94b6c0ec347e65dfd3909d6114e42b0181e26194a9598e5b88fd700281cb692","contract":["KnownLayout is implemented for primitive sized types and slices","KnownLayout can be derived for repr(C) sized structs with PointerMetadata of ()","KnownLayout can be derived for repr(C) slice DST structs with PointerMetadata of usize","size_for_metadata accurately calculates size including alignment rounding for slice DSTs","size_for_metadata returns None when size calculation overflows usize","Ref::from_prefix_with_elems safely accesses slice DST fields with KnownLayout"],"goal":"verify zerocopy::KnownLayout in pkg:cargo/zerocopy@0.8.56","kind":"HOW","packages":["pkg:cargo/zerocopy@0.8.56"],"schemaVersion":1,"symbols":["zerocopy::KnownLayout"]},"contractCommand":["cargo","run","--offline"],"environment":{"arch":"x64","distro":"alpine","ecosystem":"cargo","libc":"musl","os":"linux","packageManager":"cargo","schemaVersion":1},"license":"MIT-0","packages":["pkg:cargo/zerocopy@0.8.56"],"schemaVersion":1,"subject":"pkg:cargo/zerocopy@0.8.56","symbols":["zerocopy::KnownLayout"],"verifierAdapter":"cargo@1"}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify zerocopy::KnownLayout in pkg:cargo/zerocopy@0.8.56",
  "kind": "HOW",
  "packages": [
    "pkg:cargo/zerocopy@0.8.56"
  ],
  "symbols": [
    "zerocopy::KnownLayout"
  ]
}
src/lib.rs
//! Clean-room verification sample for zerocopy::KnownLayout.

pub use zerocopy::KnownLayout;
test/contract.rs
use zerocopy::{FromBytes, Immutable, KnownLayout, Ref};

#[derive(Debug, PartialEq, Eq, KnownLayout, FromBytes, Immutable, Copy, Clone)]
#[repr(C)]
pub struct Header {
    pub magic: u32,
    pub length: u16,
    pub flags: u16,
}

#[derive(Debug, KnownLayout, FromBytes, Immutable)]
#[repr(C)]
pub struct Packet {
    pub header: Header,
    pub payload: [u8],
}

fn assert_known_layout<T: ?Sized + KnownLayout>() {}

fn main() {
    // 1. KnownLayout is implemented for primitive sized types and slices
    assert_known_layout::<u8>();
    assert_known_layout::<u32>();
    assert_known_layout::<[u8]>();
    assert_known_layout::<Header>();
    assert_known_layout::<Packet>();

    // 2. KnownLayout can be derived for repr(C) sized structs with PointerMetadata of ()
    let () = <Header as KnownLayout>::PointerMetadata::default();
    assert_eq!(Header::size_for_metadata(()), Some(8));

    // 3. KnownLayout can be derived for repr(C) slice DST structs with PointerMetadata of usize
    let meta: <Packet as KnownLayout>::PointerMetadata = 10usize;
    assert_eq!(meta, 10usize);

    // 4. size_for_metadata accurately calculates size including alignment rounding for slice DSTs
    assert_eq!(<[u8]>::size_for_metadata(42), Some(42));
    assert_eq!(<[u16]>::size_for_metadata(42), Some(84));
    assert_eq!(Packet::size_for_metadata(0), Some(8));
    assert_eq!(Packet::size_for_metadata(8), Some(16));
    assert_eq!(Packet::size_for_metadata(10), Some(20));

    // 5. size_for_metadata returns None when size calculation overflows usize
    assert_eq!(<[u16]>::size_for_metadata(usize::MAX), None);
    assert_eq!(Packet::size_for_metadata(usize::MAX), None);

    // 6. Ref::from_prefix_with_elems safely accesses slice DST fields with KnownLayout
    let raw_bytes: [u8; 12] = [
        0x78, 0x56, 0x34, 0x12,
        0x04, 0x00,
        0x01, 0x00,
        0xDE, 0xAD, 0xBE, 0xEF,
    ];
    let (packet_ref, rest) = Ref::<&[u8], Packet>::from_prefix_with_elems(&raw_bytes[..], 4)
        .expect("valid slice DST prefix");
    assert_eq!(packet_ref.header.magic, 0x12345678);
    assert_eq!(packet_ref.header.length, 4);
    assert_eq!(packet_ref.header.flags, 1);
    assert_eq!(&packet_ref.payload, &[0xDE, 0xAD, 0xBE, 0xEF]);
    assert!(rest.is_empty());

    println!("All zerocopy::KnownLayout contract assertions passed successfully.");
}

오리진 시더

익명