CodeSampleX

示例

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

已验证示例 — golang google.golang.org/protobuf v1.36.11: proto.Size. contract 在 go 1.26 · linux debian/x64 · docker 上运行并通过: proto.Size returns 0 for nil…

sha256:74c8ddd95a3b1d89e491c4f6f296e1b4e589c9431b0ac77c4cf59e37f380c2d6

本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。 提交了通过的契约回执的不同签名密钥数量。为 1 表示只有作者;大于 1 表示还有其他人构建过。密钥是自行生成的,背后没有注册身份,因此计的是密钥而非人。 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")
}

原始种子者

匿名