CodeSampleX

Пример

futures-sink 0.3.34

Проверенный пример — cargo futures-sink 0.3.34. Контракт выполнен на rust 1 · linux alpine/x64 · docker и пройден: Vec implements Sink allowing items to be…

sha256:f0f7e9da2bd66976e164934bfdfb4eb77e0098db2fe97605a535ddf0ecfec105

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

Кейс

HOW
Цель
verify pkg:cargo/futures-sink@0.3.34
Пакеты
Создан
2026-09-18T21:16:06Z

Контракт

  1. Vec implements Sink allowing items to be sent and buffered via poll_ready and start_send
  2. VecDeque implements Sink allowing items to be sent and buffered
  3. Box implements Sink forwarding sink operations to the boxed sink
  4. Mutable reference implements Sink forwarding operations to the underlying sink
  5. Custom Sink implementation manages capacity and closed state across poll_ready, start_send, poll_flush, and poll_close

Файлы

  • 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 = "futures-sink"
version = "0.3.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d"

[[package]]
name = "sample-futures-sink"
version = "1.0.0"
dependencies = [
 "futures-sink",
]
Cargo.toml
[package]
name = "sample-futures-sink"
version = "1.0.0"
edition = "2021"
publish = false

[dependencies]
futures-sink = "=0.3.34"

[[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/futures-sink@0.3.34
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:cargo/futures-sink@0.3.34

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:b5b51a62274142b7c45fc5dcba2922aed1fb6b997db3a757c0d18243044a3471","contract":["Vec implements Sink allowing items to be sent and buffered via poll_ready and start_send","VecDeque implements Sink allowing items to be sent and buffered","Box implements Sink forwarding sink operations to the boxed sink","Mutable reference implements Sink forwarding operations to the underlying sink","Custom Sink implementation manages capacity and closed state across poll_ready, start_send, poll_flush, and poll_close"],"goal":"verify pkg:cargo/futures-sink@0.3.34","kind":"HOW","packages":["pkg:cargo/futures-sink@0.3.34"],"schemaVersion":1},"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/futures-sink@0.3.34"],"schemaVersion":1,"subject":"pkg:cargo/futures-sink@0.3.34","verifierAdapter":"cargo@1"}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:cargo/futures-sink@0.3.34",
  "kind": "HOW",
  "packages": [
    "pkg:cargo/futures-sink@0.3.34"
  ]
}
src/lib.rs
//! Clean-room verification sample for futures-sink.

pub use futures_sink::*;
test/contract.rs
use core::pin::Pin;
use core::task::{Context, Poll, RawWaker, RawWakerVTable, Waker};
use futures_sink::Sink;
use std::collections::VecDeque;

fn dummy_waker() -> Waker {
    static VTABLE: RawWakerVTable = RawWakerVTable::new(
        |_| RawWaker::new(std::ptr::null(), &VTABLE),
        |_| {},
        |_| {},
        |_| {},
    );
    unsafe { Waker::from_raw(RawWaker::new(std::ptr::null(), &VTABLE)) }
}

struct BoundedChannelSink {
    buffer: Vec<i32>,
    capacity: usize,
    closed: bool,
}

impl BoundedChannelSink {
    fn new(capacity: usize) -> Self {
        Self {
            buffer: Vec::new(),
            capacity,
            closed: false,
        }
    }
}

impl Sink<i32> for BoundedChannelSink {
    type Error = &'static str;

    fn poll_ready(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        let this = self.get_mut();
        if this.closed {
            return Poll::Ready(Err("sink is closed"));
        }
        if this.buffer.len() < this.capacity {
            Poll::Ready(Ok(()))
        } else {
            Poll::Pending
        }
    }

    fn start_send(self: Pin<&mut Self>, item: i32) -> Result<(), Self::Error> {
        let this = self.get_mut();
        if this.closed {
            return Err("sink is closed");
        }
        if this.buffer.len() >= this.capacity {
            return Err("sink is full");
        }
        this.buffer.push(item);
        Ok(())
    }

    fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        Poll::Ready(Ok(()))
    }

    fn poll_close(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        let this = self.get_mut();
        this.closed = true;
        Poll::Ready(Ok(()))
    }
}

fn main() {
    let waker = dummy_waker();
    let mut cx = Context::from_waker(&waker);

    // 1. Vec implements Sink allowing items to be sent and buffered via poll_ready and start_send
    let mut vec_sink = Vec::<i32>::new();
    assert_eq!(Pin::new(&mut vec_sink).poll_ready(&mut cx), Poll::Ready(Ok(())));
    assert!(Pin::new(&mut vec_sink).start_send(10).is_ok());
    assert_eq!(Pin::new(&mut vec_sink).poll_ready(&mut cx), Poll::Ready(Ok(())));
    assert!(Pin::new(&mut vec_sink).start_send(20).is_ok());
    assert_eq!(Pin::new(&mut vec_sink).poll_flush(&mut cx), Poll::Ready(Ok(())));
    assert_eq!(Pin::new(&mut vec_sink).poll_close(&mut cx), Poll::Ready(Ok(())));
    assert_eq!(vec_sink, vec![10, 20]);

    // 2. VecDeque implements Sink allowing items to be sent and buffered
    let mut deque_sink = VecDeque::<&'static str>::new();
    assert_eq!(Pin::new(&mut deque_sink).poll_ready(&mut cx), Poll::Ready(Ok(())));
    assert!(Pin::new(&mut deque_sink).start_send("first").is_ok());
    assert_eq!(Pin::new(&mut deque_sink).poll_ready(&mut cx), Poll::Ready(Ok(())));
    assert!(Pin::new(&mut deque_sink).start_send("second").is_ok());
    assert_eq!(Pin::new(&mut deque_sink).poll_flush(&mut cx), Poll::Ready(Ok(())));
    assert_eq!(deque_sink.pop_front(), Some("first"));
    assert_eq!(deque_sink.pop_front(), Some("second"));
    assert_eq!(deque_sink.pop_front(), None);

    // 3. Box implements Sink forwarding sink operations to the boxed sink
    let mut boxed: Box<dyn Sink<i32, Error = core::convert::Infallible> + Unpin> = Box::new(Vec::new());
    assert_eq!(Pin::new(&mut boxed).poll_ready(&mut cx), Poll::Ready(Ok(())));
    assert!(Pin::new(&mut boxed).start_send(99).is_ok());
    assert_eq!(Pin::new(&mut boxed).poll_flush(&mut cx), Poll::Ready(Ok(())));
    assert_eq!(Pin::new(&mut boxed).poll_close(&mut cx), Poll::Ready(Ok(())));

    // 4. Mutable reference implements Sink forwarding operations to the underlying sink
    let mut target_vec = Vec::<i32>::new();
    {
        let mut ref_sink = &mut target_vec;
        assert_eq!(Pin::new(&mut ref_sink).poll_ready(&mut cx), Poll::Ready(Ok(())));
        assert!(Pin::new(&mut ref_sink).start_send(123).is_ok());
        assert_eq!(Pin::new(&mut ref_sink).poll_flush(&mut cx), Poll::Ready(Ok(())));
    }
    assert_eq!(target_vec, vec![123]);

    // 5. Custom Sink implementation manages capacity and closed state across poll_ready, start_send, poll_flush, and poll_close
    let mut custom_sink = BoundedChannelSink::new(2);
    assert_eq!(Pin::new(&mut custom_sink).poll_ready(&mut cx), Poll::Ready(Ok(())));
    assert_eq!(Pin::new(&mut custom_sink).start_send(1), Ok(()));
    assert_eq!(Pin::new(&mut custom_sink).poll_ready(&mut cx), Poll::Ready(Ok(())));
    assert_eq!(Pin::new(&mut custom_sink).start_send(2), Ok(()));
    // Sink is now full: poll_ready returns Pending and start_send returns Err
    assert_eq!(Pin::new(&mut custom_sink).poll_ready(&mut cx), Poll::Pending);
    assert_eq!(Pin::new(&mut custom_sink).start_send(3), Err("sink is full"));
    // Flush and close
    assert_eq!(Pin::new(&mut custom_sink).poll_flush(&mut cx), Poll::Ready(Ok(())));
    assert_eq!(Pin::new(&mut custom_sink).poll_close(&mut cx), Poll::Ready(Ok(())));
    // After closing: poll_ready and start_send return closed error
    assert_eq!(Pin::new(&mut custom_sink).poll_ready(&mut cx), Poll::Ready(Err("sink is closed")));
    assert_eq!(Pin::new(&mut custom_sink).start_send(4), Err("sink is closed"));
    assert_eq!(custom_sink.buffer, vec![1, 2]);

    println!("All futures-sink contract assertions passed successfully.");
}

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

аноним