CodeSampleX

Ejemplo

google.golang.org/protobuf v1.31.0: Serialize and parse Protocol Buffers text format messages using prototext Marshal, Unmarshal, and options

Muestra verificada para golang google.golang.org/protobuf v1.31.0: Serialize and parse Protocol Buffers text format messages using prototext Marshal…

sha256:5721207c7102e85d6ec19cdd15d18d37b2d797f1db1bcaa6b5ef727614e913f5

Esta red ofrece una sola cosa: una muestra que compila. La ejecutó en un sandbox y guardó el recibo firmado. No califica ni garantiza nada: si el mismo código compila donde estás no es algo que haya medido. Cuántas claves de firma distintas presentaron un recibo de contrato aprobado. Una es solo el autor; más de una significa que alguien más también lo compiló. Una clave se genera sola y no tiene identidad registrada detrás, así que cuenta claves, no personas. MIT-0

Evidencia de ejecución

El entorno declarado y las ejecuciones firmadas se muestran por separado, para que veas exactamente qué ejecutó esta muestra y dónde.

Base de evidencia
Contrato firmado aprobado
Recibos de verificación
2
Claves de firma que lo compilaron
1
Entorno declarado linux 24 · ubuntu · glibc 2.39 x64 go

Entornos de las ejecuciones de verificación

Entorno Contrato Etapas Ejecución
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-27
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

Caso

HOW
Objetivo
Serialize and parse Protocol Buffers text format messages using prototext Marshal, Unmarshal, and options
Paquetes
Símbolos
  • google.golang.org/protobuf/encoding/prototext.Marshal
  • google.golang.org/protobuf/encoding/prototext.MarshalOptions
  • google.golang.org/protobuf/encoding/prototext.Unmarshal
  • google.golang.org/protobuf/encoding/prototext.UnmarshalOptions
Creado
2026-08-27T17:54:36Z

Contrato

  1. prototext.Marshal serializes a proto.Message into Protocol Buffers text format bytes and roundtrips with prototext.Unmarshal
  2. prototext.MarshalOptions with Multiline set to false formats message into a single-line compact representation
  3. prototext.MarshalOptions with EmitASCII set to true escapes non-ASCII Unicode characters
  4. prototext.MarshalOptions.MarshalAppend appends formatted text format bytes to an existing byte buffer
  5. prototext.Format directly returns text format string for a proto.Message
  6. prototext.Unmarshal rejects malformed text format input with a syntax error
  7. prototext.Unmarshal by default rejects unknown field names, whereas prototext.UnmarshalOptions with DiscardUnknown set to true silently ignores them
  8. prototext.Marshal on nil proto.Message returns empty bytes without error
  9. prototext.Marshal on empty proto.Message returns empty bytes without error

Archivos

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

Descargar el artefacto de código fuente (tar.gz)

Código fuente

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: Serialize and parse Protocol Buffers text format messages using prototext Marshal, Unmarshal, and options
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/google.golang.org/protobuf@v1.31.0
Demonstrate these symbols/APIs:
  - google.golang.org/protobuf/encoding/prototext.Marshal
  - google.golang.org/protobuf/encoding/prototext.MarshalOptions
  - google.golang.org/protobuf/encoding/prototext.Unmarshal
  - google.golang.org/protobuf/encoding/prototext.UnmarshalOptions

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:c2667b05fa67fcb25250a0819f78bb44139581d6b15ba192facbd204cedd4877","contract":["prototext.Marshal serializes a proto.Message into Protocol Buffers text format bytes and roundtrips with prototext.Unmarshal","prototext.MarshalOptions with Multiline set to false formats message into a single-line compact representation","prototext.MarshalOptions with EmitASCII set to true escapes non-ASCII Unicode characters","prototext.MarshalOptions.MarshalAppend appends formatted text format bytes to an existing byte buffer","prototext.Format directly returns text format string for a proto.Message","prototext.Unmarshal rejects malformed text format input with a syntax error","prototext.Unmarshal by default rejects unknown field names, whereas prototext.UnmarshalOptions with DiscardUnknown set to true silently ignores them","prototext.Marshal on nil proto.Message returns empty bytes without error","prototext.Marshal on empty proto.Message returns empty bytes without error"],"goal":"Serialize and parse Protocol Buffers text format messages using prototext Marshal, Unmarshal, and options","kind":"HOW","packages":["pkg:golang/google.golang.org/protobuf@v1.31.0"],"schemaVersion":1,"symbols":["google.golang.org/protobuf/encoding/prototext.Marshal","google.golang.org/protobuf/encoding/prototext.MarshalOptions","google.golang.org/protobuf/encoding/prototext.Unmarshal","google.golang.org/protobuf/encoding/prototext.UnmarshalOptions"]},"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/google.golang.org/protobuf@v1.31.0"],"schemaVersion":1,"subject":"pkg:golang/google.golang.org/protobuf@v1.31.0","symbols":["google.golang.org/protobuf/encoding/prototext.Marshal","google.golang.org/protobuf/encoding/prototext.MarshalOptions","google.golang.org/protobuf/encoding/prototext.Unmarshal","google.golang.org/protobuf/encoding/prototext.UnmarshalOptions"],"verifierAdapter":"golang@1"}
go.mod
module sample-protobuf-prototext

go 1.23.0

require google.golang.org/protobuf v1.36.12
go.sum
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
google.golang.org/protobuf v1.36.12 h1:pJOKDDOyeXErUroCihFAd5LQuwXBSpVnKGrj5o/fwxc=
google.golang.org/protobuf v1.36.12/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
main.go
package main

import (
	"fmt"
	"time"

	"google.golang.org/protobuf/encoding/prototext"
	"google.golang.org/protobuf/types/known/structpb"
	"google.golang.org/protobuf/types/known/timestamppb"
	"google.golang.org/protobuf/types/known/wrapperspb"
)

func main() {
	// 1. Marshal a protobuf message into text format
	msg := wrapperspb.String("Hello, Protobuf Text!")
	textData, err := prototext.Marshal(msg)
	if err != nil {
		fmt.Printf("prototext marshal error: %v\n", err)
		return
	}
	fmt.Printf("Marshaled text format:\n%s\n", string(textData))

	// 2. Unmarshal text format back into protobuf message
	var restored wrapperspb.StringValue
	if err := prototext.Unmarshal(textData, &restored); err != nil {
		fmt.Printf("prototext unmarshal error: %v\n", err)
		return
	}
	fmt.Printf("Unmarshaled value: %s\n", restored.GetValue())

	// 3. Use MarshalOptions for single-line compact representation
	compactOpts := prototext.MarshalOptions{Multiline: false}
	compactBytes, err := compactOpts.Marshal(msg)
	if err != nil {
		fmt.Printf("compact marshal error: %v\n", err)
		return
	}
	fmt.Printf("Compact text format: %s\n", string(compactBytes))

	// 4. Use MarshalOptions to format a Timestamp
	ts := timestamppb.New(time.Date(2026, 8, 27, 12, 0, 0, 0, time.UTC))
	formattedTS := prototext.Format(ts)
	fmt.Printf("Formatted timestamp:\n%s\n", formattedTS)

	// 5. Use UnmarshalOptions to discard unknown fields
	dataWithUnknown := []byte("value: \"CodeSampleX\"\nextra_unknown_field: 42\n")
	discardOpts := prototext.UnmarshalOptions{DiscardUnknown: true}
	var valueFromUnknown wrapperspb.StringValue
	if err := discardOpts.Unmarshal(dataWithUnknown, &valueFromUnknown); err != nil {
		fmt.Printf("unmarshal with discard unknown error: %v\n", err)
		return
	}
	fmt.Printf("Parsed with unknown field discarded: %s\n", valueFromUnknown.GetValue())

	// 6. Format dynamic structpb
	st, err := structpb.NewStruct(map[string]any{
		"name":    "prototext-sample",
		"version": 1,
	})
	if err != nil {
		fmt.Printf("structpb error: %v\n", err)
		return
	}
	fmt.Printf("Struct text:\n%s\n", prototext.Format(st))
}
spec.json
{
  "schemaVersion": 1,
  "goal": "Serialize and parse Protocol Buffers text format messages using prototext Marshal, Unmarshal, and options",
  "kind": "HOW",
  "packages": [
    "pkg:golang/google.golang.org/protobuf@v1.31.0"
  ],
  "symbols": [
    "google.golang.org/protobuf/encoding/prototext.Marshal",
    "google.golang.org/protobuf/encoding/prototext.MarshalOptions",
    "google.golang.org/protobuf/encoding/prototext.Unmarshal",
    "google.golang.org/protobuf/encoding/prototext.UnmarshalOptions"
  ]
}
test/contract.go
package main

import (
	"bytes"
	"fmt"
	"os"
	"strings"

	"google.golang.org/protobuf/encoding/prototext"
	"google.golang.org/protobuf/proto"
	"google.golang.org/protobuf/types/known/emptypb"
	"google.golang.org/protobuf/types/known/structpb"
	"google.golang.org/protobuf/types/known/wrapperspb"
)

func main() {
	// Assertion 1: prototext.Marshal serializes a proto.Message into Protocol Buffers text format bytes and roundtrips with prototext.Unmarshal
	{
		msg := wrapperspb.String("test-payload")
		data, err := prototext.Marshal(msg)
		if err != nil {
			fmt.Fprintf(os.Stderr, "FAIL: prototext.Marshal failed: %v\n", err)
			os.Exit(1)
		}
		if len(data) == 0 {
			fmt.Fprintln(os.Stderr, "FAIL: prototext.Marshal produced empty output for non-empty message")
			os.Exit(1)
		}

		var restored wrapperspb.StringValue
		if err := prototext.Unmarshal(data, &restored); err != nil {
			fmt.Fprintf(os.Stderr, "FAIL: prototext.Unmarshal failed: %v\n", err)
			os.Exit(1)
		}
		if !proto.Equal(msg, &restored) {
			fmt.Fprintf(os.Stderr, "FAIL: restored message not equal to original: got %v, want %v\n", &restored, msg)
			os.Exit(1)
		}
	}

	// Assertion 2: prototext.MarshalOptions with Multiline set to false formats message into a single-line compact representation
	{
		msg := wrapperspb.String("compact-representation")
		opts := prototext.MarshalOptions{Multiline: false}
		data, err := opts.Marshal(msg)
		if err != nil {
			fmt.Fprintf(os.Stderr, "FAIL: prototext.MarshalOptions.Marshal failed: %v\n", err)
			os.Exit(1)
		}
		if strings.Contains(string(data), "\n") {
			fmt.Fprintf(os.Stderr, "FAIL: Multiline: false produced newlines: %q\n", string(data))
			os.Exit(1)
		}

		var restored wrapperspb.StringValue
		if err := prototext.Unmarshal(data, &restored); err != nil {
			fmt.Fprintf(os.Stderr, "FAIL: unmarshaling compact representation failed: %v\n", err)
			os.Exit(1)
		}
		if restored.GetValue() != "compact-representation" {
			fmt.Fprintf(os.Stderr, "FAIL: restored value mismatch: got %q, want %q\n", restored.GetValue(), "compact-representation")
			os.Exit(1)
		}
	}

	// Assertion 3: prototext.MarshalOptions with EmitASCII set to true escapes non-ASCII Unicode characters
	{
		msg := wrapperspb.String("Hello \u4e16\u754c")
		opts := prototext.MarshalOptions{EmitASCII: true}
		data, err := opts.Marshal(msg)
		if err != nil {
			fmt.Fprintf(os.Stderr, "FAIL: EmitASCII marshal failed: %v\n", err)
			os.Exit(1)
		}
		for i, b := range data {
			if b > 127 {
				fmt.Fprintf(os.Stderr, "FAIL: non-ASCII byte 0x%x at position %d in EmitASCII output\n", b, i)
				os.Exit(1)
			}
		}

		var restored wrapperspb.StringValue
		if err := prototext.Unmarshal(data, &restored); err != nil {
			fmt.Fprintf(os.Stderr, "FAIL: unmarshaling escaped ASCII failed: %v\n", err)
			os.Exit(1)
		}
		if restored.GetValue() != "Hello \u4e16\u754c" {
			fmt.Fprintf(os.Stderr, "FAIL: restored unicode string mismatch: got %q\n", restored.GetValue())
			os.Exit(1)
		}
	}

	// Assertion 4: prototext.MarshalOptions.MarshalAppend appends formatted text format bytes to an existing byte buffer
	{
		prefix := []byte("# Header Comment\n")
		msg := wrapperspb.Int32(12345)
		opts := prototext.MarshalOptions{}

		appended, err := opts.MarshalAppend(prefix, msg)
		if err != nil {
			fmt.Fprintf(os.Stderr, "FAIL: MarshalAppend failed: %v\n", err)
			os.Exit(1)
		}
		if !bytes.HasPrefix(appended, prefix) {
			fmt.Fprintln(os.Stderr, "FAIL: MarshalAppend did not preserve prefix buffer")
			os.Exit(1)
		}

		expectedBody, err := opts.Marshal(msg)
		if err != nil {
			fmt.Fprintf(os.Stderr, "FAIL: opts.Marshal failed: %v\n", err)
			os.Exit(1)
		}
		if !bytes.Equal(appended[len(prefix):], expectedBody) {
			fmt.Fprintf(os.Stderr, "FAIL: MarshalAppend appended payload mismatch: got %q, want %q\n", appended[len(prefix):], expectedBody)
			os.Exit(1)
		}
	}

	// Assertion 5: prototext.Format directly returns text format string for a proto.Message
	{
		st, err := structpb.NewStruct(map[string]any{
			"key": "val",
		})
		if err != nil {
			fmt.Fprintf(os.Stderr, "FAIL: structpb.NewStruct failed: %v\n", err)
			os.Exit(1)
		}

		formatted := prototext.Format(st)
		if !strings.Contains(formatted, "key") || !strings.Contains(formatted, "val") {
			fmt.Fprintf(os.Stderr, "FAIL: prototext.Format output does not contain expected fields: %q\n", formatted)
			os.Exit(1)
		}
	}

	// Assertion 6: prototext.Unmarshal rejects malformed text format input with a syntax error
	{
		malformed := []byte("invalid { text : proto")
		var dst wrapperspb.StringValue
		err := prototext.Unmarshal(malformed, &dst)
		if err == nil {
			fmt.Fprintln(os.Stderr, "FAIL: prototext.Unmarshal succeeded on malformed input")
			os.Exit(1)
		}
	}

	// Assertion 7: prototext.Unmarshal by default rejects unknown field names, whereas prototext.UnmarshalOptions with DiscardUnknown set to true silently ignores them
	{
		unknownPayload := []byte("value: \"known-value\"\nunknown_attribute: 999\n")
		var dstDefault wrapperspb.StringValue
		errDefault := prototext.Unmarshal(unknownPayload, &dstDefault)
		if errDefault == nil {
			fmt.Fprintln(os.Stderr, "FAIL: prototext.Unmarshal expected error for unknown field, got nil")
			os.Exit(1)
		}

		opts := prototext.UnmarshalOptions{DiscardUnknown: true}
		var dstDiscard wrapperspb.StringValue
		errDiscard := opts.Unmarshal(unknownPayload, &dstDiscard)
		if errDiscard != nil {
			fmt.Fprintf(os.Stderr, "FAIL: UnmarshalOptions with DiscardUnknown failed: %v\n", errDiscard)
			os.Exit(1)
		}
		if dstDiscard.GetValue() != "known-value" {
			fmt.Fprintf(os.Stderr, "FAIL: value mismatch after DiscardUnknown: got %q, want %q\n", dstDiscard.GetValue(), "known-value")
			os.Exit(1)
		}
	}

	// Assertion 8: prototext.Marshal on nil proto.Message returns empty bytes without error
	{
		out, err := prototext.Marshal(nil)
		if err != nil {
			fmt.Fprintf(os.Stderr, "FAIL: prototext.Marshal on nil message returned error: %v\n", err)
			os.Exit(1)
		}
		if len(out) != 0 {
			fmt.Fprintf(os.Stderr, "FAIL: expected 0 bytes for nil message, got %d bytes\n", len(out))
			os.Exit(1)
		}
	}

	// Assertion 9: prototext.Marshal on empty proto.Message returns empty bytes without error
	{
		empty := &emptypb.Empty{}
		out, err := prototext.Marshal(empty)
		if err != nil {
			fmt.Fprintf(os.Stderr, "FAIL: prototext.Marshal on empty message returned error: %v\n", err)
			os.Exit(1)
		}
		if len(out) != 0 {
			fmt.Fprintf(os.Stderr, "FAIL: expected 0 bytes for empty message, got %d bytes\n", len(out))
			os.Exit(1)
		}
	}

	fmt.Println("PASS: google.golang.org/protobuf/encoding/prototext contract passed")
}

Seeder de origen

anónimo