CodeSampleX

샘플

github.com/rs/xid v1.6.0: marshal unmarshal xid with JSON text SQL database driver scan value and sort IDs

검증된 샘플 — golang github.com/rs/xid v1.6.0: marshal unmarshal xid with JSON text SQL database driver scan value and sort IDs. go 1.26 · linux alpine/x64 …

sha256:87e63a928f9806ba5d3cf2ae29005187e77cd4e88a03fd1e179ceef701e27ff2

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

실행 증거

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

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

검증 실행 환경

환경 컨트랙트 단계 실행일
go 1.26 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · golang@1golang:1.26-alpine@sha256:28d89ee9cc0f…
2026-08-26
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-07

케이스

HOW
목표
marshal unmarshal xid with JSON text SQL database driver scan value and sort IDs
패키지
심벌
  • github.com/rs/xid.ID.Compare
  • github.com/rs/xid.ID.MarshalJSON
  • github.com/rs/xid.ID.Scan
  • github.com/rs/xid.ID.UnmarshalJSON
  • github.com/rs/xid.ID.Value
  • github.com/rs/xid.Sort
생성일
2026-08-26T12:07:55Z

컨트랙트

  1. id.MarshalJSON serializes xid.ID as a 20-character base32 quoted JSON string
  2. id.UnmarshalJSON parses a valid JSON string into xid.ID and handles null as NilID
  3. id.Value returns the 20-character string representation implementing database/sql driver.Valuer
  4. id.Scan unmarshals string or byte representations into xid.ID and handles nil implementing sql.Scanner
  5. id.Compare returns -1, 0, or 1 based on lexicographical ordering of identifiers
  6. xid.Sort sorts a slice of xid.ID identifiers in ascending order

파일

  • PROMPT.md
  • csx.json
  • go.mod
  • go.sum
  • spec.json
  • test/contract_test.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: marshal unmarshal xid with JSON text SQL database driver scan value and sort IDs
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/github.com/rs/xid@v1.6.0
Demonstrate these symbols/APIs:
  - github.com/rs/xid.ID.Compare
  - github.com/rs/xid.ID.MarshalJSON
  - github.com/rs/xid.ID.Scan
  - github.com/rs/xid.ID.UnmarshalJSON
  - github.com/rs/xid.ID.Value
  - github.com/rs/xid.Sort

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:66608b10e2d6231ca2fa232f774ea98d38babe834d68fda8a615f9d4337b2b0f","contract":["id.MarshalJSON serializes xid.ID as a 20-character base32 quoted JSON string","id.UnmarshalJSON parses a valid JSON string into xid.ID and handles null as NilID","id.Value returns the 20-character string representation implementing database/sql driver.Valuer","id.Scan unmarshals string or byte representations into xid.ID and handles nil implementing sql.Scanner","id.Compare returns -1, 0, or 1 based on lexicographical ordering of identifiers","xid.Sort sorts a slice of xid.ID identifiers in ascending order"],"goal":"marshal unmarshal xid with JSON text SQL database driver scan value and sort IDs","kind":"HOW","packages":["pkg:golang/github.com/rs/xid@v1.6.0"],"schemaVersion":1,"symbols":["github.com/rs/xid.ID.Compare","github.com/rs/xid.ID.MarshalJSON","github.com/rs/xid.ID.Scan","github.com/rs/xid.ID.UnmarshalJSON","github.com/rs/xid.ID.Value","github.com/rs/xid.Sort"]},"contractCommand":["go","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/rs/xid@v1.6.0"],"schemaVersion":1,"subject":"pkg:golang/github.com/rs/xid@v1.6.0","symbols":["github.com/rs/xid.ID.Compare","github.com/rs/xid.ID.MarshalJSON","github.com/rs/xid.ID.Scan","github.com/rs/xid.ID.UnmarshalJSON","github.com/rs/xid.ID.Value","github.com/rs/xid.Sort"],"verifierAdapter":"golang@1"}
go.mod
module example.com/xid-sample

go 1.22

require github.com/rs/xid v1.6.0
go.sum
github.com/rs/xid v1.6.0 h1:fV591PaemRlL6JfRxGDEPl69wICngIQ3shQtzfy2gxU=
github.com/rs/xid v1.6.0/go.mod h1:7XoLgs4eV+QndskICGsho+ADou8ySMSjJKDIan90Nz0=
spec.json
{
  "schemaVersion": 1,
  "goal": "marshal unmarshal xid with JSON text SQL database driver scan value and sort IDs",
  "kind": "HOW",
  "packages": [
    "pkg:golang/github.com/rs/xid@v1.6.0"
  ],
  "symbols": [
    "github.com/rs/xid.ID.Compare",
    "github.com/rs/xid.ID.MarshalJSON",
    "github.com/rs/xid.ID.Scan",
    "github.com/rs/xid.ID.UnmarshalJSON",
    "github.com/rs/xid.ID.Value",
    "github.com/rs/xid.Sort"
  ]
}
test/contract_test.go
package test

import (
	"database/sql/driver"
	"encoding/json"
	"fmt"
	"testing"
	"time"

	"github.com/rs/xid"
)

func TestJSONMarshalingAndUnmarshaling(t *testing.T) {
	id := xid.New()
	expectedJSON := fmt.Sprintf("%q", id.String())

	marshaled, err := id.MarshalJSON()
	if err != nil {
		t.Fatalf("MarshalJSON failed: %v", err)
	}
	if string(marshaled) != expectedJSON {
		t.Fatalf("MarshalJSON returned %s, expected %s", string(marshaled), expectedJSON)
	}

	// Test struct with xid.ID field JSON serialization
	type Document struct {
		ID   xid.ID `json:"id"`
		Name string `json:"name"`
	}

	doc := Document{
		ID:   id,
		Name: "sample-item",
	}

	data, err := json.Marshal(doc)
	if err != nil {
		t.Fatalf("json.Marshal failed: %v", err)
	}

	var decoded Document
	if err := json.Unmarshal(data, &decoded); err != nil {
		t.Fatalf("json.Unmarshal failed: %v", err)
	}

	if decoded.ID != id {
		t.Fatalf("decoded ID %v does not match original %v", decoded.ID, id)
	}
	if decoded.Name != doc.Name {
		t.Fatalf("decoded Name %q does not match original %q", decoded.Name, doc.Name)
	}

	// Test UnmarshalJSON with invalid JSON and invalid lengths
	var invalidID xid.ID
	if err := invalidID.UnmarshalJSON([]byte(`"not-a-valid-xid-string"`)); err == nil {
		t.Fatal("expected error unmarshaling invalid xid string, got nil")
	}
	if err := invalidID.UnmarshalJSON([]byte(`12345`)); err == nil {
		t.Fatal("expected error unmarshaling non-string JSON, got nil")
	}
	if err := invalidID.UnmarshalJSON([]byte(`null`)); err != nil {
		t.Fatalf("UnmarshalJSON with null returned error: %v", err)
	}
	if !invalidID.IsNil() {
		t.Fatalf("UnmarshalJSON with null should result in NilID, got %v", invalidID)
	}
}

func TestSQLDriverValuerAndScanner(t *testing.T) {
	id := xid.New()

	// Test driver.Valuer interface
	val, err := id.Value()
	if err != nil {
		t.Fatalf("Value() failed: %v", err)
	}
	valStr, ok := val.(string)
	if !ok {
		t.Fatalf("expected Value() to return string, got %T", val)
	}
	if valStr != id.String() {
		t.Fatalf("Value() returned %q, expected %q", valStr, id.String())
	}

	// Nil ID Value
	var nilID xid.ID
	nilVal, err := nilID.Value()
	if err != nil {
		t.Fatalf("nilID.Value() failed: %v", err)
	}
	if nilVal != nil {
		t.Logf("nilID.Value() returned %v", nilVal)
	}

	// Test sql.Scanner interface
	var scannedFromString xid.ID
	if err := scannedFromString.Scan(id.String()); err != nil {
		t.Fatalf("Scan(string) failed: %v", err)
	}
	if scannedFromString != id {
		t.Fatalf("scanned from string %v does not match original %v", scannedFromString, id)
	}

	var scannedFromByteString xid.ID
	if err := scannedFromByteString.Scan([]byte(id.String())); err != nil {
		t.Fatalf("Scan([]byte string) failed: %v", err)
	}
	if scannedFromByteString != id {
		t.Fatalf("scanned from byte string %v does not match original %v", scannedFromByteString, id)
	}

	var scannedNil xid.ID
	if err := scannedNil.Scan(nil); err != nil {
		t.Fatalf("Scan(nil) failed: %v", err)
	}
	if !scannedNil.IsNil() {
		t.Fatalf("Scan(nil) expected IsNil() true, got %v", scannedNil)
	}

	// Invalid Scan inputs
	var errTarget xid.ID
	if err := errTarget.Scan(12345); err == nil {
		t.Fatal("expected error scanning integer, got nil")
	}
	if err := errTarget.Scan("invalid-length"); err == nil {
		t.Fatal("expected error scanning invalid string, got nil")
	}
	if err := errTarget.Scan([]byte("too-short")); err == nil {
		t.Fatal("expected error scanning short byte slice, got nil")
	}

	// Ensure driver.Valuer is implemented
	var _ driver.Valuer = id
}

func TestComparisonAndSorting(t *testing.T) {
	now := time.Now().Truncate(time.Second)
	t1 := now.Add(-10 * time.Second)
	t2 := now
	t3 := now.Add(10 * time.Second)

	id1 := xid.NewWithTime(t1)
	id2 := xid.NewWithTime(t2)
	id3 := xid.NewWithTime(t3)

	// Test Compare
	if cmp := id1.Compare(id2); cmp >= 0 {
		t.Fatalf("expected id1.Compare(id2) < 0, got %d", cmp)
	}
	if cmp := id2.Compare(id1); cmp <= 0 {
		t.Fatalf("expected id2.Compare(id1) > 0, got %d", cmp)
	}
	if cmp := id1.Compare(id1); cmp != 0 {
		t.Fatalf("expected id1.Compare(id1) == 0, got %d", cmp)
	}

	// Test Sort
	ids := []xid.ID{id3, id1, id2}
	xid.Sort(ids)

	if ids[0] != id1 || ids[1] != id2 || ids[2] != id3 {
		t.Fatalf("xid.Sort failed: expected [%v, %v, %v], got [%v, %v, %v]", id1, id2, id3, ids[0], ids[1], ids[2])
	}
}

오리진 시더

익명