CodeSampleX

Пример

google.golang.org/api v0.288.0: iterator.PageInfo

Проверенный пример — golang google.golang.org/api v0.288.0: iterator.PageInfo. Контракт выполнен на go 1.26 · linux debian/x64 · docker и пройден.

sha256:da53947e5759ce2d559e343ed9a5461671ca0d6457a9e64bea37a5ca3f0caad2

Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла. Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди. 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-13

Кейс

HOW
Цель
verify google.golang.org/api/iterator.PageInfo in pkg:golang/google.golang.org/api@v0.288.0
Пакеты
Символы
  • google.golang.org/api/iterator.PageInfo
Создан
2026-10-13T04:44:15Z

Контракт

  1. PageInfo tracks pagination token and max page size for pageable iterators
  2. PageInfo.Remaining reports the number of buffered items remaining before next fetch
  3. Pager retrieves items page by page using PageInfo token and buffer
  4. PageInfo detects and prevents mixed calls to Next and NextPage on the same iterator

Файлы

  • PROMPT.md
  • csx.json
  • go.mod
  • go.sum
  • sample.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/api/iterator.PageInfo in pkg:golang/google.golang.org/api@v0.288.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/google.golang.org/api@v0.288.0
Demonstrate these symbols/APIs:
  - google.golang.org/api/iterator.PageInfo

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:53b55746d731ea3963f4c3d40efd2a783d9612d10a7030dae7f053d50aba3e61","contract":["PageInfo tracks pagination token and max page size for pageable iterators","PageInfo.Remaining reports the number of buffered items remaining before next fetch","Pager retrieves items page by page using PageInfo token and buffer","PageInfo detects and prevents mixed calls to Next and NextPage on the same iterator"],"goal":"verify google.golang.org/api/iterator.PageInfo in pkg:golang/google.golang.org/api@v0.288.0","kind":"HOW","packages":["pkg:golang/google.golang.org/api@v0.288.0"],"schemaVersion":1,"symbols":["google.golang.org/api/iterator.PageInfo"]},"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/api@v0.288.0"],"schemaVersion":1,"subject":"pkg:golang/google.golang.org/api@v0.288.0","symbols":["google.golang.org/api/iterator.PageInfo"],"verifierAdapter":"golang@1"}
go.mod
module example.com/iterator-sample

go 1.26.6

require google.golang.org/api v0.288.0
go.sum
google.golang.org/api v0.288.0 h1:glhO/J88obKP5I269W3hB73dvBKrjU56ZfmNlNXpgTU=
google.golang.org/api v0.288.0/go.mod h1:lM2kYRzYUCBY91P9h6VF1PYmvhxii3O5hji37qRvIcY=
sample.go
package sample

import (
	"google.golang.org/api/iterator"
)

// ItemIterator demonstrates paging using iterator.PageInfo.
type ItemIterator struct {
	pageInfo *iterator.PageInfo
	next     func() error
	items    []string
}

// NewItemIterator creates a new ItemIterator over pages of string items.
func NewItemIterator(pages map[string][]string, initialToken string) *ItemIterator {
	it := &ItemIterator{
		items: make([]string, 0),
	}
	it.pageInfo, it.next = iterator.NewPageInfo(
		func(pageSize int, pageToken string) (string, error) {
			items, ok := pages[pageToken]
			if !ok {
				return "", nil
			}
			it.items = append(it.items, items...)
			var nextTok string
			if pageToken == "" && len(pages) > 1 {
				nextTok = "token-page-2"
			}
			return nextTok, nil
		},
		func() int {
			return len(it.items)
		},
		func() interface{} {
			b := it.items
			it.items = nil
			if b == nil {
				return []string{}
			}
			return b
		},
	)
	it.pageInfo.Token = initialToken
	return it
}

// PageInfo returns the iterator's PageInfo.
func (it *ItemIterator) PageInfo() *iterator.PageInfo {
	return it.pageInfo
}

// Next returns the next item in the iterator.
func (it *ItemIterator) Next() (string, error) {
	if err := it.next(); err != nil {
		return "", err
	}
	item := it.items[0]
	it.items = it.items[1:]
	return item, nil
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify google.golang.org/api/iterator.PageInfo in pkg:golang/google.golang.org/api@v0.288.0",
  "kind": "HOW",
  "packages": [
    "pkg:golang/google.golang.org/api@v0.288.0"
  ],
  "symbols": [
    "google.golang.org/api/iterator.PageInfo"
  ]
}
test/contract.go
package main

import (
	"fmt"
	"os"
	"strings"

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

func main() {
	// Assertion 1: PageInfo tracks pagination token and max page size for pageable iterators
	{
		pages := map[string][]string{
			"":             {"alpha", "beta"},
			"token-page-2": {"gamma"},
		}
		it := sample.NewItemIterator(pages, "custom-start-token")
		pi := it.PageInfo()
		if pi == nil {
			fmt.Fprintf(os.Stderr, "Assertion 1 failed: expected non-nil PageInfo\n")
			os.Exit(1)
		}
		if pi.Token != "custom-start-token" {
			fmt.Fprintf(os.Stderr, "Assertion 1 failed: expected token 'custom-start-token', got %q\n", pi.Token)
			os.Exit(1)
		}
		pi.MaxSize = 50
		if pi.MaxSize != 50 {
			fmt.Fprintf(os.Stderr, "Assertion 1 failed: expected MaxSize 50, got %d\n", pi.MaxSize)
			os.Exit(1)
		}
	}

	// Assertion 2: PageInfo.Remaining reports the number of buffered items remaining before next fetch
	{
		pages := map[string][]string{
			"": {"item1", "item2", "item3"},
		}
		it := sample.NewItemIterator(pages, "")
		pi := it.PageInfo()
		if rem := pi.Remaining(); rem != 0 {
			fmt.Fprintf(os.Stderr, "Assertion 2 failed: expected 0 remaining before first Next, got %d\n", rem)
			os.Exit(1)
		}

		item1, err := it.Next()
		if err != nil || item1 != "item1" {
			fmt.Fprintf(os.Stderr, "Assertion 2 failed: unexpected first item: %s, err: %v\n", item1, err)
			os.Exit(1)
		}
		if rem := pi.Remaining(); rem != 2 {
			fmt.Fprintf(os.Stderr, "Assertion 2 failed: expected 2 remaining after first Next, got %d\n", rem)
			os.Exit(1)
		}

		item2, err := it.Next()
		if err != nil || item2 != "item2" {
			fmt.Fprintf(os.Stderr, "Assertion 2 failed: unexpected second item: %s, err: %v\n", item2, err)
			os.Exit(1)
		}
		if rem := pi.Remaining(); rem != 1 {
			fmt.Fprintf(os.Stderr, "Assertion 2 failed: expected 1 remaining after second Next, got %d\n", rem)
			os.Exit(1)
		}

		item3, err := it.Next()
		if err != nil || item3 != "item3" {
			fmt.Fprintf(os.Stderr, "Assertion 2 failed: unexpected third item: %s, err: %v\n", item3, err)
			os.Exit(1)
		}
		if rem := pi.Remaining(); rem != 0 {
			fmt.Fprintf(os.Stderr, "Assertion 2 failed: expected 0 remaining after third Next, got %d\n", rem)
			os.Exit(1)
		}

		_, err = it.Next()
		if err != iterator.Done {
			fmt.Fprintf(os.Stderr, "Assertion 2 failed: expected iterator.Done, got %v\n", err)
			os.Exit(1)
		}
	}

	// Assertion 3: Pager retrieves items page by page using PageInfo token and buffer
	{
		pages := map[string][]string{
			"":             {"page1-a", "page1-b"},
			"token-page-2": {"page2-a"},
		}
		it := sample.NewItemIterator(pages, "")
		pager := iterator.NewPager(it, 2, "")

		var page1 []string
		nextTok, err := pager.NextPage(&page1)
		if err != nil {
			fmt.Fprintf(os.Stderr, "Assertion 3 failed: unexpected error on page 1: %v\n", err)
			os.Exit(1)
		}
		if len(page1) != 2 || page1[0] != "page1-a" || page1[1] != "page1-b" {
			fmt.Fprintf(os.Stderr, "Assertion 3 failed: unexpected page 1 items: %v\n", page1)
			os.Exit(1)
		}
		if nextTok != "token-page-2" {
			fmt.Fprintf(os.Stderr, "Assertion 3 failed: expected next token 'token-page-2', got %q\n", nextTok)
			os.Exit(1)
		}

		var page2 []string
		nextTok2, err := pager.NextPage(&page2)
		if err != nil {
			fmt.Fprintf(os.Stderr, "Assertion 3 failed: unexpected error on page 2: %v\n", err)
			os.Exit(1)
		}
		if len(page2) != 1 || page2[0] != "page2-a" {
			fmt.Fprintf(os.Stderr, "Assertion 3 failed: unexpected page 2 items: %v\n", page2)
			os.Exit(1)
		}
		if nextTok2 != "" {
			fmt.Fprintf(os.Stderr, "Assertion 3 failed: expected empty next token, got %q\n", nextTok2)
			os.Exit(1)
		}
	}

	// Assertion 4: PageInfo detects and prevents mixed calls to Next and NextPage on the same iterator
	{
		pages := map[string][]string{
			"": {"item1", "item2"},
		}
		it := sample.NewItemIterator(pages, "")
		_, err := it.Next()
		if err != nil {
			fmt.Fprintf(os.Stderr, "Assertion 4 failed: unexpected error on Next: %v\n", err)
			os.Exit(1)
		}

		pager := iterator.NewPager(it, 1, "")
		var items []string
		_, err = pager.NextPage(&items)
		if err == nil {
			fmt.Fprintf(os.Stderr, "Assertion 4 failed: expected error on mixed NextPage call, got nil\n")
			os.Exit(1)
		}
		if !strings.Contains(err.Error(), "Next and NextPage called on same iterator") {
			fmt.Fprintf(os.Stderr, "Assertion 4 failed: unexpected error message: %v\n", err)
			os.Exit(1)
		}
	}

	fmt.Println("PASS: google.golang.org/api/iterator.PageInfo contract passed")
}

Исходный сидер

аноним