CodeSampleX

Ejemplo

writeable 0.6.4: writeable::LengthHint, writeable::TryWriteable, writeable::Writeable

Muestra verificada para cargo writeable 0.6.4: writeable::LengthHint, writeable::TryWriteable, writeable::Writeable. El contrato se ejecutó en rust 1 · linux…

sha256:5ee4918f6341adbff8282f896719c7351194020685ab096716618a269bc37909

Esta red ofrece una sola cosa: una muestra que compila. La ejecutó en un sandbox y guardó el recibo firmado. No califica ni garantiza nada: si el mismo código compila donde estás no es algo que haya medido. Cuántas claves de firma distintas presentaron un recibo de contrato aprobado. Una es solo el autor; más de una significa que alguien más también lo compiló. Una clave se genera sola y no tiene identidad registrada detrás, así que cuenta claves, no personas. MIT-0

Evidencia de ejecución

El entorno declarado y las ejecuciones firmadas se muestran por separado, para que veas exactamente qué ejecutó esta muestra y dónde.

Base de evidencia
Contrato firmado aprobado
Recibos de verificación
1
Claves de firma que lo compilaron
1
Entorno declarado linux · alpine · musl x64 cargo

Entornos de las ejecuciones de verificación

Entorno Contrato Etapas Ejecución
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-19

Caso

HOW
Objetivo
verify pkg:cargo/writeable@0.6.4
Paquetes
Símbolos
  • writeable::LengthHint
  • writeable::TryWriteable
  • writeable::Writeable
  • writeable::assert_writeable_eq
  • writeable::cmp_str
  • writeable::impl_display_with_writeable
Creado
2026-09-18T14:08:35Z

Contrato

  1. Writeable trait formats custom types to fmt::Write sinks with custom writeable_length_hint
  2. LengthHint computes exact, bounded and unbounded allocation hints with arithmetic operators
  3. assert_writeable_eq macro verifies Writeable output and length hints against string literals
  4. impl_display_with_writeable macro implements core::fmt::Display by delegating to Writeable
  5. cmp_str and cmp_utf8 compare Writeable instances directly without allocating memory
  6. TryWriteable produces fallible output annotated with Part errors when write fails

Archivos

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

Descargar el artefacto de código fuente (tar.gz)

Código fuente

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

[[package]]
name = "sample-writeable"
version = "1.0.0"
dependencies = [
 "writeable",
]

[[package]]
name = "writeable"
version = "0.6.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc"
Cargo.toml
[package]
name = "sample-writeable"
version = "1.0.0"
edition = "2021"
publish = false

[dependencies]
writeable = "=0.6.4"

[[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 pkg:cargo/writeable@0.6.4
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:cargo/writeable@0.6.4
Demonstrate these symbols/APIs:
  - writeable::LengthHint
  - writeable::TryWriteable
  - writeable::Writeable
  - writeable::assert_writeable_eq
  - writeable::cmp_str
  - writeable::impl_display_with_writeable

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:d55cedf52a4531d7b22e8258f39adef777bd873a0884cdb7383872a2518bad93","contract":["Writeable trait formats custom types to fmt::Write sinks with custom writeable_length_hint","LengthHint computes exact, bounded and unbounded allocation hints with arithmetic operators","assert_writeable_eq macro verifies Writeable output and length hints against string literals","impl_display_with_writeable macro implements core::fmt::Display by delegating to Writeable","cmp_str and cmp_utf8 compare Writeable instances directly without allocating memory","TryWriteable produces fallible output annotated with Part errors when write fails"],"goal":"verify pkg:cargo/writeable@0.6.4","kind":"HOW","packages":["pkg:cargo/writeable@0.6.4"],"schemaVersion":1,"symbols":["writeable::LengthHint","writeable::TryWriteable","writeable::Writeable","writeable::assert_writeable_eq","writeable::cmp_str","writeable::impl_display_with_writeable"]},"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/writeable@0.6.4"],"schemaVersion":1,"subject":"pkg:cargo/writeable@0.6.4","symbols":["writeable::LengthHint","writeable::TryWriteable","writeable::Writeable","writeable::assert_writeable_eq","writeable::cmp_str","writeable::impl_display_with_writeable"],"verifierAdapter":"cargo@1"}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:cargo/writeable@0.6.4",
  "kind": "HOW",
  "packages": [
    "pkg:cargo/writeable@0.6.4"
  ],
  "symbols": [
    "writeable::LengthHint",
    "writeable::TryWriteable",
    "writeable::Writeable",
    "writeable::assert_writeable_eq",
    "writeable::cmp_str",
    "writeable::impl_display_with_writeable"
  ]
}
src/lib.rs
//! Clean-room verification sample for writeable.

pub use writeable::*;
test/contract.rs
use core::cmp::Ordering;
use core::fmt;
use writeable::{
    adapters::LossyWrap, assert_try_writeable_eq, assert_try_writeable_parts_eq,
    assert_writeable_eq, cmp_str, cmp_utf8, impl_display_with_writeable, LengthHint, Part,
    PartsWrite, TryWriteable, Writeable,
};

struct FormattedMessage<'a> {
    prefix: &'a str,
    number: u32,
}

impl Writeable for FormattedMessage<'_> {
    fn write_to<W: fmt::Write + ?Sized>(&self, sink: &mut W) -> fmt::Result {
        sink.write_str(self.prefix)?;
        sink.write_str(": ")?;
        write!(sink, "{}", self.number)?;
        Ok(())
    }

    fn writeable_length_hint(&self) -> LengthHint {
        LengthHint::between(self.prefix.len() + 3, self.prefix.len() + 12)
    }
}

impl_display_with_writeable!(FormattedMessage<'_>);

#[derive(Debug, PartialEq, Eq)]
enum MessageError {
    InvalidPayload,
}

struct FallibleMessage {
    payload: Option<&'static str>,
}

impl TryWriteable for FallibleMessage {
    type Error = MessageError;

    fn try_write_to_parts<S: PartsWrite + ?Sized>(
        &self,
        sink: &mut S,
    ) -> Result<Result<(), Self::Error>, fmt::Error> {
        sink.write_str("Data: ")?;
        let err = self
            .payload
            .ok_or("[MISSING]")
            .try_write_to_parts(sink)?
            .err();
        if err.is_none() {
            Ok(Ok(()))
        } else {
            Ok(Err(MessageError::InvalidPayload))
        }
    }

    fn writeable_length_hint(&self) -> LengthHint {
        self.payload.ok_or("[MISSING]").writeable_length_hint() + 6
    }
}

fn main() {
    // 1. Writeable trait formats custom types to fmt::Write sinks with custom writeable_length_hint
    let msg = FormattedMessage {
        prefix: "Counter",
        number: 42,
    };
    let mut buffer = String::new();
    let res = msg.write_to(&mut buffer);
    assert!(res.is_ok());
    assert_eq!(buffer, "Counter: 42");

    let hint = msg.writeable_length_hint();
    assert!(hint.0 <= buffer.len());
    assert!(hint.1.unwrap() >= buffer.len());
    assert_eq!(msg.write_to_string(), "Counter: 42");

    // 2. LengthHint computes exact, bounded and unbounded allocation hints with arithmetic operators
    let exact_hint = LengthHint::exact(10);
    assert_eq!(exact_hint.capacity(), 10);
    assert!(!exact_hint.is_zero());
    assert_eq!(LengthHint::exact(0).is_zero(), true);

    let bounded = LengthHint::between(5, 15);
    assert_eq!(bounded.capacity(), 15);

    let combined = exact_hint + LengthHint::exact(7);
    assert_eq!(combined, LengthHint::exact(17));

    let scaled = exact_hint * 3;
    assert_eq!(scaled, LengthHint::exact(30));

    let unbounded = LengthHint::at_least(8);
    assert_eq!((bounded + unbounded).1, None);

    // 3. assert_writeable_eq macro verifies Writeable output and length hints against string literals
    assert_writeable_eq!(&msg, "Counter: 42");

    // 4. impl_display_with_writeable macro implements core::fmt::Display by delegating to Writeable
    assert_eq!(format!("{}", msg), "Counter: 42");
    assert_eq!(msg.to_string(), "Counter: 42");

    // 5. cmp_str and cmp_utf8 compare Writeable instances directly without allocating memory
    assert_eq!(cmp_str(&msg, "Counter: 42"), Ordering::Equal);
    assert_eq!(cmp_str(&msg, "Counter: 41"), Ordering::Greater);
    assert_eq!(cmp_str(&msg, "Counter: 43"), Ordering::Less);
    assert_eq!(cmp_utf8(&msg, b"Counter: 42"), Ordering::Equal);

    // 6. TryWriteable produces fallible output annotated with Part errors when write fails
    let success = FallibleMessage {
        payload: Some("valid"),
    };
    assert_try_writeable_eq!(success, "Data: valid");

    let failure = FallibleMessage { payload: None };
    assert_try_writeable_parts_eq!(
        failure,
        "Data: [MISSING]",
        Err(MessageError::InvalidPayload),
        [(6, 15, Part::ERROR)]
    );

    let lossy = LossyWrap(FallibleMessage { payload: None });
    assert_writeable_eq!(&lossy, "Data: [MISSING]");

    println!("All writeable contract assertions passed successfully.");
}

Seeder de origen

anónimo