CodeSampleX

示例

google.golang.org/protobuf v1.36.4: proto.Clone

已验证示例 — golang google.golang.org/protobuf v1.36.4: proto.Clone. contract 在 go 1.26 · linux debian/x64 · docker 上运行并通过: proto.Clone creates an isolated deep…

sha256:26d5c21dbe2f86e7cf4e1b1e1fecb0720e9fefae171d8126e111e3f0294638a1

本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。 提交了通过的契约回执的不同签名密钥数量。为 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-10-24

案例

HOW
目标
verify google.golang.org/protobuf/proto.Clone in pkg:golang/google.golang.org/protobuf@v1.36.4
包
符号
  • google.golang.org/protobuf/proto.Clone
创建时间
2026-10-24T16:01:20Z

契约

  1. proto.Clone creates an isolated deep copy across nested messages, repeated lists, and map entries where mutating the clone does not affect the original
  2. proto.Clone(nil) returns untyped nil for an untyped nil proto.Message and returns a typed nil pointer whose ProtoReflect().IsValid() is false for a typed nil pointer
  3. proto.Clone preserves explicit field presence on proto3_optional fields set to zero values while leaving unpopulated implicit scalar fields unpopulated
  4. proto.Clone preserves unknown wire fields on the cloned message

文件

  • 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/proto.Clone in pkg:golang/google.golang.org/protobuf@v1.36.4
Kind: HOW

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

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:c9d6f64a4e69e885dafd5cae90c5e3ef281853c0a8b5337b91afdc8366d6908a","contract":["proto.Clone creates an isolated deep copy across nested messages, repeated lists, and map entries where mutating the clone does not affect the original","proto.Clone(nil) returns untyped nil for an untyped nil proto.Message and returns a typed nil pointer whose ProtoReflect().IsValid() is false for a typed nil pointer","proto.Clone preserves explicit field presence on proto3_optional fields set to zero values while leaving unpopulated implicit scalar fields unpopulated","proto.Clone preserves unknown wire fields on the cloned message"],"goal":"verify google.golang.org/protobuf/proto.Clone in pkg:golang/google.golang.org/protobuf@v1.36.4","kind":"HOW","packages":["pkg:golang/google.golang.org/protobuf@v1.36.4"],"schemaVersion":1,"symbols":["google.golang.org/protobuf/proto.Clone"]},"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.4"],"schemaVersion":1,"subject":"pkg:golang/google.golang.org/protobuf@v1.36.4","symbols":["google.golang.org/protobuf/proto.Clone"],"verifierAdapter":"golang@1"}
go.mod
module sample

go 1.26.6

require google.golang.org/protobuf v1.36.4
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.36.4 h1:6A3ZDJHn/eNqc1i+IdefRzy/9PokBTPvcqMySR7NNIM=
google.golang.org/protobuf v1.36.4/go.mod h1:9fA7Ob0pmnwhb644+1+CVWFRbNajQ6iRojtC/QF5bRE=
main.go
package main

import (
	"fmt"
	"os"

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

func cloneTimestamp(src *timestamppb.Timestamp) *timestamppb.Timestamp {
	cloned := proto.Clone(src)
	if cloned == nil {
		return nil
	}
	return cloned.(*timestamppb.Timestamp)
}

func main() {
	orig := &timestamppb.Timestamp{Seconds: 1700000000, Nanos: 250}
	copyMsg := cloneTimestamp(orig)
	if !proto.Equal(orig, copyMsg) {
		fmt.Fprintln(os.Stderr, "cloned message does not equal original")
		os.Exit(1)
	}
	copyMsg.Seconds = 1700000099
	if orig.Seconds != 1700000000 {
		fmt.Fprintln(os.Stderr, "mutating clone affected original")
		os.Exit(1)
	}
	fmt.Printf("Verified proto.Clone: original=%d cloned=%d\n", orig.Seconds, copyMsg.Seconds)
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify google.golang.org/protobuf/proto.Clone in pkg:golang/google.golang.org/protobuf@v1.36.4",
  "kind": "HOW",
  "packages": [
    "pkg:golang/google.golang.org/protobuf@v1.36.4"
  ],
  "symbols": [
    "google.golang.org/protobuf/proto.Clone"
  ]
}
test/contract.go
package main

import (
	"bytes"
	"fmt"
	"os"
	"reflect"

	"google.golang.org/protobuf/encoding/protowire"
	"google.golang.org/protobuf/proto"
	"google.golang.org/protobuf/reflect/protodesc"
	"google.golang.org/protobuf/reflect/protoreflect"
	"google.golang.org/protobuf/reflect/protoregistry"
	"google.golang.org/protobuf/types/descriptorpb"
	"google.golang.org/protobuf/types/dynamicpb"
	"google.golang.org/protobuf/types/known/structpb"
	"google.golang.org/protobuf/types/known/timestamppb"
)

func main() {
	// Assertion 1: proto.Clone creates an isolated deep copy across nested messages, repeated lists, and map entries
	{
		orig, err := structpb.NewStruct(map[string]any{
			"name": "service-a",
			"tags": []any{"v1", "production"},
			"nested": map[string]any{
				"port": 8080,
			},
		})
		if err != nil {
			fmt.Fprintf(os.Stderr, "assertion 1 failed: NewStruct error: %v\n", err)
			os.Exit(1)
		}

		clonedMsg := proto.Clone(orig)
		cloned, ok := clonedMsg.(*structpb.Struct)
		if !ok {
			fmt.Fprintln(os.Stderr, "assertion 1 failed: unexpected concrete type from proto.Clone")
			os.Exit(1)
		}
		if !proto.Equal(orig, cloned) {
			fmt.Fprintln(os.Stderr, "assertion 1 failed: cloned struct does not equal original")
			os.Exit(1)
		}

		// Mutate map entry, repeated list element, and nested struct in the clone
		cloned.Fields["name"] = structpb.NewStringValue("service-b")
		cloned.Fields["tags"].GetListValue().Values[0] = structpb.NewStringValue("v2")
		cloned.Fields["nested"].GetStructValue().Fields["port"] = structpb.NewNumberValue(9090)

		if orig.Fields["name"].GetStringValue() != "service-a" {
			fmt.Fprintln(os.Stderr, "assertion 1 failed: mutating cloned map entry modified original")
			os.Exit(1)
		}
		if orig.Fields["tags"].GetListValue().Values[0].GetStringValue() != "v1" {
			fmt.Fprintln(os.Stderr, "assertion 1 failed: mutating cloned list modified original")
			os.Exit(1)
		}
		if orig.Fields["nested"].GetStructValue().Fields["port"].GetNumberValue() != 8080 {
			fmt.Fprintln(os.Stderr, "assertion 1 failed: mutating cloned nested message modified original")
			os.Exit(1)
		}
	}

	// Assertion 2: proto.Clone(nil) returns untyped nil for untyped nil and a typed nil pointer with invalid reflection for typed nil
	{
		var untypedNil proto.Message
		if got := proto.Clone(untypedNil); got != nil {
			fmt.Fprintf(os.Stderr, "assertion 2 failed: expected untyped nil, got %v\n", got)
			os.Exit(1)
		}

		var typedNil *timestamppb.Timestamp
		gotTyped := proto.Clone(typedNil)
		if gotTyped == nil {
			fmt.Fprintln(os.Stderr, "assertion 2 failed: expected typed nil interface, got untyped nil")
			os.Exit(1)
		}
		if !reflect.ValueOf(gotTyped).IsNil() {
			fmt.Fprintln(os.Stderr, "assertion 2 failed: expected concrete value of cloned typed nil to be nil")
			os.Exit(1)
		}
		if gotTyped.ProtoReflect().IsValid() {
			fmt.Fprintln(os.Stderr, "assertion 2 failed: expected ProtoReflect().IsValid() to be false for typed nil clone")
			os.Exit(1)
		}
	}

	// Assertion 3: proto.Clone preserves explicit field presence on proto3_optional zero values while keeping unpopulated implicit fields unpopulated
	{
		fdp := &descriptorpb.FileDescriptorProto{
			Name:    proto.String("presence.proto"),
			Package: proto.String("sample.presence"),
			Syntax:  proto.String("proto3"),
			MessageType: []*descriptorpb.DescriptorProto{
				{
					Name: proto.String("Record"),
					Field: []*descriptorpb.FieldDescriptorProto{
						{
							Name:     proto.String("implicit_text"),
							Number:   proto.Int32(1),
							Type:     descriptorpb.FieldDescriptorProto_TYPE_STRING.Enum(),
							JsonName: proto.String("implicitText"),
						},
						{
							Name:           proto.String("optional_zero"),
							Number:         proto.Int32(2),
							Type:           descriptorpb.FieldDescriptorProto_TYPE_INT32.Enum(),
							JsonName:       proto.String("optionalZero"),
							Proto3Optional: proto.Bool(true),
							OneofIndex:     proto.Int32(0),
						},
					},
					OneofDecl: []*descriptorpb.OneofDescriptorProto{
						{Name: proto.String("_optional_zero")},
					},
				},
			},
		}
		fileDesc, err := protodesc.NewFile(fdp, protoregistry.GlobalFiles)
		if err != nil {
			fmt.Fprintf(os.Stderr, "assertion 3 failed: NewFile error: %v\n", err)
			os.Exit(1)
		}
		msgDesc := fileDesc.Messages().ByName("Record")
		implicitField := msgDesc.Fields().ByName("implicit_text")
		optField := msgDesc.Fields().ByName("optional_zero")

		origDyn := dynamicpb.NewMessage(msgDesc)
		origDyn.Set(optField, protoreflect.ValueOfInt32(0))

		clonedDyn := proto.Clone(origDyn).(*dynamicpb.Message)
		if !clonedDyn.Has(optField) || clonedDyn.Get(optField).Int() != 0 {
			fmt.Fprintln(os.Stderr, "assertion 3 failed: proto.Clone lost explicit presence for proto3_optional field set to 0")
			os.Exit(1)
		}
		if clonedDyn.Has(implicitField) {
			fmt.Fprintln(os.Stderr, "assertion 3 failed: proto.Clone populated unpopulated implicit scalar field")
			os.Exit(1)
		}
	}

	// Assertion 4: proto.Clone preserves unknown wire fields on the cloned message
	{
		orig := &timestamppb.Timestamp{Seconds: 100, Nanos: 200}
		var unknownRaw []byte
		unknownRaw = protowire.AppendTag(unknownRaw, 99, protowire.VarintType)
		unknownRaw = protowire.AppendVarint(unknownRaw, 4242)
		orig.ProtoReflect().SetUnknown(protoreflect.RawFields(unknownRaw))

		cloned := proto.Clone(orig).(*timestamppb.Timestamp)
		gotUnknown := []byte(cloned.ProtoReflect().GetUnknown())
		if !bytes.Equal(gotUnknown, unknownRaw) {
			fmt.Fprintf(os.Stderr, "assertion 4 failed: unknown fields mismatch: got %x want %x\n", gotUnknown, unknownRaw)
			os.Exit(1)
		}
	}

	fmt.Println("All proto.Clone contract assertions passed.")
}

原始种子者

匿名