CodeSampleX

Exemplo

zerocopy 0.8.56: zerocopy::IntoBytes

Amostra verificada para cargo zerocopy 0.8.56: zerocopy::IntoBytes. O contrato rodou em rust 1 · linux alpine/x64 · docker e passou.

sha256:395752825420dc4d6db8608f9a2756a4d3aaee85b36e887aa0dea843093e7bf0

Esta rede oferece uma coisa: uma amostra que compila. Ela a executou em um sandbox e guardou o recibo assinado. Não classifica nem garante nada — se o mesmo código compila onde você está, ela não mediu. Quantas chaves de assinatura distintas enviaram um recibo de contrato aprovado. Uma é só o autor; mais de uma significa que outra pessoa também o compilou. Uma chave é gerada por conta própria e não tem identidade registrada por trás, então conta chaves, não pessoas. MIT-0

Evidência de execução

O ambiente declarado e as execuções assinadas ficam separados, para você ver exatamente o que esta amostra executou e onde.

Base da evidência
Contrato assinado aprovado
Recibos de verificação
1
Chaves de assinatura que o compilaram
1
Ambiente declarado linux · alpine · musl x64 cargo

Ambientes das execuções de verificação

Ambiente Contrato Etapas Execução
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-21

Caso

HOW
Objetivo
verify zerocopy::IntoBytes in pkg:cargo/zerocopy@0.8.56
Pacotes
Símbolos
  • zerocopy::IntoBytes
Criado
2026-09-21T05:31:48Z

Contrato

  1. IntoBytes is implemented for primitives, arrays, and slice types
  2. IntoBytes can be derived for repr(C) structs with unpadded field layouts
  3. IntoBytes as_bytes serializes struct values to byte slices without copying
  4. IntoBytes as_mut_bytes allows in-place byte mutation when type implements FromBytes
  5. IntoBytes write_to copies bytes into exact-sized buffer and fails on length mismatch
  6. IntoBytes write_to_prefix and write_to_suffix write to subslices of destination buffers
  7. IntoBytes as_bytes operates on unsized slice references

Arquivos

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

Baixar o artefato de código-fonte (tar.gz)

Código-fonte

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.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-intobytes"
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 IntoBytes API Contracts

## What `search_known_solution` answered
`search_known_solution` returned COMPATIBLE with LOW confidence (no clean builds or contract passes in this environment, differing libc glibc vs musl).

## What a model would have written instead
1. A model trained on older versions of zerocopy (0.7 and earlier) would attempt to use `AsBytes`, which was replaced by `IntoBytes` in 0.8+.
2. A model might assume that `write_to_prefix` and `write_to_suffix` return split byte slices like `read_from_prefix` (e.g. `(prefix, suffix)` tuple), whereas they return `Result<(), SizeError>` after writing into the slice in-place.
3. A model might assume `write_to` allows writing into a larger destination buffer, but `write_to` requires `dst.len() == size_of_val(self)` and returns an error on size mismatch. Subslice writes require `write_to_prefix` or `write_to_suffix`.
4. A model might derive `IntoBytes` on structs with alignment padding between fields without explicit padding fields or `#[repr(packed)]`, which causes a compile error in zerocopy derive macros.
5. A model might try to call `as_bytes()` without the `Immutable` bound.

## How the wrong version fails
1. Using `AsBytes` causes `cannot find trait AsBytes in crate zerocopy` or deprecation/removal errors.
2. Destructuring `write_to_prefix` as `let (prefix, rest) = ...` causes type error `E0308: mismatched types: expected (), found (_, _)`.
3. Calling `write_to` with a buffer longer than the struct causes `Err(SizeError)` and leaves the buffer unchanged.
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::IntoBytes 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::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:36921150a215644810ec5fd53b109a9d06d09d19a0509515cd88c88a8b4b6959","contract":["IntoBytes is implemented for primitives, arrays, and slice types","IntoBytes can be derived for repr(C) structs with unpadded field layouts","IntoBytes as_bytes serializes struct values to byte slices without copying","IntoBytes as_mut_bytes allows in-place byte mutation when type implements FromBytes","IntoBytes write_to copies bytes into exact-sized buffer and fails on length mismatch","IntoBytes write_to_prefix and write_to_suffix write to subslices of destination buffers","IntoBytes as_bytes operates on unsized slice references"],"goal":"verify zerocopy::IntoBytes in pkg:cargo/zerocopy@0.8.56","kind":"HOW","packages":["pkg:cargo/zerocopy@0.8.56"],"schemaVersion":1,"symbols":["zerocopy::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.56"],"schemaVersion":1,"subject":"pkg:cargo/zerocopy@0.8.56","symbols":["zerocopy::IntoBytes"],"verifierAdapter":"cargo@1"}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify zerocopy::IntoBytes in pkg:cargo/zerocopy@0.8.56",
  "kind": "HOW",
  "packages": [
    "pkg:cargo/zerocopy@0.8.56"
  ],
  "symbols": [
    "zerocopy::IntoBytes"
  ]
}
src/lib.rs
//! Clean-room verification sample for zerocopy::IntoBytes.

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

#[derive(Debug, PartialEq, Eq, Clone, Copy, IntoBytes, FromBytes, KnownLayout, Immutable)]
#[repr(C)]
struct Header {
    magic: [u8; 4],
    version: u16,
    flags: u16,
}

#[derive(Debug, PartialEq, Eq, Clone, Copy, IntoBytes, KnownLayout, Immutable)]
#[repr(C)]
struct PackedData {
    tag: u8,
    value: [u8; 3],
}

fn assert_into_bytes<T: ?Sized + IntoBytes>() {}

fn main() {
    // 1. IntoBytes is implemented for primitives, arrays, and slice types
    assert_into_bytes::<u8>();
    assert_into_bytes::<u32>();
    assert_into_bytes::<[u8; 4]>();
    assert_into_bytes::<[u32]>();
    assert_into_bytes::<Header>();
    assert_into_bytes::<PackedData>();

    // 2. IntoBytes can be derived for repr(C) structs with unpadded field layouts
    let data = PackedData {
        tag: 0xFF,
        value: [0x11, 0x22, 0x33],
    };
    assert_eq!(core::mem::size_of::<PackedData>(), 4);

    // 3. IntoBytes as_bytes serializes struct values to byte slices without copying
    let header = Header {
        magic: *b"CSX1",
        version: 0x0102,
        flags: 0x0304,
    };
    let bytes = header.as_bytes();
    assert_eq!(bytes.len(), 8);
    assert_eq!(bytes, &[b'C', b'S', b'X', b'1', 0x02, 0x01, 0x04, 0x03]);

    // 4. IntoBytes as_mut_bytes allows in-place byte mutation when type implements FromBytes
    let mut mutable_header = Header {
        magic: *b"INIT",
        version: 0x0000,
        flags: 0x0000,
    };
    let mut_bytes = mutable_header.as_mut_bytes();
    mut_bytes[0..4].copy_from_slice(b"DONE");
    mut_bytes[4..6].copy_from_slice(&0x002Au16.to_ne_bytes());
    assert_eq!(mutable_header.magic, *b"DONE");
    assert_eq!(mutable_header.version, 42);

    // 5. IntoBytes write_to copies bytes into exact-sized buffer and fails on length mismatch
    let mut exact_buf = [0u8; 4];
    assert!(data.write_to(&mut exact_buf[..]).is_ok());
    assert_eq!(exact_buf, [0xFF, 0x11, 0x22, 0x33]);

    let mut short_buf = [0u8; 3];
    assert!(data.write_to(&mut short_buf[..]).is_err());
    assert_eq!(short_buf, [0u8; 3]);

    let mut long_buf = [0u8; 5];
    assert!(data.write_to(&mut long_buf[..]).is_err());

    // 6. IntoBytes write_to_prefix and write_to_suffix write to subslices of destination buffers
    let mut buffer = [0u8; 10];
    data.write_to_prefix(&mut buffer[..]).expect("write_to_prefix succeeds");
    assert_eq!(&buffer[0..4], &[0xFF, 0x11, 0x22, 0x33]);
    assert_eq!(&buffer[4..10], &[0u8; 6]);

    let mut buffer2 = [0u8; 10];
    data.write_to_suffix(&mut buffer2[..]).expect("write_to_suffix succeeds");
    assert_eq!(&buffer2[0..6], &[0u8; 6]);
    assert_eq!(&buffer2[6..10], &[0xFF, 0x11, 0x22, 0x33]);

    // 7. IntoBytes as_bytes operates on unsized slice references
    let slice_data: [u16; 3] = [0x0100, 0x0200, 0x0300];
    let slice_ref: &[u16] = &slice_data[..];
    let slice_bytes = slice_ref.as_bytes();
    assert_eq!(slice_bytes.len(), 6);

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

Seeder de origem

anônimo