CodeSampleX

샘플

google.golang.org/protobuf v1.36.11: proto.Size

검증된 샘플 — golang google.golang.org/protobuf v1.36.11: proto.Size. go 1.26 · linux debian/x64 · docker에서 contract를 실행해 통과했습니다: proto.Size returns 0 for nil…

sha256:74c8ddd95a3b1d89e491c4f6f296e1b4e589c9431b0ac77c4cf59e37f380c2d6

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

실행 증거

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

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

검증 실행 환경

환경 컨트랙트 단계 실행일
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-02

케이스

HOW
목표
verify proto.Size in pkg:golang/google.golang.org/protobuf@v1.36.11
패키지
심벌
  • proto.Size
생성일
2026-09-02T08:41:00Z

컨트랙트

  1. proto.Size returns 0 for nil proto.Message or nil typed pointers
  2. proto.Size returns 0 for zero-value proto3 messages with only default fields
  3. proto.Size returns exact wire-format byte size matching proto.Marshal length for populated scalar messages
  4. proto.Size computes exact wire size for complex messages with maps and nested structures like structpb.Struct and anypb.Any
  5. proto.Size enables buffer pre-allocation for proto.MarshalAppend without slice reallocation

파일

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

소스 아티팩트 내려받기 (tar.gz)

소스

NOTES.md
# Protocol Buffers proto.Size Wire Size Calculation Semantics

A search for `proto.Size` in `pkg:golang/google.golang.org/protobuf@v1.36.11` returned `NO_SAFE_MATCH`.

This sample verifies the wire size calculation behavior of `proto.Size`.

## Observed Behavior

1. **Nil Pointer / Interface Handling**:
   - `proto.Size(nil)` returns 0.
   - Calling `proto.Size` on a nil typed pointer (e.g. `(*durationpb.Duration)(nil)`) returns 0.

2. **Default / Zero-value Proto3 Messages**:
   - Messages containing only default zero values (e.g. `&durationpb.Duration{}`, `&emptypb.Empty{}`) serialize to 0 bytes on wire in proto3.
   - `proto.Size` correctly returns 0 without allocating.

3. **Parity with `proto.Marshal`**:
   - For populated scalar, struct, wrapper, and well-known types (`timestamppb.Timestamp`, `durationpb.Duration`, `wrapperspb.String`), `proto.Size(m)` matches `len(proto.Marshal(m))` exactly.

4. **Complex Nested and Dynamic Structures**:
   - For nested structures, map values, and dynamically typed messages (`structpb.Struct`, `anypb.Any`), `proto.Size` computes the exact serialized length.

5. **Buffer Pre-allocation**:
   - `proto.Size(m)` allows pre-allocating a buffer `make([]byte, 0, proto.Size(m))` for `proto.MarshalOptions{}.MarshalAppend(buf, m)` without undergoing buffer reallocation during marshaling.
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 proto.Size in pkg:golang/google.golang.org/protobuf@v1.36.11
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/google.golang.org/protobuf@v1.36.11
Demonstrate these symbols/APIs:
  - proto.Size

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:b9ccd78ae7f012f7cc245f690b4d55857d0bd5c4ef79c7a27f3b8fa52866e1e7","contract":["proto.Size returns 0 for nil proto.Message or nil typed pointers","proto.Size returns 0 for zero-value proto3 messages with only default fields","proto.Size returns exact wire-format byte size matching proto.Marshal length for populated scalar messages","proto.Size computes exact wire size for complex messages with maps and nested structures like structpb.Struct and anypb.Any","proto.Size enables buffer pre-allocation for proto.MarshalAppend without slice reallocation"],"goal":"verify proto.Size in pkg:golang/google.golang.org/protobuf@v1.36.11","kind":"HOW","packages":["pkg:golang/google.golang.org/protobuf@v1.36.11"],"schemaVersion":1,"symbols":["proto.Size"]},"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.36.11"],"schemaVersion":1,"subject":"pkg:golang/google.golang.org/protobuf@v1.36.11","symbols":["proto.Size"],"verifierAdapter":"golang@1"}
go.mod
module sample

go 1.23

require google.golang.org/protobuf v1.36.11
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.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
main.go
package main

import (
	"fmt"

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

// CalculateMessageSize returns the encoded wire-format byte size of a protobuf message.
func CalculateMessageSize(m proto.Message) int {
	return proto.Size(m)
}

func main() {
	d := &durationpb.Duration{
		Seconds: 120,
		Nanos:   500,
	}

	size := CalculateMessageSize(d)
	data, err := proto.Marshal(d)
	if err != nil {
		panic(err)
	}

	fmt.Printf("Duration wire size: %d bytes (marshaled len: %d bytes)\n", size, len(data))

	s, err := structpb.NewStruct(map[string]interface{}{
		"name":   "sample",
		"active": true,
		"count":  42,
	})
	if err != nil {
		panic(err)
	}

	structSize := CalculateMessageSize(s)
	sData, err := proto.Marshal(s)
	if err != nil {
		panic(err)
	}

	fmt.Printf("Struct wire size: %d bytes (marshaled len: %d bytes)\n", structSize, len(sData))
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify proto.Size in pkg:golang/google.golang.org/protobuf@v1.36.11",
  "kind": "HOW",
  "packages": [
    "pkg:golang/google.golang.org/protobuf@v1.36.11"
  ],
  "symbols": [
    "proto.Size"
  ]
}
test/contract.go
package main

import (
	"bytes"
	"fmt"
	"os"

	"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/emptypb"
	"google.golang.org/protobuf/types/known/structpb"
	"google.golang.org/protobuf/types/known/timestamppb"
	"google.golang.org/protobuf/types/known/wrapperspb"
)

func main() {
	// 1. proto.Size returns 0 for nil proto.Message or nil typed pointers
	{
		var nilMsg proto.Message
		if sz := proto.Size(nilMsg); sz != 0 {
			fmt.Fprintf(os.Stderr, "FAIL: expected proto.Size(nil) == 0, got %d\n", sz)
			os.Exit(1)
		}

		var nilDuration *durationpb.Duration
		if sz := proto.Size(nilDuration); sz != 0 {
			fmt.Fprintf(os.Stderr, "FAIL: expected proto.Size(nil typed pointer) == 0, got %d\n", sz)
			os.Exit(1)
		}

		var nilStruct *structpb.Struct
		if sz := proto.Size(nilStruct); sz != 0 {
			fmt.Fprintf(os.Stderr, "FAIL: expected proto.Size(nil structpb) == 0, got %d\n", sz)
			os.Exit(1)
		}
	}

	// 2. proto.Size returns 0 for zero-value proto3 messages with only default fields
	{
		emptyMsg := &emptypb.Empty{}
		emptyData, err := proto.Marshal(emptyMsg)
		if err != nil {
			fmt.Fprintf(os.Stderr, "FAIL: Marshal emptyMsg failed: %v\n", err)
			os.Exit(1)
		}
		if sz := proto.Size(emptyMsg); sz != 0 || len(emptyData) != 0 {
			fmt.Fprintf(os.Stderr, "FAIL: expected zero size for emptypb.Empty, got Size=%d, Marshal len=%d\n", sz, len(emptyData))
			os.Exit(1)
		}

		defaultDuration := &durationpb.Duration{}
		defaultData, err := proto.Marshal(defaultDuration)
		if err != nil {
			fmt.Fprintf(os.Stderr, "FAIL: Marshal defaultDuration failed: %v\n", err)
			os.Exit(1)
		}
		if sz := proto.Size(defaultDuration); sz != 0 || len(defaultData) != 0 {
			fmt.Fprintf(os.Stderr, "FAIL: expected zero size for default Duration, got Size=%d, Marshal len=%d\n", sz, len(defaultData))
			os.Exit(1)
		}
	}

	// 3. proto.Size returns exact wire-format byte size matching proto.Marshal length for populated scalar messages
	{
		dur := &durationpb.Duration{
			Seconds: 3600,
			Nanos:   500000,
		}
		durData, err := proto.Marshal(dur)
		if err != nil {
			fmt.Fprintf(os.Stderr, "FAIL: Marshal dur failed: %v\n", err)
			os.Exit(1)
		}
		if sz := proto.Size(dur); sz != len(durData) {
			fmt.Fprintf(os.Stderr, "FAIL: proto.Size mismatch for Duration: got %d, want %d\n", sz, len(durData))
			os.Exit(1)
		}

		ts := &timestamppb.Timestamp{
			Seconds: 1700000000,
			Nanos:   987654321,
		}
		tsData, err := proto.Marshal(ts)
		if err != nil {
			fmt.Fprintf(os.Stderr, "FAIL: Marshal Timestamp failed: %v\n", err)
			os.Exit(1)
		}
		if sz := proto.Size(ts); sz != len(tsData) {
			fmt.Fprintf(os.Stderr, "FAIL: proto.Size mismatch for Timestamp: got %d, want %d\n", sz, len(tsData))
			os.Exit(1)
		}

		strVal := wrapperspb.String("hello CodeSampleX contract verification")
		strData, err := proto.Marshal(strVal)
		if err != nil {
			fmt.Fprintf(os.Stderr, "FAIL: Marshal StringValue failed: %v\n", err)
			os.Exit(1)
		}
		if sz := proto.Size(strVal); sz != len(strData) {
			fmt.Fprintf(os.Stderr, "FAIL: proto.Size mismatch for StringValue: got %d, want %d\n", sz, len(strData))
			os.Exit(1)
		}
	}

	// 4. proto.Size computes exact wire size for complex messages with maps and nested structures like structpb.Struct and anypb.Any
	{
		st, err := structpb.NewStruct(map[string]interface{}{
			"name":    "service-config",
			"retries": 3,
			"active":  true,
			"tags":    []interface{}{"prod", "us-east-1", "primary"},
			"meta": map[string]interface{}{
				"version": "1.0.0",
				"weight":  12.5,
			},
		})
		if err != nil {
			fmt.Fprintf(os.Stderr, "FAIL: structpb.NewStruct failed: %v\n", err)
			os.Exit(1)
		}

		stData, err := proto.Marshal(st)
		if err != nil {
			fmt.Fprintf(os.Stderr, "FAIL: Marshal structpb failed: %v\n", err)
			os.Exit(1)
		}
		if sz := proto.Size(st); sz != len(stData) {
			fmt.Fprintf(os.Stderr, "FAIL: proto.Size mismatch for Struct: got %d, want %d\n", sz, len(stData))
			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)
		}
		anyData, err := proto.Marshal(anyMsg)
		if err != nil {
			fmt.Fprintf(os.Stderr, "FAIL: Marshal anypb failed: %v\n", err)
			os.Exit(1)
		}
		if sz := proto.Size(anyMsg); sz != len(anyData) {
			fmt.Fprintf(os.Stderr, "FAIL: proto.Size mismatch for Any: got %d, want %d\n", sz, len(anyData))
			os.Exit(1)
		}
	}

	// 5. proto.Size enables buffer pre-allocation for proto.MarshalAppend without slice reallocation
	{
		msg := &durationpb.Duration{
			Seconds: 86400,
			Nanos:   1234,
		}
		expectedSize := proto.Size(msg)
		if expectedSize <= 0 {
			fmt.Fprintf(os.Stderr, "FAIL: expected positive size for non-zero Duration, got %d\n", expectedSize)
			os.Exit(1)
		}

		// Allocate buffer with exact capacity
		buf := make([]byte, 0, expectedSize)
		initialCap := cap(buf)

		marshaled, err := proto.MarshalOptions{}.MarshalAppend(buf, msg)
		if err != nil {
			fmt.Fprintf(os.Stderr, "FAIL: MarshalAppend failed: %v\n", err)
			os.Exit(1)
		}

		if len(marshaled) != expectedSize {
			fmt.Fprintf(os.Stderr, "FAIL: expected length %d, got %d\n", expectedSize, len(marshaled))
			os.Exit(1)
		}
		if cap(marshaled) != initialCap {
			fmt.Fprintf(os.Stderr, "FAIL: buffer was reallocated (cap changed from %d to %d)\n", initialCap, cap(marshaled))
			os.Exit(1)
		}

		// Verify that marshaled bytes correctly unmarshal back to equivalent message
		unmarshaled := &durationpb.Duration{}
		if err := proto.Unmarshal(marshaled, unmarshaled); err != nil {
			fmt.Fprintf(os.Stderr, "FAIL: Unmarshal failed: %v\n", err)
			os.Exit(1)
		}
		if !proto.Equal(msg, unmarshaled) {
			fmt.Fprintf(os.Stderr, "FAIL: unmarshaled message does not match original\n")
			os.Exit(1)
		}

		// Test prefix preservation with MarshalAppend
		prefix := []byte("PRE_")
		bufWithPrefix := make([]byte, len(prefix), len(prefix)+expectedSize)
		copy(bufWithPrefix, prefix)
		appended, err := proto.MarshalOptions{}.MarshalAppend(bufWithPrefix, msg)
		if err != nil {
			fmt.Fprintf(os.Stderr, "FAIL: MarshalAppend with prefix failed: %v\n", err)
			os.Exit(1)
		}
		if !bytes.HasPrefix(appended, prefix) {
			fmt.Fprintf(os.Stderr, "FAIL: prefix was not preserved\n")
			os.Exit(1)
		}
		if len(appended) != len(prefix)+expectedSize {
			fmt.Fprintf(os.Stderr, "FAIL: expected appended length %d, got %d\n", len(prefix)+expectedSize, len(appended))
			os.Exit(1)
		}
	}

	fmt.Println("CONTRACT_PASS")
}

오리진 시더

익명