CodeSampleX

Beispiel

google.golang.org/protobuf v1.35.1: anypb.UnmarshalTo

Verifiziertes Beispiel für golang google.golang.org/protobuf v1.35.1: anypb.UnmarshalTo. Der Vertrag lief auf go 1.26 · linux alpine/x64 · docker und bestand.

sha256:d02387d444ca1033fdbdbb3f680958d712f268132d4226ec5ff2f78fdebb8049

Dieses Netzwerk bietet eine Sache: ein Sample, das baut. Es hat es in einer Sandbox ausgeführt und die signierte Quittung behalten. Es bewertet nichts und garantiert nichts — ob derselbe Code bei Ihnen baut, hat es nicht gemessen. Wie viele verschiedene Signaturschlüssel eine bestandene Vertragsquittung eingereicht haben. Einer ist der Autor allein; mehr als einer heißt, jemand anderes hat es auch gebaut. Ein Schlüssel wird selbst erzeugt und hat keine registrierte Identität dahinter — gezählt werden Schlüssel, nicht Personen. MIT-0

Ausführungsbelege

Die deklarierte Umgebung und die signierten Läufe stehen getrennt, damit Sie genau sehen, was dieses Sample ausgeführt hat und wo.

Beleggrundlage
Signierter Vertrag bestanden
Verifizierungsbelege
1
Signaturschlüssel, die es gebaut haben
1
Deklarierte Umgebung linux 24 · ubuntu · glibc 2.39 x64 go

Umgebungen der Verifizierungsläufe

Umgebung Contract Stufen Lauf
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

Fall

HOW
Ziel
verify google.golang.org/protobuf/types/known/anypb.UnmarshalTo in pkg:golang/google.golang.org/protobuf@v1.35.1
Pakete
Symbole
  • google.golang.org/protobuf/types/known/anypb.UnmarshalTo
Erstellt
2026-08-27T10:36:39Z

Contract

  1. anypb.UnmarshalTo unpacks Any payload into the matching destination proto.Message
  2. anypb.UnmarshalTo resets destination message fields before unmarshaling
  3. anypb.UnmarshalTo returns error when destination message type mismatches packed type
  4. anypb.UnmarshalTo with proto.UnmarshalOptions respects options during unmarshaling
  5. Any.UnmarshalTo method unmarshals underlying message into target without explicit options

Dateien

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

Quellartefakt herunterladen (tar.gz)

Quelltext

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 google.golang.org/protobuf/types/known/anypb.UnmarshalTo in pkg:golang/google.golang.org/protobuf@v1.35.1
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/google.golang.org/protobuf@v1.35.1
Demonstrate these symbols/APIs:
  - google.golang.org/protobuf/types/known/anypb.UnmarshalTo

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:d1623e17c86fdcd09e56db36f140b6504e105be5bb67cae003a67a2e39c48ad4","contract":["anypb.UnmarshalTo unpacks Any payload into the matching destination proto.Message","anypb.UnmarshalTo resets destination message fields before unmarshaling","anypb.UnmarshalTo returns error when destination message type mismatches packed type","anypb.UnmarshalTo with proto.UnmarshalOptions respects options during unmarshaling","Any.UnmarshalTo method unmarshals underlying message into target without explicit options"],"goal":"verify google.golang.org/protobuf/types/known/anypb.UnmarshalTo in pkg:golang/google.golang.org/protobuf@v1.35.1","kind":"HOW","packages":["pkg:golang/google.golang.org/protobuf@v1.35.1"],"schemaVersion":1,"symbols":["google.golang.org/protobuf/types/known/anypb.UnmarshalTo"]},"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.35.1"],"schemaVersion":1,"subject":"pkg:golang/google.golang.org/protobuf@v1.35.1","symbols":["google.golang.org/protobuf/types/known/anypb.UnmarshalTo"],"verifierAdapter":"golang@1"}
go.mod
module example.com/sample

go 1.22

require google.golang.org/protobuf v1.35.1
go.sum
github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU=
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/protobuf v1.35.1 h1:m3LfL6/Ca+fqnjnlqQXNpFPABW1UD7mjh8KO2mKFytA=
google.golang.org/protobuf v1.35.1/go.mod h1:9fA7Ob0pmnwhb644+1+CVWFRbNajQ6iRojtC/QF5bRE=
main.go
package main

import (
	"fmt"
	"time"

	"google.golang.org/protobuf/proto"
	"google.golang.org/protobuf/types/known/anypb"
	"google.golang.org/protobuf/types/known/durationpb"
	"google.golang.org/protobuf/types/known/timestamppb"
)

// EventContainer demonstrates storing and unpacking polymorphic protobuf messages via Any.
type EventContainer struct {
	Name    string
	Payload *anypb.Any
}

// NewEvent packs a proto.Message into an EventContainer.
func NewEvent(name string, msg proto.Message) (*EventContainer, error) {
	anyMsg, err := anypb.New(msg)
	if err != nil {
		return nil, fmt.Errorf("failed to pack message into Any: %w", err)
	}
	return &EventContainer{
		Name:    name,
		Payload: anyMsg,
	}, nil
}

// UnpackInto extracts the wrapped message into the provided target destination.
func (e *EventContainer) UnpackInto(dst proto.Message) error {
	if e.Payload == nil {
		return fmt.Errorf("payload is nil")
	}
	return anypb.UnmarshalTo(e.Payload, dst, proto.UnmarshalOptions{})
}

func main() {
	// Create an event wrapping a Timestamp message
	now := time.Now().UTC()
	tsMsg := timestamppb.New(now)
	event, err := NewEvent("audit_event", tsMsg)
	if err != nil {
		fmt.Printf("Error creating event: %v\n", err)
		return
	}

	// Unpack using anypb.UnmarshalTo
	var decodedTs timestamppb.Timestamp
	if err := event.UnpackInto(&decodedTs); err != nil {
		fmt.Printf("Error unpacking timestamp: %v\n", err)
		return
	}

	fmt.Printf("Unpacked event '%s': timestamp=%v\n", event.Name, decodedTs.AsTime())

	// Create an event wrapping a Duration message
	durMsg := durationpb.New(42 * time.Second)
	durEvent, err := NewEvent("timeout_event", durMsg)
	if err != nil {
		fmt.Printf("Error creating duration event: %v\n", err)
		return
	}

	var decodedDur durationpb.Duration
	if err := durEvent.UnpackInto(&decodedDur); err != nil {
		fmt.Printf("Error unpacking duration: %v\n", err)
		return
	}

	fmt.Printf("Unpacked event '%s': duration=%v\n", durEvent.Name, decodedDur.AsDuration())
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify google.golang.org/protobuf/types/known/anypb.UnmarshalTo in pkg:golang/google.golang.org/protobuf@v1.35.1",
  "kind": "HOW",
  "packages": [
    "pkg:golang/google.golang.org/protobuf@v1.35.1"
  ],
  "symbols": [
    "google.golang.org/protobuf/types/known/anypb.UnmarshalTo"
  ]
}
test/contract.go
package main

import (
	"fmt"
	"os"
	"time"

	"google.golang.org/protobuf/proto"
	"google.golang.org/protobuf/types/known/anypb"
	"google.golang.org/protobuf/types/known/durationpb"
	"google.golang.org/protobuf/types/known/structpb"
	"google.golang.org/protobuf/types/known/timestamppb"
)

func main() {
	// Assertion 1: anypb.UnmarshalTo unpacks Any payload into the matching destination proto.Message
	{
		orig := timestamppb.New(time.Date(2026, 8, 27, 10, 0, 0, 0, time.UTC))
		anyMsg, err := anypb.New(orig)
		if err != nil {
			fmt.Fprintf(os.Stderr, "FAIL: anypb.New failed: %v\n", err)
			os.Exit(1)
		}

		var dst timestamppb.Timestamp
		if err := anypb.UnmarshalTo(anyMsg, &dst, proto.UnmarshalOptions{}); err != nil {
			fmt.Fprintf(os.Stderr, "FAIL: anypb.UnmarshalTo failed: %v\n", err)
			os.Exit(1)
		}

		if !proto.Equal(orig, &dst) {
			fmt.Fprintf(os.Stderr, "FAIL: unmarshaled message %v does not equal original %v\n", dst, orig)
			os.Exit(1)
		}
		if !dst.AsTime().Equal(orig.AsTime()) {
			fmt.Fprintf(os.Stderr, "FAIL: unmarshaled timestamp %v does not match original %v\n", dst.AsTime(), orig.AsTime())
			os.Exit(1)
		}
	}

	// Assertion 2: anypb.UnmarshalTo resets destination message fields before unmarshaling
	{
		orig := &durationpb.Duration{
			Seconds: 300,
			Nanos:   0,
		}
		anyMsg, err := anypb.New(orig)
		if err != nil {
			fmt.Fprintf(os.Stderr, "FAIL: anypb.New failed: %v\n", err)
			os.Exit(1)
		}

		// Pre-populate destination with old values
		dst := &durationpb.Duration{
			Seconds: 9999,
			Nanos:   8888,
		}
		if err := anypb.UnmarshalTo(anyMsg, dst, proto.UnmarshalOptions{}); err != nil {
			fmt.Fprintf(os.Stderr, "FAIL: anypb.UnmarshalTo failed: %v\n", err)
			os.Exit(1)
		}

		if dst.Seconds != 300 || dst.Nanos != 0 {
			fmt.Fprintf(os.Stderr, "FAIL: anypb.UnmarshalTo did not reset destination fields, got Seconds=%d Nanos=%d\n", dst.Seconds, dst.Nanos)
			os.Exit(1)
		}
	}

	// Assertion 3: anypb.UnmarshalTo returns error when destination message type mismatches packed type
	{
		dur := &durationpb.Duration{Seconds: 60}
		anyMsg, err := anypb.New(dur)
		if err != nil {
			fmt.Fprintf(os.Stderr, "FAIL: anypb.New failed: %v\n", err)
			os.Exit(1)
		}

		var wrongDst timestamppb.Timestamp
		if err := anypb.UnmarshalTo(anyMsg, &wrongDst, proto.UnmarshalOptions{}); err == nil {
			fmt.Fprintf(os.Stderr, "FAIL: expected type mismatch error when unmarshaling Duration into Timestamp, got nil\n")
			os.Exit(1)
		}
	}

	// Assertion 4: anypb.UnmarshalTo with proto.UnmarshalOptions respects options during unmarshaling
	{
		st, err := structpb.NewStruct(map[string]any{
			"key":   "value",
			"count": float64(10),
		})
		if err != nil {
			fmt.Fprintf(os.Stderr, "FAIL: structpb.NewStruct failed: %v\n", err)
			os.Exit(1)
		}

		anyMsg, err := anypb.New(st)
		if err != nil {
			fmt.Fprintf(os.Stderr, "FAIL: anypb.New failed: %v\n", err)
			os.Exit(1)
		}

		var dst structpb.Struct
		opts := proto.UnmarshalOptions{
			DiscardUnknown: true,
		}
		if err := anypb.UnmarshalTo(anyMsg, &dst, opts); err != nil {
			fmt.Fprintf(os.Stderr, "FAIL: anypb.UnmarshalTo with custom options failed: %v\n", err)
			os.Exit(1)
		}

		if dst.Fields["key"].GetStringValue() != "value" {
			fmt.Fprintf(os.Stderr, "FAIL: struct field value mismatch\n")
			os.Exit(1)
		}
	}

	// Assertion 5: Any.UnmarshalTo method unmarshals underlying message into target without explicit options
	{
		dur := &durationpb.Duration{Seconds: 120, Nanos: 500}
		anyMsg, err := anypb.New(dur)
		if err != nil {
			fmt.Fprintf(os.Stderr, "FAIL: anypb.New failed: %v\n", err)
			os.Exit(1)
		}

		var dst durationpb.Duration
		if err := anyMsg.UnmarshalTo(&dst); err != nil {
			fmt.Fprintf(os.Stderr, "FAIL: anyMsg.UnmarshalTo method failed: %v\n", err)
			os.Exit(1)
		}

		if !proto.Equal(dur, &dst) {
			fmt.Fprintf(os.Stderr, "FAIL: anyMsg.UnmarshalTo method unpacked message %v does not equal original %v\n", dst, dur)
			os.Exit(1)
		}
	}

	fmt.Println("PASS: all anypb.UnmarshalTo contract assertions passed")
}

Ursprungs-Seeder

anonym