CodeSampleX

샘플

golang.org/x/exp v0.0.0-20251023183803-a4bb9ffd2546: rand

검증된 샘플 — golang golang.org/x/exp v0.0.0-20251023183803-a4bb9ffd2546: rand. go 1.26 · linux debian/x64 · docker에서 contract를 실행해 통과했습니다.

sha256:5c98829f9199a27a672474002362f7590784bd99cb3a02679199c2c094d3e243

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

실행 증거

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

증거 기준
서명된 컨트랙트 통과
검증 영수증
1
빌드한 서명 키
1
선언된 환경 linux 24 · ubuntu · glibc 2.39 x64 go go

검증 실행 환경

환경 컨트랙트 단계 실행일
go 1.26 · linux debian/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · golang@1golang:1.26@sha256:e30143be198a…
2026-09-01

케이스

HOW
목표
verify golang.org/x/exp/rand in pkg:golang/golang.org/x/exp@v0.0.0-20251023183803-a4bb9ffd2546
패키지
심벌
  • golang.org/x/exp/rand
생성일
2026-09-01T10:09:15Z

컨트랙트

  1. rand.New with rand.NewSource initializes a deterministic PRNG
  2. rand.Intn returns non-negative values strictly bounded by n
  3. rand.Float64 returns float values in half-open interval [0.0, 1.0)
  4. rand.Perm returns a slice containing a valid permutation of [0, n)
  5. rand.Shuffle randomly permutes elements in-place with a custom swap function
  6. rand.PCGSource supports binary state serialization via MarshalBinary and UnmarshalBinary

파일

  • PROMPT.md
  • csx.json
  • go.mod
  • go.sum
  • randsample.go
  • spec.json
  • test/contract.go

소스 아티팩트 내려받기 (tar.gz)

소스

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 golang.org/x/exp/rand in pkg:golang/golang.org/x/exp@v0.0.0-20251023183803-a4bb9ffd2546
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/golang.org/x/exp@v0.0.0-20251023183803-a4bb9ffd2546
Demonstrate these symbols/APIs:
  - golang.org/x/exp/rand
Constraints:
  - executionContext: node
Required runtime conditions:
  - ecosystem: npm
  - language: javascript
  - moduleSystem: cjs
  - packageManager: npm
  - 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:26dd7816e89e2be5a0ef9a221d6b0d33e67c0d36ccdfd512ff4c8c5f30ddab52","contract":["rand.New with rand.NewSource initializes a deterministic PRNG","rand.Intn returns non-negative values strictly bounded by n","rand.Float64 returns float values in half-open interval [0.0, 1.0)","rand.Perm returns a slice containing a valid permutation of [0, n)","rand.Shuffle randomly permutes elements in-place with a custom swap function","rand.PCGSource supports binary state serialization via MarshalBinary and UnmarshalBinary"],"goal":"verify golang.org/x/exp/rand in pkg:golang/golang.org/x/exp@v0.0.0-20251023183803-a4bb9ffd2546","kind":"HOW","packages":["pkg:golang/golang.org/x/exp@v0.0.0-20251023183803-a4bb9ffd2546"],"schemaVersion":1,"symbols":["golang.org/x/exp/rand"]},"contractCommand":["go","run","./test"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"golang","language":"go","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"go","schemaVersion":1},"license":"MIT-0","packages":["pkg:golang/golang.org/x/exp@v0.0.0-20251023183803-a4bb9ffd2546"],"schemaVersion":1,"subject":"pkg:golang/golang.org/x/exp@v0.0.0-20251023183803-a4bb9ffd2546","symbols":["golang.org/x/exp/rand"],"verifierAdapter":"golang@1"}
go.mod
module example.com/randsample

go 1.24.0

require golang.org/x/exp v0.0.0-20251023183803-a4bb9ffd2546
go.sum
golang.org/x/exp v0.0.0-20251023183803-a4bb9ffd2546 h1:mgKeJMpvi0yx/sU5GsxQ7p6s2wtOnGAHZWCHUM4KGzY=
golang.org/x/exp v0.0.0-20251023183803-a4bb9ffd2546/go.mod h1:j/pmGrbnkbPtQfxEe5D0VQhZC6qKbfKifgD0oM7sR70=
randsample.go
package randsample

import (
	"golang.org/x/exp/rand"
)

// NewDeterministicRand creates a new Rand instance with a seeded Source.
func NewDeterministicRand(seed uint64) *rand.Rand {
	src := rand.NewSource(seed)
	return rand.New(src)
}

// GenerateBoundedInts generates a slice of pseudo-random ints in [0, max).
func GenerateBoundedInts(r *rand.Rand, count int, max int) []int {
	res := make([]int, count)
	for i := 0; i < count; i++ {
		res[i] = r.Intn(max)
	}
	return res
}

// ShuffleStrings randomizes the order of the given string slice in place.
func ShuffleStrings(r *rand.Rand, items []string) {
	r.Shuffle(len(items), func(i, j int) {
		items[i], items[j] = items[j], items[i]
	})
}

// ClonePCGSource clones a PCGSource by serializing and deserializing its state.
func ClonePCGSource(src *rand.PCGSource) (*rand.PCGSource, error) {
	data, err := src.MarshalBinary()
	if err != nil {
		return nil, err
	}
	clone := new(rand.PCGSource)
	if err := clone.UnmarshalBinary(data); err != nil {
		return nil, err
	}
	return clone, nil
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify golang.org/x/exp/rand in pkg:golang/golang.org/x/exp@v0.0.0-20251023183803-a4bb9ffd2546",
  "kind": "HOW",
  "packages": [
    "pkg:golang/golang.org/x/exp@v0.0.0-20251023183803-a4bb9ffd2546"
  ],
  "symbols": [
    "golang.org/x/exp/rand"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm",
    "runtime": "node@22.23.2"
  }
}
test/contract.go
package main

import (
	"bytes"
	"fmt"
	"os"

	"example.com/randsample"
	"golang.org/x/exp/rand"
)

func main() {
	// Assertion 1: rand.New with rand.NewSource initializes a deterministic PRNG
	r1 := randsample.NewDeterministicRand(42)
	r2 := randsample.NewDeterministicRand(42)

	v1_1 := r1.Uint64()
	v1_2 := r1.Intn(1000)
	v1_3 := r1.Float64()

	v2_1 := r2.Uint64()
	v2_2 := r2.Intn(1000)
	v2_3 := r2.Float64()

	if v1_1 != v2_1 || v1_2 != v2_2 || v1_3 != v2_3 {
		fmt.Fprintf(os.Stderr, "FAIL: seeded rand generators are not deterministic: (%d, %d, %f) vs (%d, %d, %f)\n",
			v1_1, v1_2, v1_3, v2_1, v2_2, v2_3)
		os.Exit(1)
	}

	// Assertion 2: rand.Intn returns non-negative values strictly bounded by n
	r := randsample.NewDeterministicRand(12345)
	bounded := randsample.GenerateBoundedInts(r, 500, 25)
	for idx, val := range bounded {
		if val < 0 || val >= 25 {
			fmt.Fprintf(os.Stderr, "FAIL: bounded int at %d out of bounds [0, 25): %d\n", idx, val)
			os.Exit(1)
		}
	}

	// Assertion 3: rand.Float64 returns float values in half-open interval [0.0, 1.0)
	for i := 0; i < 500; i++ {
		f := r.Float64()
		if f < 0.0 || f >= 1.0 {
			fmt.Fprintf(os.Stderr, "FAIL: Float64() produced out-of-range value: %f\n", f)
			os.Exit(1)
		}
	}

	// Assertion 4: rand.Perm returns a slice containing a valid permutation of [0, n)
	n := 10
	perm := r.Perm(n)
	if len(perm) != n {
		fmt.Fprintf(os.Stderr, "FAIL: Perm(%d) returned slice of length %d\n", n, len(perm))
		os.Exit(1)
	}
	seen := make([]bool, n)
	for _, val := range perm {
		if val < 0 || val >= n {
			fmt.Fprintf(os.Stderr, "FAIL: Perm value out of range: %d\n", val)
			os.Exit(1)
		}
		if seen[val] {
			fmt.Fprintf(os.Stderr, "FAIL: Perm returned duplicate value: %d\n", val)
			os.Exit(1)
		}
		seen[val] = true
	}
	for i, present := range seen {
		if !present {
			fmt.Fprintf(os.Stderr, "FAIL: Perm missing element: %d\n", i)
			os.Exit(1)
		}
	}

	// Assertion 5: rand.Shuffle randomly permutes elements in-place with a custom swap function
	items := []string{"apple", "banana", "cherry", "date", "elderberry", "fig", "grape"}
	origCopy := append([]string(nil), items...)
	randsample.ShuffleStrings(r, items)
	if len(items) != len(origCopy) {
		fmt.Fprintf(os.Stderr, "FAIL: Shuffle changed slice length\n")
		os.Exit(1)
	}
	// Verify multiset equality
	counts := make(map[string]int)
	for _, item := range origCopy {
		counts[item]++
	}
	for _, item := range items {
		counts[item]--
		if counts[item] < 0 {
			fmt.Fprintf(os.Stderr, "FAIL: Shuffle mutated elements unexpectedly: %s\n", item)
			os.Exit(1)
		}
	}

	// Assertion 6: rand.PCGSource supports binary state serialization via MarshalBinary and UnmarshalBinary
	pcg := new(rand.PCGSource)
	pcg.Seed(999)
	_ = pcg.Uint64() // advance state
	_ = pcg.Uint64()

	clone, err := randsample.ClonePCGSource(pcg)
	if err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: ClonePCGSource failed: %v\n", err)
		os.Exit(1)
	}

	state1, _ := pcg.MarshalBinary()
	state2, _ := clone.MarshalBinary()
	if !bytes.Equal(state1, state2) {
		fmt.Fprintf(os.Stderr, "FAIL: marshaled states do not match\n")
		os.Exit(1)
	}

	for i := 0; i < 10; i++ {
		origVal := pcg.Uint64()
		cloneVal := clone.Uint64()
		if origVal != cloneVal {
			fmt.Fprintf(os.Stderr, "FAIL: PCGSource clone generated different value at step %d: %d vs %d\n", i, origVal, cloneVal)
			os.Exit(1)
		}
	}

	fmt.Println("PASS: golang.org/x/exp/rand contract verified")
}

오리진 시더

익명