CodeSampleX

Пример

golang.org/x/text v0.31.0: charmap.ISO8859_1

Проверенный пример — golang golang.org/x/text v0.31.0: charmap.ISO8859_1. Контракт выполнен на go 1.26 · linux debian/x64 · docker и пройден.

sha256:8254fa1e73515931ca59846d8308f92e3f88190d83d3842ad0eacc1983d9587a

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

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

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

Основа свидетельства
Подписанный контракт пройден
Квитанции проверки
1
Ключи подписи, собравшие его
1
Заявленная среда go 1.26 linux 24 · ubuntu · glibc 2.39 x64 go 1.26 go go 1

Среды запусков проверки

Окружение Контракт Этапы Запуск
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 golang.org/x/text/encoding/charmap.ISO8859_1 in pkg:golang/golang.org/x/text@v0.31.0
Пакеты
Символы
  • golang.org/x/text/encoding/charmap.ISO8859_1
Окружение
go 1.26.6
Создан
2026-10-11T16:32:41Z

Контракт

  1. charmap.ISO8859_1 has encoding name "ISO 8859-1"
  2. charmap.ISO8859_1 NewEncoder encodes ASCII and Latin-1 Unicode strings into ISO-8859-1 byte slices
  3. charmap.ISO8859_1 NewDecoder decodes ISO-8859-1 byte slices into UTF-8 strings
  4. charmap.ISO8859_1 EncodeRune and DecodeByte map valid code points accurately
  5. charmap.ISO8859_1 detects out-of-repertoire runes and returns errors or replacement byte
  6. charmap.ISO8859_1 streaming Reader and Writer correctly transform data streams

Файлы

  • PROMPT.md
  • csx.json
  • go.mod
  • go.sum
  • main.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/text/encoding/charmap.ISO8859_1 in pkg:golang/golang.org/x/text@v0.31.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/golang.org/x/text@v0.31.0
Demonstrate these symbols/APIs:
  - golang.org/x/text/encoding/charmap.ISO8859_1

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:cddb5af13bbd37ba45bce576c6fae28da6468b9821617ca0d6616fc02abefdff","contract":["charmap.ISO8859_1 has encoding name \"ISO 8859-1\"","charmap.ISO8859_1 NewEncoder encodes ASCII and Latin-1 Unicode strings into ISO-8859-1 byte slices","charmap.ISO8859_1 NewDecoder decodes ISO-8859-1 byte slices into UTF-8 strings","charmap.ISO8859_1 EncodeRune and DecodeByte map valid code points accurately","charmap.ISO8859_1 detects out-of-repertoire runes and returns errors or replacement byte","charmap.ISO8859_1 streaming Reader and Writer correctly transform data streams"],"goal":"verify golang.org/x/text/encoding/charmap.ISO8859_1 in pkg:golang/golang.org/x/text@v0.31.0","kind":"HOW","packages":["pkg:golang/golang.org/x/text@v0.31.0"],"schemaVersion":1,"symbols":["golang.org/x/text/encoding/charmap.ISO8859_1"]},"contractCommand":["go","run","./test"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"golang","language":"go","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"go","packageManagerVersion":"1.26.6","runtime":"go","runtimeVersion":"1.26.6","schemaVersion":1},"license":"MIT-0","packages":["pkg:golang/golang.org/x/text@v0.31.0"],"schemaVersion":1,"subject":"pkg:golang/golang.org/x/text@v0.31.0","symbols":["golang.org/x/text/encoding/charmap.ISO8859_1"],"verifierAdapter":"golang@1"}
go.mod
module sample

go 1.26.6

require golang.org/x/text v0.31.0
go.sum
golang.org/x/text v0.31.0 h1:aC8ghyu4JhP8VojJ2lEHBnochRno1sgL6nEi9WGFGMM=
golang.org/x/text v0.31.0/go.mod h1:tKRAlv61yKIjGGHX/4tP1LTbc13YSec1pxVEWXzfoeM=
main.go
package main

import (
	"bytes"
	"fmt"
	"io"

	"golang.org/x/text/encoding/charmap"
)

func main() {
	// Demonstrating golang.org/x/text/encoding/charmap.ISO8859_1
	fmt.Printf("Encoding name: %s\n", charmap.ISO8859_1.String())

	// 1. Encoding a UTF-8 string to ISO-8859-1 bytes
	encoder := charmap.ISO8859_1.NewEncoder()
	text := "Café & Résumé (ASCII + Latin-1)"
	encodedBytes, err := encoder.Bytes([]byte(text))
	if err != nil {
		fmt.Printf("Encoding error: %v\n", err)
		return
	}
	fmt.Printf("Encoded length: %d bytes (raw bytes: %x)\n", len(encodedBytes), encodedBytes)

	// 2. Decoding ISO-8859-1 bytes back to UTF-8
	decoder := charmap.ISO8859_1.NewDecoder()
	decodedText, err := decoder.String(string(encodedBytes))
	if err != nil {
		fmt.Printf("Decoding error: %v\n", err)
		return
	}
	fmt.Printf("Decoded string: %s\n", decodedText)

	// 3. Single rune encoding and byte decoding
	r := 'é' // U+00E9
	b, ok := charmap.ISO8859_1.EncodeRune(r)
	if ok {
		fmt.Printf("Rune '%c' encoded to byte 0x%02x\n", r, b)
	}
	decodedRune := charmap.ISO8859_1.DecodeByte(b)
	fmt.Printf("Byte 0x%02x decoded to rune '%c'\n", b, decodedRune)

	// 4. Handling unsupported runes outside ISO-8859-1 repertoire
	euroRune := '€' // U+20AC is not in ISO 8859-1
	euroByte, ok := charmap.ISO8859_1.EncodeRune(euroRune)
	fmt.Printf("Euro rune '%c' in ISO-8859-1: ok=%v, byte=0x%02x\n", euroRune, ok, euroByte)

	// 5. Streaming conversion using Reader and Writer
	isoStream := []byte("Streamed: El Ni\xf1o")
	reader := decoder.Reader(bytes.NewReader(isoStream))
	streamedResult, err := io.ReadAll(reader)
	if err != nil {
		fmt.Printf("Stream read error: %v\n", err)
		return
	}
	fmt.Printf("Streamed decoded text: %s\n", string(streamedResult))

	var outBuf bytes.Buffer
	writer := encoder.Writer(&outBuf)
	_, err = writer.Write([]byte("Written stream: Voilà!"))
	if err != nil {
		fmt.Printf("Stream write error: %v\n", err)
		return
	}
	fmt.Printf("Buffer output length: %d bytes (raw: %x)\n", outBuf.Len(), outBuf.Bytes())

	fmt.Println("golang.org/x/text/encoding/charmap.ISO8859_1 demonstration complete.")
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify golang.org/x/text/encoding/charmap.ISO8859_1 in pkg:golang/golang.org/x/text@v0.31.0",
  "kind": "HOW",
  "packages": [
    "pkg:golang/golang.org/x/text@v0.31.0"
  ],
  "symbols": [
    "golang.org/x/text/encoding/charmap.ISO8859_1"
  ]
}
test/contract.go
package main

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

	"golang.org/x/text/encoding/charmap"
)

func main() {
	// Assertion 1: charmap.ISO8859_1 has encoding name "ISO 8859-1"
	{
		name := charmap.ISO8859_1.String()
		if name != "ISO 8859-1" {
			fmt.Fprintf(os.Stderr, "assertion 1 failed: expected name 'ISO 8859-1', got '%s'\n", name)
			os.Exit(1)
		}
	}

	// Assertion 2: charmap.ISO8859_1 NewEncoder encodes ASCII and Latin-1 Unicode strings into ISO-8859-1 byte slices
	{
		encoder := charmap.ISO8859_1.NewEncoder()
		if encoder == nil {
			fmt.Fprintf(os.Stderr, "assertion 2 failed: NewEncoder returned nil\n")
			os.Exit(1)
		}

		utf8Input := "Café 100%"
		expectedBytes := []byte{0x43, 0x61, 0x66, 0xe9, 0x20, 0x31, 0x30, 0x30, 0x25}

		encodedBytes, err := encoder.Bytes([]byte(utf8Input))
		if err != nil {
			fmt.Fprintf(os.Stderr, "assertion 2 failed: Bytes returned error: %v\n", err)
			os.Exit(1)
		}
		if !bytes.Equal(encodedBytes, expectedBytes) {
			fmt.Fprintf(os.Stderr, "assertion 2 failed: expected %x, got %x\n", expectedBytes, encodedBytes)
			os.Exit(1)
		}

		encodedStr, err := encoder.String(utf8Input)
		if err != nil {
			fmt.Fprintf(os.Stderr, "assertion 2 failed: String returned error: %v\n", err)
			os.Exit(1)
		}
		if encodedStr != string(expectedBytes) {
			fmt.Fprintf(os.Stderr, "assertion 2 failed: String output mismatch\n")
			os.Exit(1)
		}
	}

	// Assertion 3: charmap.ISO8859_1 NewDecoder decodes ISO-8859-1 byte slices into UTF-8 strings
	{
		decoder := charmap.ISO8859_1.NewDecoder()
		if decoder == nil {
			fmt.Fprintf(os.Stderr, "assertion 3 failed: NewDecoder returned nil\n")
			os.Exit(1)
		}

		isoBytes := []byte{0x43, 0x61, 0x66, 0xe9, 0x20, 0x31, 0x30, 0x30, 0x25}
		expectedUTF8 := "Café 100%"

		decodedBytes, err := decoder.Bytes(isoBytes)
		if err != nil {
			fmt.Fprintf(os.Stderr, "assertion 3 failed: Bytes returned error: %v\n", err)
			os.Exit(1)
		}
		if string(decodedBytes) != expectedUTF8 {
			fmt.Fprintf(os.Stderr, "assertion 3 failed: expected %s, got %s\n", expectedUTF8, string(decodedBytes))
			os.Exit(1)
		}

		decodedStr, err := decoder.String(string(isoBytes))
		if err != nil {
			fmt.Fprintf(os.Stderr, "assertion 3 failed: String returned error: %v\n", err)
			os.Exit(1)
		}
		if decodedStr != expectedUTF8 {
			fmt.Fprintf(os.Stderr, "assertion 3 failed: expected %s, got %s\n", expectedUTF8, decodedStr)
			os.Exit(1)
		}
	}

	// Assertion 4: charmap.ISO8859_1 EncodeRune and DecodeByte map valid code points accurately
	{
		testCases := []struct {
			r rune
			b byte
		}{
			{'A', 0x41},
			{'~', 0x7e},
			{'©', 0xa9},
			{'é', 0xe9},
			{'ü', 0xfc},
			{'ÿ', 0xff},
		}

		for _, tc := range testCases {
			b, ok := charmap.ISO8859_1.EncodeRune(tc.r)
			if !ok {
				fmt.Fprintf(os.Stderr, "assertion 4 failed: EncodeRune('%c') reported ok=false\n", tc.r)
				os.Exit(1)
			}
			if b != tc.b {
				fmt.Fprintf(os.Stderr, "assertion 4 failed: EncodeRune('%c') expected 0x%02x, got 0x%02x\n", tc.r, tc.b, b)
				os.Exit(1)
			}

			decRune := charmap.ISO8859_1.DecodeByte(tc.b)
			if decRune != tc.r {
				fmt.Fprintf(os.Stderr, "assertion 4 failed: DecodeByte(0x%02x) expected '%c', got '%c'\n", tc.b, tc.r, decRune)
				os.Exit(1)
			}
		}
	}

	// Assertion 5: charmap.ISO8859_1 detects out-of-repertoire runes and returns errors or replacement byte
	{
		euro := '€' // U+20AC is not in ISO 8859-1
		b, ok := charmap.ISO8859_1.EncodeRune(euro)
		if ok {
			fmt.Fprintf(os.Stderr, "assertion 5 failed: EncodeRune('%c') should report ok=false\n", euro)
			os.Exit(1)
		}
		if b != 0x1a {
			fmt.Fprintf(os.Stderr, "assertion 5 failed: EncodeRune('%c') replacement byte expected 0x1a, got 0x%02x\n", euro, b)
			os.Exit(1)
		}

		encoder := charmap.ISO8859_1.NewEncoder()
		_, err := encoder.Bytes([]byte("Price: 10€"))
		if err == nil {
			fmt.Fprintf(os.Stderr, "assertion 5 failed: expected error encoding out-of-repertoire rune '€'\n")
			os.Exit(1)
		}
	}

	// Assertion 6: charmap.ISO8859_1 streaming Reader and Writer correctly transform data streams
	{
		isoBytes := []byte{0xe9, 0xfc} // "éü" in ISO-8859-1
		reader := charmap.ISO8859_1.NewDecoder().Reader(bytes.NewReader(isoBytes))
		streamedUTF8, err := io.ReadAll(reader)
		if err != nil {
			fmt.Fprintf(os.Stderr, "assertion 6 failed: Reader read error: %v\n", err)
			os.Exit(1)
		}
		if string(streamedUTF8) != "éü" {
			fmt.Fprintf(os.Stderr, "assertion 6 failed: Reader output expected 'éü', got '%s'\n", string(streamedUTF8))
			os.Exit(1)
		}

		var buf bytes.Buffer
		writer := charmap.ISO8859_1.NewEncoder().Writer(&buf)
		n, err := writer.Write([]byte("éü"))
		if err != nil {
			fmt.Fprintf(os.Stderr, "assertion 6 failed: Writer write error: %v\n", err)
			os.Exit(1)
		}
		if n != len([]byte("éü")) {
			fmt.Fprintf(os.Stderr, "assertion 6 failed: Writer returned n=%d, expected %d\n", n, len([]byte("éü")))
			os.Exit(1)
		}
		if !bytes.Equal(buf.Bytes(), isoBytes) {
			fmt.Fprintf(os.Stderr, "assertion 6 failed: Writer output expected %x, got %x\n", isoBytes, buf.Bytes())
			os.Exit(1)
		}
	}

	fmt.Println("All contract assertions passed successfully.")
}

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

аноним