CodeSampleX

Пример

zerocopy 0.8.62: IntoBytes

Проверенный пример — cargo zerocopy 0.8.62: IntoBytes. Контракт выполнен на rust 1 · linux alpine/x64 · docker и пройден: IntoBytes::as_bytes views a repr(C)…

sha256:66a1fd846520fcfc851045647f0504e39f7bb6b67a909659dcf9c6a15a6a8b8b

Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла. Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди. 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-10-16

Кейс

HOW
Цель
verify IntoBytes in pkg:cargo/zerocopy@0.8.62
Пакеты
Символы
  • IntoBytes
Создан
2026-10-16T16:38:19Z

Контракт

  1. IntoBytes::as_bytes views a repr(C) struct deriving IntoBytes and Immutable as a byte slice
  2. IntoBytes::as_mut_bytes provides mutable byte-level access when FromBytes and Immutable are also implemented
  3. IntoBytes::write_to, write_to_prefix, and write_to_suffix copy bytes into destination buffers and reject size mismatches
  4. IntoBytes works on primitive arrays and dynamically sized slices

Файлы

  • Cargo.lock
  • Cargo.toml
  • 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-intobytes"
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.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"

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

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

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

[[bin]]
name = "contract"
path = "test/contract.rs"
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 IntoBytes in pkg:cargo/zerocopy@0.8.62
Kind: HOW

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

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:f7c572b1e44cc72a22391779bcc9e59826f20560a8443fe4eb8624f2b1045eee","contract":["IntoBytes::as_bytes views a repr(C) struct deriving IntoBytes and Immutable as a byte slice","IntoBytes::as_mut_bytes provides mutable byte-level access when FromBytes and Immutable are also implemented","IntoBytes::write_to, write_to_prefix, and write_to_suffix copy bytes into destination buffers and reject size mismatches","IntoBytes works on primitive arrays and dynamically sized slices"],"goal":"verify IntoBytes in pkg:cargo/zerocopy@0.8.62","kind":"HOW","packages":["pkg:cargo/zerocopy@0.8.62"],"schemaVersion":1,"symbols":["IntoBytes"]},"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.62"],"schemaVersion":1,"subject":"pkg:cargo/zerocopy@0.8.62","symbols":["IntoBytes"],"verifierAdapter":"cargo@1"}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify IntoBytes in pkg:cargo/zerocopy@0.8.62",
  "kind": "HOW",
  "packages": [
    "pkg:cargo/zerocopy@0.8.62"
  ],
  "symbols": [
    "IntoBytes"
  ]
}
src/lib.rs
//! Clean-room verification sample for zerocopy::IntoBytes.

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

#[repr(C)]
#[derive(Debug, PartialEq, Eq, FromBytes, IntoBytes, Immutable)]
struct PacketHeader {
    magic: [u8; 2],
    length: u16,
    sequence: u32,
}

fn main() {
    // 1. IntoBytes::as_bytes views a repr(C) struct deriving IntoBytes and Immutable as a byte slice
    let header = PacketHeader {
        magic: [0xAB, 0xCD],
        length: u16::from_le_bytes([0x10, 0x00]),
        sequence: u32::from_le_bytes([0x01, 0x02, 0x03, 0x04]),
    };
    let bytes: &[u8] = header.as_bytes();
    assert_eq!(bytes.len(), 8);
    assert_eq!(&bytes[0..2], &[0xAB, 0xCD]);
    assert_eq!(&bytes[2..4], &[0x10, 0x00]);
    assert_eq!(&bytes[4..8], &[0x01, 0x02, 0x03, 0x04]);

    // 2. IntoBytes::as_mut_bytes provides mutable byte-level access when FromBytes and Immutable are also implemented
    let mut mutable_header = PacketHeader {
        magic: [0x00, 0x00],
        length: 0,
        sequence: 0,
    };
    let mut_bytes: &mut [u8] = mutable_header.as_mut_bytes();
    mut_bytes.copy_from_slice(&[0xCA, 0xFE, 0x20, 0x00, 0xAA, 0xBB, 0xCC, 0xDD]);
    assert_eq!(mutable_header.magic, [0xCA, 0xFE]);
    assert_eq!(mutable_header.length.to_le_bytes(), [0x20, 0x00]);
    assert_eq!(mutable_header.sequence.to_le_bytes(), [0xAA, 0xBB, 0xCC, 0xDD]);

    // 3. IntoBytes::write_to, write_to_prefix, and write_to_suffix copy bytes into destination buffers and reject size mismatches
    let mut exact_buf = [0u8; 8];
    assert!(header.write_to(&mut exact_buf[..]).is_ok());
    assert_eq!(&exact_buf, header.as_bytes());

    let mut wrong_size_buf = [0u8; 6];
    assert!(header.write_to(&mut wrong_size_buf[..]).is_err());

    let mut larger_buf = [0u8; 12];
    assert!(header.write_to_prefix(&mut larger_buf[..]).is_ok());
    assert_eq!(&larger_buf[..8], header.as_bytes());
    assert_eq!(&larger_buf[8..], &[0, 0, 0, 0]);

    let mut suffix_buf = [0u8; 12];
    assert!(header.write_to_suffix(&mut suffix_buf[..]).is_ok());
    assert_eq!(&suffix_buf[..4], &[0, 0, 0, 0]);
    assert_eq!(&suffix_buf[4..], header.as_bytes());

    // 4. IntoBytes works on primitive arrays and dynamically sized slices
    let arr: [u16; 3] = [
        u16::from_le_bytes([0x01, 0x02]),
        u16::from_le_bytes([0x03, 0x04]),
        u16::from_le_bytes([0x05, 0x06]),
    ];
    assert_eq!(arr.as_bytes(), &[0x01, 0x02, 0x03, 0x04, 0x05, 0x06]);

    let slice: &[u16] = &arr[1..3];
    assert_eq!(slice.as_bytes(), &[0x03, 0x04, 0x05, 0x06]);
}

Исходный сидер

аноним