CodeSampleX

Exemplo

google.golang.org/protobuf v1.28.0: structpb.NewList

Amostra verificada para golang google.golang.org/protobuf v1.28.0: structpb.NewList. O contrato rodou em go 1.26 · linux debian/x64 · docker e passou…

sha256:3e202a97b8557a1a1be26d66600a1a72a587d62c216b4c4b8999e65e7241c82b

Esta rede oferece uma coisa: uma amostra que compila. Ela a executou em um sandbox e guardou o recibo assinado. Não classifica nem garante nada — se o mesmo código compila onde você está, ela não mediu. Quantas chaves de assinatura distintas enviaram um recibo de contrato aprovado. Uma é só o autor; mais de uma significa que outra pessoa também o compilou. Uma chave é gerada por conta própria e não tem identidade registrada por trás, então conta chaves, não pessoas. MIT-0

Evidência de execução

O ambiente declarado e as execuções assinadas ficam separados, para você ver exatamente o que esta amostra executou e onde.

Base da evidência
Contrato assinado aprovado
Recibos de verificação
1
Chaves de assinatura que o compilaram
1
Ambiente declarado go linux 24 · ubuntu · glibc 2.39 x64 go go go

Ambientes das execuções de verificação

Ambiente Contrato Etapas Execução
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

Caso

HOW
Objetivo
verify google.golang.org/protobuf/types/known/structpb.NewList in pkg:golang/google.golang.org/protobuf@v1.28.0
Pacotes
Símbolos
  • google.golang.org/protobuf/types/known/structpb.NewList
Ambiente
go
Criado
2026-09-02T06:53:17Z

Contrato

  1. structpb.NewList converts Go slices containing primitive types (nil, bool, numbers, strings) into *structpb.ListValue with matching Value kinds.
  2. structpb.NewList converts nested Go slices and maps into nested ListValue and StructValue elements.
  3. structpb.NewList(nil) succeeds and returns an empty non-nil *structpb.ListValue with zero elements.
  4. ListValue.AsSlice converts *structpb.ListValue back to []interface{}, and calling AsSlice on a nil receiver safely returns an empty non-nil slice.
  5. structpb.NewList returns an error when converting a slice containing unsupported Go types such as channels or functions.

Arquivos

  • NOTES.md
  • PROMPT.md
  • csx.json
  • go.mod
  • go.sum
  • spec.json
  • structpb_list_test.go

Baixar o artefato de código-fonte (tar.gz)

Código-fonte

NOTES.md
# Protocol Buffers structpb NewList Dynamic Slice Conversion

A search for `google.golang.org/protobuf/types/known/structpb.NewList` in `google.golang.org/protobuf@v1.28.0` was verified in this clean-room environment.

This sample tests and verifies conversion semantics between dynamic Go slices and Protocol Buffers `ListValue` messages using `structpb.NewList`.

## Observed Behavior

1. **Primitive Value Conversion (`structpb.NewList`)**:
   - `structpb.NewList([]interface{})` converts primitive elements (`nil`, `bool`, `int`/`int32`/`int64`/`float32`/`float64`, `string`) to appropriate `Value` kinds (`NullValue`, `BoolValue`, `NumberValue` as float64, `StringValue`).

2. **Nested Structures Conversion**:
   - Nested Go slices and maps are converted to nested `ListValue` and `StructValue` respectively within the `ListValue`.

3. **Nil and Empty Slice Handling**:
   - `structpb.NewList(nil)` succeeds without error and produces an empty `*structpb.ListValue` with zero elements.
   - Calling `AsSlice()` on an empty `ListValue` returns an empty non-nil `[]interface{}{}`.

4. **Slice Conversion Back (`ListValue.AsSlice`) and Nil Safety**:
   - `lv.AsSlice()` converts `*structpb.ListValue` back to `[]interface{}`.
   - Calling `AsSlice()` on a `nil` `*structpb.ListValue` receiver safely returns an empty non-nil slice (`[]interface{}{}`) without panicking.

5. **Error Handling on Unsupported Types**:
   - Passing slices containing unsupported Go types such as channels or functions causes `structpb.NewList` to fail and return an error.
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/structpb.NewList in pkg:golang/google.golang.org/protobuf@v1.28.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/google.golang.org/protobuf@v1.28.0
Demonstrate these symbols/APIs:
  - google.golang.org/protobuf/types/known/structpb.NewList

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:65929e508ec7e5c0647a3f181d1266f66b1681873765e9d587d97ec1bb791643","contract":["structpb.NewList converts Go slices containing primitive types (nil, bool, numbers, strings) into *structpb.ListValue with matching Value kinds.","structpb.NewList converts nested Go slices and maps into nested ListValue and StructValue elements.","structpb.NewList(nil) succeeds and returns an empty non-nil *structpb.ListValue with zero elements.","ListValue.AsSlice converts *structpb.ListValue back to []interface{}, and calling AsSlice on a nil receiver safely returns an empty non-nil slice.","structpb.NewList returns an error when converting a slice containing unsupported Go types such as channels or functions."],"goal":"verify google.golang.org/protobuf/types/known/structpb.NewList in pkg:golang/google.golang.org/protobuf@v1.28.0","kind":"HOW","packages":["pkg:golang/google.golang.org/protobuf@v1.28.0"],"schemaVersion":1,"symbols":["google.golang.org/protobuf/types/known/structpb.NewList"]},"contractCommand":["go","test","./..."],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"golang","executionContext":"go","language":"go","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"go","runtime":"go","schemaVersion":1},"license":"MIT-0","packages":["pkg:golang/google.golang.org/protobuf@v1.28.0"],"schemaVersion":1,"subject":"pkg:golang/google.golang.org/protobuf@v1.28.0","symbols":["google.golang.org/protobuf/types/known/structpb.NewList"],"verifierAdapter":"golang@1"}
go.mod
module example.com/structpblist

go 1.20

require google.golang.org/protobuf v1.28.0
go.sum
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
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.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
google.golang.org/protobuf v1.28.0 h1:w43yiav+6bVFTBQFZX0r7ipe9JQ1QsbMgHwbBziscLw=
google.golang.org/protobuf v1.28.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I=
spec.json
{
  "schemaVersion": 1,
  "goal": "verify google.golang.org/protobuf/types/known/structpb.NewList in pkg:golang/google.golang.org/protobuf@v1.28.0",
  "kind": "HOW",
  "packages": [
    "pkg:golang/google.golang.org/protobuf@v1.28.0"
  ],
  "symbols": [
    "google.golang.org/protobuf/types/known/structpb.NewList"
  ]
}
structpb_list_test.go
package structpblist_test

import (
	"reflect"
	"testing"

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

func TestNewListPrimitives(t *testing.T) {
	input := []interface{}{
		nil,
		true,
		false,
		int(42),
		int32(100),
		int64(200),
		float32(3.14),
		float64(2.71828),
		"hello world",
	}

	lv, err := structpb.NewList(input)
	if err != nil {
		t.Fatalf("NewList failed for primitives: %v", err)
	}

	if len(lv.GetValues()) != len(input) {
		t.Fatalf("expected %d values, got %d", len(input), len(lv.GetValues()))
	}

	// 1. nil -> NullValue
	if _, ok := lv.Values[0].GetKind().(*structpb.Value_NullValue); !ok {
		t.Fatalf("expected NullValue at index 0, got %T", lv.Values[0].GetKind())
	}

	// 2. bool -> BoolValue
	if b, ok := lv.Values[1].GetKind().(*structpb.Value_BoolValue); !ok || !b.BoolValue {
		t.Fatalf("expected BoolValue(true) at index 1, got %v", lv.Values[1].GetKind())
	}

	// 3. numbers -> NumberValue (float64)
	if num, ok := lv.Values[3].GetKind().(*structpb.Value_NumberValue); !ok || num.NumberValue != 42 {
		t.Fatalf("expected NumberValue(42) at index 3, got %v", lv.Values[3].GetKind())
	}

	// 4. string -> StringValue
	if s, ok := lv.Values[8].GetKind().(*structpb.Value_StringValue); !ok || s.StringValue != "hello world" {
		t.Fatalf("expected StringValue('hello world') at index 8, got %v", lv.Values[8].GetKind())
	}
}

func TestNewListNestedStructures(t *testing.T) {
	input := []interface{}{
		[]interface{}{"nested", float64(1)},
		map[string]interface{}{"key": "value"},
	}

	lv, err := structpb.NewList(input)
	if err != nil {
		t.Fatalf("NewList failed on nested structures: %v", err)
	}

	if len(lv.GetValues()) != 2 {
		t.Fatalf("expected 2 values, got %d", len(lv.GetValues()))
	}

	if _, ok := lv.Values[0].GetKind().(*structpb.Value_ListValue); !ok {
		t.Fatalf("expected nested ListValue at index 0, got %T", lv.Values[0].GetKind())
	}

	if _, ok := lv.Values[1].GetKind().(*structpb.Value_StructValue); !ok {
		t.Fatalf("expected nested StructValue at index 1, got %T", lv.Values[1].GetKind())
	}

	slice := lv.AsSlice()
	if !reflect.DeepEqual(input, slice) {
		t.Fatalf("AsSlice() mismatch on nested data:\nwant: %#v\ngot:  %#v", input, slice)
	}
}

func TestNewListNilAndEmpty(t *testing.T) {
	// structpb.NewList(nil) succeeds and returns an empty non-nil ListValue
	lv, err := structpb.NewList(nil)
	if err != nil {
		t.Fatalf("NewList(nil) failed: %v", err)
	}
	if lv == nil {
		t.Fatalf("expected non-nil ListValue for NewList(nil)")
	}
	if len(lv.GetValues()) != 0 {
		t.Fatalf("expected 0 values for NewList(nil), got %d", len(lv.GetValues()))
	}

	slice := lv.AsSlice()
	if slice == nil || len(slice) != 0 {
		t.Fatalf("expected empty non-nil slice from empty ListValue.AsSlice(), got %#v", slice)
	}
}

func TestListValueAsSliceAndNilReceiver(t *testing.T) {
	input := []interface{}{"alpha", float64(123), true}
	lv, err := structpb.NewList(input)
	if err != nil {
		t.Fatalf("NewList failed: %v", err)
	}

	got := lv.AsSlice()
	if !reflect.DeepEqual(input, got) {
		t.Fatalf("AsSlice() mismatch:\nwant: %#v\ngot:  %#v", input, got)
	}

	// Calling AsSlice on a nil receiver safely returns an empty non-nil slice
	var nilList *structpb.ListValue
	nilSlice := nilList.AsSlice()
	if nilSlice == nil || len(nilSlice) != 0 {
		t.Fatalf("expected nil receiver AsSlice() to return empty non-nil slice, got %#v", nilSlice)
	}
}

func TestNewListUnsupportedTypesError(t *testing.T) {
	// Channels cannot be converted
	ch := make(chan int)
	if _, err := structpb.NewList([]interface{}{ch}); err == nil {
		t.Fatalf("expected error for slice containing channel, got nil")
	}

	// Functions cannot be converted
	fn := func() {}
	if _, err := structpb.NewList([]interface{}{"valid", fn}); err == nil {
		t.Fatalf("expected error for slice containing func, got nil")
	}
}

Seeder de origem

anônimo