CodeSampleX

Пример

github.com/klauspost/compress v1.19.1: zlib.NewWriterLevelDict

Проверенный пример — golang github.com/klauspost/compress v1.19.1: zlib.NewWriterLevelDict. Контракт выполнен на go 1.26 · linux debian/x64 · docker и…

sha256:9d2c51d5f1bead9426665ae285d46fb9cacea35aaced5e95d60d02813bbffd73

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

Свидетельства выполнения

Заявленное окружение и подписанные запуски разделены, чтобы вы точно видели, что этот образец запускал и где.

Основа свидетельства
Подписанный контракт пройден
Квитанции проверки
1
Ключи подписи, собравшие его
1
Заявленная среда linux 24 · ubuntu · glibc 2.39 x64 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-10-11

Кейс

HOW
Цель
verify github.com/klauspost/compress/zlib.NewWriterLevelDict in pkg:golang/github.com/klauspost/compress@v1.19.1
Пакеты
Символы
  • github.com/klauspost/compress/zlib.NewWriterLevelDict
Создан
2026-10-11T07:30:41Z

Контракт

  1. zlib.NewWriterLevelDict initializes a Writer with specified compression level and dictionary
  2. zlib.NewWriterLevelDict produces compressed data successfully decompressed using the matching dictionary
  3. zlib.NewWriterLevelDict requires the identical dictionary during decompression and fails when omitted or mismatched
  4. zlib.NewWriterLevelDict accepts a nil dictionary behaving equivalent to standard compression
  5. zlib.NewWriterLevelDict returns an error when given an invalid compression level

Файлы

  • PROMPT.md
  • csx.json
  • go.mod
  • go.sum
  • spec.json
  • test/contract.go
  • zlib_dict.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 github.com/klauspost/compress/zlib.NewWriterLevelDict in pkg:golang/github.com/klauspost/compress@v1.19.1
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/github.com/klauspost/compress@v1.19.1
Demonstrate these symbols/APIs:
  - github.com/klauspost/compress/zlib.NewWriterLevelDict

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:4d36a079a9db467a39c8c96251bfdae4f783b6f9a0a208deaf1bbaac8d9b7718","contract":["zlib.NewWriterLevelDict initializes a Writer with specified compression level and dictionary","zlib.NewWriterLevelDict produces compressed data successfully decompressed using the matching dictionary","zlib.NewWriterLevelDict requires the identical dictionary during decompression and fails when omitted or mismatched","zlib.NewWriterLevelDict accepts a nil dictionary behaving equivalent to standard compression","zlib.NewWriterLevelDict returns an error when given an invalid compression level"],"goal":"verify github.com/klauspost/compress/zlib.NewWriterLevelDict in pkg:golang/github.com/klauspost/compress@v1.19.1","kind":"HOW","packages":["pkg:golang/github.com/klauspost/compress@v1.19.1"],"schemaVersion":1,"symbols":["github.com/klauspost/compress/zlib.NewWriterLevelDict"]},"contractCommand":["go","run","./test"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"golang","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"go","schemaVersion":1},"license":"MIT-0","packages":["pkg:golang/github.com/klauspost/compress@v1.19.1"],"schemaVersion":1,"subject":"pkg:golang/github.com/klauspost/compress@v1.19.1","symbols":["github.com/klauspost/compress/zlib.NewWriterLevelDict"],"verifierAdapter":"golang@1"}
go.mod
module sample

go 1.26.6

require github.com/klauspost/compress v1.19.1
go.sum
github.com/klauspost/compress v1.19.1 h1:VsB4HPswih7mmZ8WleSFQ75c/Ui1M4trX5oAsJnhSlk=
github.com/klauspost/compress v1.19.1/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ=
spec.json
{
  "schemaVersion": 1,
  "goal": "verify github.com/klauspost/compress/zlib.NewWriterLevelDict in pkg:golang/github.com/klauspost/compress@v1.19.1",
  "kind": "HOW",
  "packages": [
    "pkg:golang/github.com/klauspost/compress@v1.19.1"
  ],
  "symbols": [
    "github.com/klauspost/compress/zlib.NewWriterLevelDict"
  ]
}
test/contract.go
package main

import (
	"bytes"
	"errors"
	"fmt"
	"io"
	"os"

	"github.com/klauspost/compress/zlib"
	"sample"
)

func main() {
	dict := []byte("frequently-occurring-common-dictionary-string-pattern")

	// Assertion 1: zlib.NewWriterLevelDict initializes a Writer with specified compression level and dictionary
	var buf1 bytes.Buffer
	w1, err := sample.NewDictWriter(&buf1, zlib.BestSpeed, dict)
	if err != nil {
		fmt.Fprintf(os.Stderr, "FAIL assertion 1: NewWriterLevelDict returned error: %v\n", err)
		os.Exit(1)
	}
	if w1 == nil {
		fmt.Fprintf(os.Stderr, "FAIL assertion 1: NewWriterLevelDict returned nil writer\n")
		os.Exit(1)
	}

	// Assertion 2: zlib.NewWriterLevelDict produces compressed data successfully decompressed using the matching dictionary
	payload := []byte("frequently-occurring-common-dictionary-string-pattern and some unique payload data for verification")
	compressed, err := sample.CompressWithDict(payload, zlib.BestCompression, dict)
	if err != nil {
		fmt.Fprintf(os.Stderr, "FAIL assertion 2: CompressWithDict failed: %v\n", err)
		os.Exit(1)
	}
	decompressed, err := sample.DecompressWithDict(compressed, dict)
	if err != nil {
		fmt.Fprintf(os.Stderr, "FAIL assertion 2: DecompressWithDict failed: %v\n", err)
		os.Exit(1)
	}
	if !bytes.Equal(decompressed, payload) {
		fmt.Fprintf(os.Stderr, "FAIL assertion 2: payload mismatch: got %q, expected %q\n", decompressed, payload)
		os.Exit(1)
	}

	// Assertion 3: zlib.NewWriterLevelDict requires the identical dictionary during decompression and fails when omitted or mismatched
	rNoDict, err := zlib.NewReader(bytes.NewReader(compressed))
	if err == nil {
		_, readErr := io.ReadAll(rNoDict)
		rNoDict.Close()
		if readErr == nil {
			fmt.Fprintf(os.Stderr, "FAIL assertion 3: expected decompression error without dictionary, got success\n")
			os.Exit(1)
		}
	} else if !errors.Is(err, zlib.ErrDictionary) {
		// NewReader itself may return ErrDictionary directly
	}

	wrongDict := []byte("different-dictionary-string-pattern-mismatch")
	rWrongDict, err := zlib.NewReaderDict(bytes.NewReader(compressed), wrongDict)
	if err == nil {
		_, readErr := io.ReadAll(rWrongDict)
		rWrongDict.Close()
		if readErr == nil {
			fmt.Fprintf(os.Stderr, "FAIL assertion 3: expected decompression error with mismatched dictionary, got success\n")
			os.Exit(1)
		}
	}

	// Assertion 4: zlib.NewWriterLevelDict accepts a nil dictionary behaving equivalent to standard compression
	nilDictCompressed, err := sample.CompressWithDict(payload, zlib.DefaultCompression, nil)
	if err != nil {
		fmt.Fprintf(os.Stderr, "FAIL assertion 4: CompressWithDict with nil dict failed: %v\n", err)
		os.Exit(1)
	}
	rStandard, err := zlib.NewReader(bytes.NewReader(nilDictCompressed))
	if err != nil {
		fmt.Fprintf(os.Stderr, "FAIL assertion 4: NewReader failed on nil dict compressed data: %v\n", err)
		os.Exit(1)
	}
	nilDictDecompressed, err := io.ReadAll(rStandard)
	rStandard.Close()
	if err != nil {
		fmt.Fprintf(os.Stderr, "FAIL assertion 4: ReadAll failed on nil dict compressed data: %v\n", err)
		os.Exit(1)
	}
	if !bytes.Equal(nilDictDecompressed, payload) {
		fmt.Fprintf(os.Stderr, "FAIL assertion 4: nil dict payload mismatch: got %q, expected %q\n", nilDictDecompressed, payload)
		os.Exit(1)
	}

	// Assertion 5: zlib.NewWriterLevelDict returns an error when given an invalid compression level
	var bufBad bytes.Buffer
	_, errBadLevel := sample.NewDictWriter(&bufBad, 999, dict)
	if errBadLevel == nil {
		fmt.Fprintf(os.Stderr, "FAIL assertion 5: expected error for invalid compression level 999, got nil\n")
		os.Exit(1)
	}

	fmt.Println("PASS: github.com/klauspost/compress/zlib.NewWriterLevelDict contract verified")
}
zlib_dict.go
package sample

import (
	"bytes"
	"io"

	"github.com/klauspost/compress/zlib"
)

// NewDictWriter wraps zlib.NewWriterLevelDict to create a zlib writer with a custom compression level and preset dictionary.
func NewDictWriter(w io.Writer, level int, dict []byte) (*zlib.Writer, error) {
	return zlib.NewWriterLevelDict(w, level, dict)
}

// CompressWithDict compresses input data using zlib.NewWriterLevelDict with the specified compression level and dictionary.
func CompressWithDict(data []byte, level int, dict []byte) ([]byte, error) {
	var buf bytes.Buffer
	w, err := zlib.NewWriterLevelDict(&buf, level, dict)
	if err != nil {
		return nil, err
	}
	if _, err := w.Write(data); err != nil {
		return nil, err
	}
	if err := w.Close(); err != nil {
		return nil, err
	}
	return buf.Bytes(), nil
}

// DecompressWithDict decompresses data that was compressed with a preset dictionary using zlib.NewReaderDict.
func DecompressWithDict(compressed []byte, dict []byte) ([]byte, error) {
	r, err := zlib.NewReaderDict(bytes.NewReader(compressed), dict)
	if err != nil {
		return nil, err
	}
	defer r.Close()
	return io.ReadAll(r)
}

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

аноним