CodeSampleX

샘플

rand_pcg 0.10.2: rand_pcg::rand_core::TryRng

검증된 샘플 — cargo rand_pcg 0.10.2: rand_pcg::rand_core::TryRng. rust 1 · linux alpine/x64 · docker에서 contract를 실행해 통과했습니다: Pcg32 (Lcg64Xsh32) implements…

sha256:a4df04e222249b067b5bb63f20c7e738b6db8d46162253e0df570289041bdd57

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

실행 증거

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

증거 기준
서명된 컨트랙트 통과
검증 영수증
1
빌드한 서명 키
1
선언된 환경 linux x64 rust 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-11-29

케이스

HOW
목표
verify rand_pcg::rand_core::TryRng in pkg:cargo/rand_pcg@0.10.2
패키지
심벌
  • rand_pcg::rand_core::TryRng
생성일
2026-11-29T02:00:45Z

컨트랙트

  1. Pcg32 (Lcg64Xsh32) implements rand_pcg::rand_core::TryRng<Error = Infallible> with try_next_u32 matching the PCG32 reference vector and try_next_u64/try_fill_bytes matching Rng outputs including odd-length and empty slices
  2. Pcg64 (Lcg128Xsl64), Pcg64Mcg (Mcg128Xsl64), and Pcg64Dxsm (Lcg128CmDxsm64) implement rand_pcg::rand_core::TryRng<Error = Infallible> and produce deterministic outputs identical to Rng
  3. TryRng blanket DerefMut implementation advances underlying Pcg32 and Box<Pcg64> generators identically to direct TryRng calls
  4. SeedableRng::try_from_rng and try_fork succeed against Pcg32/Pcg64Mcg TryRng sources and propagate Err from a fallible TryRng implementation
  5. A custom fallible TryRng wrapper over Pcg32 returns Ok within budget, returns its core::error::Error when exhausted, and adapts to Rng via UnwrapErr (panicking on error)

파일

  • 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 = "rand_core"
version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69"

[[package]]
name = "rand_pcg"
version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "caa0f4137e1c0a72f4c651489402276c8e8e1cf081f3b0ba156d2cbeef09e86a"
dependencies = [
 "rand_core",
]

[[package]]
name = "sample-rand-pcg-try-rng"
version = "1.0.0"
dependencies = [
 "rand_pcg",
]
Cargo.toml
[package]
name = "sample-rand-pcg-try-rng"
version = "1.0.0"
edition = "2021"
publish = false

[dependencies]
rand_pcg = "=0.10.2"

[[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 rand_pcg::rand_core::TryRng in pkg:cargo/rand_pcg@0.10.2
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:cargo/rand_pcg@0.10.2
Demonstrate these symbols/APIs:
  - rand_pcg::rand_core::TryRng
Constraints:
  - executionContext: node
Required runtime conditions:
  - ecosystem: npm
  - language: javascript
  - moduleSystem: cjs
  - packageManager: npm@10.9.8
  - runtime: node@22.23.2

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:5ba53ae1666e7beeceba3da5f7ac7e525a7dbd0323414dc1b4b6435dc1962828","contract":["Pcg32 (Lcg64Xsh32) implements rand_pcg::rand_core::TryRng\u003cError = Infallible\u003e with try_next_u32 matching the PCG32 reference vector and try_next_u64/try_fill_bytes matching Rng outputs including odd-length and empty slices","Pcg64 (Lcg128Xsl64), Pcg64Mcg (Mcg128Xsl64), and Pcg64Dxsm (Lcg128CmDxsm64) implement rand_pcg::rand_core::TryRng\u003cError = Infallible\u003e and produce deterministic outputs identical to Rng","TryRng blanket DerefMut implementation advances underlying Pcg32 and Box\u003cPcg64\u003e generators identically to direct TryRng calls","SeedableRng::try_from_rng and try_fork succeed against Pcg32/Pcg64Mcg TryRng sources and propagate Err from a fallible TryRng implementation","A custom fallible TryRng wrapper over Pcg32 returns Ok within budget, returns its core::error::Error when exhausted, and adapts to Rng via UnwrapErr (panicking on error)"],"goal":"verify rand_pcg::rand_core::TryRng in pkg:cargo/rand_pcg@0.10.2","kind":"HOW","packages":["pkg:cargo/rand_pcg@0.10.2"],"schemaVersion":1,"symbols":["rand_pcg::rand_core::TryRng"]},"contractCommand":["cargo","run","--offline"],"environment":{"arch":"x64","ecosystem":"cargo","language":"rust","os":"linux","packageManager":"cargo","schemaVersion":1},"license":"MIT-0","packages":["pkg:cargo/rand_pcg@0.10.2"],"schemaVersion":1,"subject":"pkg:cargo/rand_pcg@0.10.2","symbols":["rand_pcg::rand_core::TryRng"],"verifierAdapter":"cargo@1"}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify rand_pcg::rand_core::TryRng in pkg:cargo/rand_pcg@0.10.2",
  "kind": "HOW",
  "packages": [
    "pkg:cargo/rand_pcg@0.10.2"
  ],
  "symbols": [
    "rand_pcg::rand_core::TryRng"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
src/lib.rs
use std::fmt;

use rand_pcg::rand_core::{Infallible, TryRng};

/// Error returned by [`BudgetTryRng`] when its call budget reaches zero.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct BudgetExhaustedError;

impl fmt::Display for BudgetExhaustedError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "fallible rng call budget exhausted")
    }
}

impl std::error::Error for BudgetExhaustedError {}

/// A fallible [`TryRng`] adapter around an infallible generator that allows a
/// fixed number of successful calls before returning [`BudgetExhaustedError`].
#[derive(Debug, Clone)]
pub struct BudgetTryRng<R> {
    inner: R,
    remaining_calls: usize,
}

impl<R> BudgetTryRng<R> {
    pub fn new(inner: R, remaining_calls: usize) -> Self {
        Self {
            inner,
            remaining_calls,
        }
    }

    pub fn remaining_calls(&self) -> usize {
        self.remaining_calls
    }

    fn consume_call(&mut self) -> Result<(), BudgetExhaustedError> {
        if self.remaining_calls == 0 {
            return Err(BudgetExhaustedError);
        }
        self.remaining_calls -= 1;
        Ok(())
    }
}

impl<R: TryRng<Error = Infallible>> TryRng for BudgetTryRng<R> {
    type Error = BudgetExhaustedError;

    fn try_next_u32(&mut self) -> Result<u32, Self::Error> {
        self.consume_call()?;
        match self.inner.try_next_u32() {
            Ok(v) => Ok(v),
        }
    }

    fn try_next_u64(&mut self) -> Result<u64, Self::Error> {
        self.consume_call()?;
        match self.inner.try_next_u64() {
            Ok(v) => Ok(v),
        }
    }

    fn try_fill_bytes(&mut self, dst: &mut [u8]) -> Result<(), Self::Error> {
        self.consume_call()?;
        match self.inner.try_fill_bytes(dst) {
            Ok(()) => Ok(()),
        }
    }
}

/// Exercise all three methods of [`rand_pcg::rand_core::TryRng`] on any sized or
/// unsized generator.
pub fn draw_try_sample<R: TryRng + ?Sized>(rng: &mut R) -> Result<(u32, u64, [u8; 11]), R::Error> {
    let w32 = rng.try_next_u32()?;
    let w64 = rng.try_next_u64()?;
    let mut bytes = [0u8; 11];
    rng.try_fill_bytes(&mut bytes)?;
    Ok((w32, w64, bytes))
}
test/contract.rs
use std::panic;

use rand_pcg::rand_core::{Infallible, Rng, SeedableRng, TryRng, UnwrapErr};
use rand_pcg::{
    Lcg128CmDxsm64, Lcg128Xsl64, Lcg64Xsh32, Mcg128Xsl64, Pcg32, Pcg64, Pcg64Dxsm, Pcg64Mcg,
};
use sample_rand_pcg_try_rng::{draw_try_sample, BudgetExhaustedError, BudgetTryRng};

fn assert_infallible_try_rng_matches_rng<R>(mut via_try: R, mut via_rng: R)
where
    R: TryRng<Error = Infallible> + Rng,
{
    let (t32, t64, tbytes) = draw_try_sample(&mut via_try).expect("infallible TryRng");

    let r32 = via_rng.next_u32();
    let r64 = via_rng.next_u64();
    let mut rbytes = [0u8; 11];
    via_rng.fill_bytes(&mut rbytes);

    assert_eq!(t32, r32);
    assert_eq!(t64, r64);
    assert_eq!(tbytes, rbytes);

    // Empty slice fill should succeed cleanly and not advance differently.
    let mut empty_try: [u8; 0] = [];
    let mut empty_rng: [u8; 0] = [];
    via_try
        .try_fill_bytes(&mut empty_try)
        .expect("empty try_fill_bytes");
    via_rng.fill_bytes(&mut empty_rng);

    assert_eq!(
        via_try.try_next_u64().expect("post-empty try_next_u64"),
        via_rng.next_u64()
    );
}

fn main() {
    // 1. Pcg32 (Lcg64Xsh32) TryRng<Error = Infallible> reference vector & Rng equivalence.
    let mut pcg32_ref = Lcg64Xsh32::new(42, 54);
    let mut got_ref = [0u32; 6];
    for slot in &mut got_ref {
        *slot = TryRng::try_next_u32(&mut pcg32_ref).expect("infallible pcg32");
    }
    let expected_ref: [u32; 6] = [
        0xa15c02b7, 0x7b47f409, 0xba1d3330, 0x83d2f293, 0xbfa4784b, 0xcbed606e,
    ];
    assert_eq!(got_ref, expected_ref);

    assert_infallible_try_rng_matches_rng(Pcg32::seed_from_u64(7), Pcg32::seed_from_u64(7));

    // 2. 128-bit PCG variants (Pcg64, Pcg64Mcg, Pcg64Dxsm) implement TryRng<Error = Infallible>.
    assert_infallible_try_rng_matches_rng(
        Lcg128Xsl64::seed_from_u64(11),
        Pcg64::seed_from_u64(11),
    );
    assert_infallible_try_rng_matches_rng(
        Mcg128Xsl64::seed_from_u64(0),
        Pcg64Mcg::seed_from_u64(0),
    );
    assert_infallible_try_rng_matches_rng(
        Lcg128CmDxsm64::seed_from_u64(23),
        Pcg64Dxsm::seed_from_u64(23),
    );

    // Known Pcg64Mcg seed 0 first u64 via TryRng.
    let mut mcg0 = Pcg64Mcg::seed_from_u64(0);
    assert_eq!(
        TryRng::try_next_u64(&mut mcg0).expect("infallible mcg"),
        0x5603f242407deca2
    );

    // 3. Blanket DerefMut impl of TryRng via &mut R and Box<R>.
    let mut direct_pcg32 = Pcg32::seed_from_u64(99);
    let mut ref_pcg32 = Pcg32::seed_from_u64(99);
    let mut mut_ref: &mut Pcg32 = &mut ref_pcg32;
    assert_eq!(
        draw_try_sample(&mut mut_ref).expect("mut ref TryRng"),
        draw_try_sample(&mut direct_pcg32).expect("direct TryRng")
    );
    assert_eq!(ref_pcg32.state(), direct_pcg32.state());

    let mut direct_pcg64 = Pcg64::seed_from_u64(101);
    let mut boxed_pcg64 = Box::new(Pcg64::seed_from_u64(101));
    assert_eq!(
        draw_try_sample(&mut boxed_pcg64).expect("boxed TryRng"),
        draw_try_sample(&mut direct_pcg64).expect("direct TryRng")
    );
    assert_eq!(boxed_pcg64.state(), direct_pcg64.state());

    // 4. SeedableRng::try_from_rng and try_fork with TryRng sources.
    let mut parent_a = Pcg32::seed_from_u64(1234);
    let mut parent_b = Pcg32::seed_from_u64(1234);
    let mut child_try = Pcg64Mcg::try_from_rng(&mut parent_a).expect("infallible try_from_rng");
    let mut child_infallible = Pcg64Mcg::from_rng(&mut parent_b);
    assert_eq!(
        child_try.try_next_u64().expect("child_try"),
        child_infallible.next_u64()
    );

    let mut fork_a = Pcg32::seed_from_u64(5678);
    let mut fork_b = Pcg32::seed_from_u64(5678);
    let mut forked_try = fork_a.try_fork().expect("infallible try_fork");
    let mut forked_infallible = fork_b.fork();
    assert_eq!(
        forked_try.try_next_u32().expect("forked_try"),
        forked_infallible.next_u32()
    );

    // Fallible TryRng propagates Err through SeedableRng::try_from_rng.
    let mut empty_budget = BudgetTryRng::new(Pcg32::seed_from_u64(1), 0);
    let seed_err = Pcg64::try_from_rng(&mut empty_budget).unwrap_err();
    assert_eq!(seed_err, BudgetExhaustedError);

    // 5. Custom fallible TryRng wrapper and UnwrapErr adapter.
    let mut ref_pcg = Pcg32::seed_from_u64(2026);
    let mut budgeted = BudgetTryRng::new(Pcg32::seed_from_u64(2026), 3);
    let (b32, b64, bbytes) = draw_try_sample(&mut budgeted).expect("3 calls fit budget");
    assert_eq!(budgeted.remaining_calls(), 0);
    assert_eq!(b32, ref_pcg.next_u32());
    assert_eq!(b64, ref_pcg.next_u64());
    let mut expected_bytes = [0u8; 11];
    ref_pcg.fill_bytes(&mut expected_bytes);
    assert_eq!(bbytes, expected_bytes);

    assert_eq!(budgeted.try_next_u32(), Err(BudgetExhaustedError));
    assert_eq!(budgeted.try_next_u64(), Err(BudgetExhaustedError));
    let mut untouched = [0xAAu8; 4];
    assert_eq!(
        budgeted.try_fill_bytes(&mut untouched),
        Err(BudgetExhaustedError)
    );
    assert_eq!(untouched, [0xAAu8; 4]);

    // UnwrapErr adapts fallible TryRng into infallible Rng and panics on Err.
    let mut ref_unwrap = Pcg32::seed_from_u64(404);
    let mut wrapped = UnwrapErr(BudgetTryRng::new(Pcg32::seed_from_u64(404), 1));
    assert_eq!(wrapped.next_u32(), ref_unwrap.next_u32());
    let prev_hook = panic::take_hook();
    panic::set_hook(Box::new(|_| {}));
    let panic_res = panic::catch_unwind(panic::AssertUnwindSafe(|| {
        let _ = wrapped.next_u32();
    }));
    panic::set_hook(prev_hook);
    assert!(
        panic_res.is_err(),
        "UnwrapErr must panic when underlying TryRng returns Err"
    );

    println!("ALL rand_pcg::rand_core::TryRng CONTRACTS PASSED");
}

오리진 시더

익명