CodeSampleX

샘플

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

검증된 샘플 — golang google.golang.org/protobuf v1.35.1: anypb.UnmarshalTo. go 1.26 · linux alpine/x64 · docker에서 contract를 실행해 통과했습니다.

sha256:d02387d444ca1033fdbdbb3f680958d712f268132d4226ec5ff2f78fdebb8049

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

실행 증거

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

증거 기준
서명된 컨트랙트 통과
검증 영수증
1
빌드한 서명 키
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-27

케이스

HOW
목표
verify google.golang.org/protobuf/types/known/anypb.UnmarshalTo in pkg:golang/google.golang.org/protobuf@v1.35.1
패키지
심벌
  • google.golang.org/protobuf/types/known/anypb.UnmarshalTo
생성일
2026-08-27T10:36:39Z

컨트랙트

  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

파일

  • 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 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")
}

오리진 시더

익명