CodeSampleX

Exemplo

google.golang.org/api v0.293.0: iterator.Done, iterator.NewPageInfo, iterator.NewPager

Amostra verificada para golang google.golang.org/api v0.293.0: iterator.Done, iterator.NewPageInfo, iterator.NewPager. O contrato rodou em go 1.26 · linux…

sha256:1c7f4581f819f11c297cd349d6f6ecb70dedbd77413b72b8c06bfb812f345692

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 1.26 linux 24 · ubuntu · glibc 2.39 x64 go 1.26 go go 1

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-10-05

Caso

HOW
Objetivo
verify pkg:golang/google.golang.org/api@v0.293.0
Pacotes
Símbolos
  • google.golang.org/api/iterator.Done
  • google.golang.org/api/iterator.NewPageInfo
  • google.golang.org/api/iterator.NewPager
  • google.golang.org/api/support/bundler.NewBundler
Ambiente
go 1.26.6
Criado
2026-10-05T17:15:41Z

Contrato

  1. iterator.NewPageInfo creates a functional PageInfo that supports sequential iteration terminated by iterator.Done
  2. iterator.NewPager creates a pager that paginates through items page by page using page tokens
  3. bundler.NewBundler groups added items into bundles and flushes them to the handler
  4. bundler.Bundler rejects oversized items exceeding BundleByteLimit

Arquivos

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

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

Código-fonte

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 pkg:golang/google.golang.org/api@v0.293.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/google.golang.org/api@v0.293.0
Required runtime conditions:
  - ecosystem: golang
  - language: go
  - packageManager: go@1.26.6
  - runtime: go@1.26.6

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:5ab071679a56d00e81dcb21cf793df0695538fff2c579f22b954965fb8f87590","contract":["iterator.NewPageInfo creates a functional PageInfo that supports sequential iteration terminated by iterator.Done","iterator.NewPager creates a pager that paginates through items page by page using page tokens","bundler.NewBundler groups added items into bundles and flushes them to the handler","bundler.Bundler rejects oversized items exceeding BundleByteLimit"],"goal":"verify pkg:golang/google.golang.org/api@v0.293.0","kind":"HOW","packages":["pkg:golang/google.golang.org/api@v0.293.0"],"schemaVersion":1,"symbols":["google.golang.org/api/iterator.Done","google.golang.org/api/iterator.NewPageInfo","google.golang.org/api/iterator.NewPager","google.golang.org/api/support/bundler.NewBundler"]},"contractCommand":["go","run","./test"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"golang","language":"go","libc":"glibc","libcVersion":"2.39","moduleSystem":"go.mod","os":"linux","osVersionBucket":"24","packageManager":"go","packageManagerVersion":"1.26.6","runtime":"go","runtimeVersion":"1.26.6","schemaVersion":1},"license":"MIT-0","packages":["pkg:golang/google.golang.org/api@v0.293.0"],"schemaVersion":1,"subject":"pkg:golang/google.golang.org/api@v0.293.0","symbols":["google.golang.org/api/iterator.Done","google.golang.org/api/iterator.NewPageInfo","google.golang.org/api/iterator.NewPager","google.golang.org/api/support/bundler.NewBundler"],"verifierAdapter":"golang@1"}
go.mod
module example.com/google-api-sample

go 1.26.6

require google.golang.org/api v0.293.0

require golang.org/x/sync v0.22.0 // indirect
go.sum
golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek=
golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
google.golang.org/api v0.293.0 h1:p9XIWOf63U4OgYx120ZwVU8+vl4XTPmWfgVPnmOAS9w=
google.golang.org/api v0.293.0/go.mod h1:6n5tjEB1gzwniZTepZ0g5u+wM7Bof5GeULCx/zh8ZE0=
iterator_bundler.go
package sample

import (
	"strconv"
	"time"

	"google.golang.org/api/iterator"
	"google.golang.org/api/support/bundler"
)

// StringIterator wraps a slice of strings into a pageable iterator using iterator.NewPageInfo.
type StringIterator struct {
	items []string
	buf   []string
	pi    *iterator.PageInfo
	next  func() error
}

// NewStringIterator initializes a new StringIterator.
func NewStringIterator(items []string) *StringIterator {
	it := &StringIterator{
		items: items,
	}
	it.pi, it.next = iterator.NewPageInfo(
		func(pageSize int, pageToken string) (string, error) {
			if pageSize <= 0 {
				pageSize = 2
			}
			start := 0
			if pageToken != "" {
				idx, err := strconv.Atoi(pageToken)
				if err != nil {
					return "", err
				}
				start = idx
			}
			if start >= len(it.items) {
				return "", nil
			}
			end := start + pageSize
			nextTok := ""
			if end < len(it.items) {
				nextTok = strconv.Itoa(end)
			} else {
				end = len(it.items)
			}
			it.buf = append(it.buf, it.items[start:end]...)
			return nextTok, nil
		},
		func() int {
			return len(it.buf)
		},
		func() interface{} {
			b := it.buf
			it.buf = nil
			return b
		},
	)
	return it
}

// PageInfo returns the PageInfo associated with the iterator.
func (it *StringIterator) PageInfo() *iterator.PageInfo {
	return it.pi
}

// Next returns the next item in the iterator or iterator.Done when exhausted.
func (it *StringIterator) Next() (string, error) {
	if err := it.next(); err != nil {
		return "", err
	}
	item := it.buf[0]
	it.buf = it.buf[1:]
	return item, nil
}

// CreateMessageBundler creates a new Bundler with custom threshold and handler.
func CreateMessageBundler(threshold int, handler func([]string)) *bundler.Bundler {
	b := bundler.NewBundler("", func(items interface{}) {
		handler(items.([]string))
	})
	b.DelayThreshold = 50 * time.Millisecond
	b.BundleCountThreshold = threshold
	return b
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:golang/google.golang.org/api@v0.293.0",
  "kind": "HOW",
  "packages": [
    "pkg:golang/google.golang.org/api@v0.293.0"
  ],
  "symbols": [
    "google.golang.org/api/iterator.Done",
    "google.golang.org/api/iterator.NewPageInfo",
    "google.golang.org/api/iterator.NewPager",
    "google.golang.org/api/support/bundler.NewBundler"
  ],
  "runtimeConditions": {
    "ecosystem": "golang",
    "language": "go",
    "packageManager": "go@1.26.6",
    "runtime": "go@1.26.6"
  }
}
test/contract.go
package main

import (
	"fmt"
	"os"
	"sync"

	sample "example.com/google-api-sample"
	"google.golang.org/api/iterator"
	"google.golang.org/api/support/bundler"
)

func main() {
	items := []string{"item-1", "item-2", "item-3", "item-4"}

	// 1. iterator.NewPageInfo creates a functional PageInfo that supports sequential iteration terminated by iterator.Done
	it := sample.NewStringIterator(items)
	var collected []string
	for {
		val, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			fmt.Fprintf(os.Stderr, "FAIL: unexpected iterator error: %v\n", err)
			os.Exit(1)
		}
		collected = append(collected, val)
	}
	if len(collected) != len(items) {
		fmt.Fprintf(os.Stderr, "FAIL: expected %d items, got %d\n", len(items), len(collected))
		os.Exit(1)
	}

	// 2. iterator.NewPager creates a pager that paginates through items page by page using page tokens
	it2 := sample.NewStringIterator(items)
	pager := iterator.NewPager(it2, 2, "")
	var page1 []string
	tok1, err := pager.NextPage(&page1)
	if err != nil || len(page1) != 2 || page1[0] != "item-1" || page1[1] != "item-2" || tok1 != "2" {
		fmt.Fprintf(os.Stderr, "FAIL: page1 mismatch: tok=%q, page=%v, err=%v\n", tok1, page1, err)
		os.Exit(1)
	}

	var page2 []string
	tok2, err := pager.NextPage(&page2)
	if err != nil || len(page2) != 2 || page2[0] != "item-3" || page2[1] != "item-4" || tok2 != "" {
		fmt.Fprintf(os.Stderr, "FAIL: page2 mismatch: tok=%q, page=%v, err=%v\n", tok2, page2, err)
		os.Exit(1)
	}

	// 3. bundler.NewBundler groups added items into bundles and flushes them to the handler
	var mu sync.Mutex
	var bundled []string
	b := sample.CreateMessageBundler(2, func(msgs []string) {
		mu.Lock()
		defer mu.Unlock()
		bundled = append(bundled, msgs...)
	})

	if err := b.Add("msg-a", 1); err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: b.Add failed: %v\n", err)
		os.Exit(1)
	}
	if err := b.Add("msg-b", 1); err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: b.Add failed: %v\n", err)
		os.Exit(1)
	}
	b.Flush()

	mu.Lock()
	if len(bundled) != 2 || bundled[0] != "msg-a" || bundled[1] != "msg-b" {
		fmt.Fprintf(os.Stderr, "FAIL: unexpected bundled results: %v\n", bundled)
		mu.Unlock()
		os.Exit(1)
	}
	mu.Unlock()

	// 4. bundler.Bundler rejects oversized items exceeding BundleByteLimit
	b.BundleByteLimit = 5
	if err := b.Add("oversized-message-content", 10); err != bundler.ErrOversizedItem {
		fmt.Fprintf(os.Stderr, "FAIL: expected ErrOversizedItem, got: %v\n", err)
		os.Exit(1)
	}

	fmt.Println("PASS: pkg:golang/google.golang.org/api@v0.293.0 contract passed")
}

Seeder de origem

anônimo