CodeSampleX

示例

google.golang.org/protobuf v1.33.0: Convert between Go time.Time and Protocol Buffers Timestamp using timestamppb New, AsTime, IsValid, and CheckValid with zero and range validation

已验证示例 — golang google.golang.org/protobuf v1.33.0: Convert between Go time.Time and Protocol Buffers Timestamp using timestamppb New, AsTime, IsValid, and…

sha256:9f4e978498bd666624a103863d3c7a58a7a39f9095661f61dece4c3eb4e3d6af

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

执行证据

声明的环境与签名的运行分开呈现,你可以看到这个样本究竟运行了什么、在哪里运行。

证据依据
签名契约通过
验证回执
1
构建过它的签名密钥
1
声明的环境 linux 24 · ubuntu · glibc 2.39 x64 go

验证运行环境

环境 契约 阶段 运行日期
go 1.26 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · golang@1golang:1.26-alpine@sha256:28d89ee9cc0f…
2026-08-27

案例

HOW
目标
Convert between Go time.Time and Protocol Buffers Timestamp using timestamppb New, AsTime, IsValid, and CheckValid with zero and range validation
包
符号
  • google.golang.org/protobuf/types/known/timestamppb.New
  • google.golang.org/protobuf/types/known/timestamppb.Timestamp.AsTime
  • google.golang.org/protobuf/types/known/timestamppb.Timestamp.CheckValid
  • google.golang.org/protobuf/types/known/timestamppb.Timestamp.IsValid
创建时间
2026-08-27T20:58:39Z

契约

  1. timestamppb.New converts time.Time into *timestamppb.Timestamp with Seconds and Nanos normalized to UTC, correctly mapping zero time and sub-second nanoseconds.
  2. timestamppb.Timestamp.AsTime converts the protobuf message back to time.Time in UTC, and calling AsTime on a nil receiver safely returns time.Unix(0, 0).UTC().
  3. timestamppb.Timestamp.CheckValid and IsValid validate timestamp bounds from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999999Z and reject negative or overflowing nanoseconds.
  4. timestamppb.Timestamp supports protobuf wire serialization and protojson serialization formatting as an RFC 3339 string.

文件

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

下载源代码构件 (tar.gz)

源代码

NOTES.md
# Protocol Buffers Timestamp Well-Known Type Behavior

A known-solution search for `google.golang.org/protobuf/types/known/timestamppb` in package `pkg:golang/google.golang.org/protobuf@v1.33.0` returned no safe match. This sample verifies the construction, conversion, validation, and serialization semantics of `google.protobuf.Timestamp` using `timestamppb.New`, `AsTime`, `IsValid`, and `CheckValid`.

## Observed Behavior

1. **Conversion with `timestamppb.New` and `timestamppb.Now`**:
   - `timestamppb.New(t)` converts a standard Go `time.Time` into a protobuf `*timestamppb.Timestamp` message consisting of `Seconds` (`int64`) and `Nanos` (`int32`).
   - Timestamps with timezone offsets are normalized to their instantaneous UTC seconds and nanoseconds.
   - Zero `time.Time{}` (the Go zero value `0001-01-01T00:00:00Z`) maps to `Seconds: -62135596800, Nanos: 0`.
   - `timestamppb.Now()` produces a valid `*timestamppb.Timestamp` corresponding to the current system clock.

2. **Reconstitution and Nil Safety (`AsTime`)**:
   - `ts.AsTime()` converts the protobuf `*timestamppb.Timestamp` back to a Go `time.Time` in UTC (`time.Unix(ts.Seconds, int64(ts.Nanos)).UTC()`).
   - Calling `(*timestamppb.Timestamp)(nil).AsTime()` is safe and returns `time.Unix(0, 0).UTC()` without panicking.

3. **Validation Semantics (`CheckValid` and `IsValid`)**:
   - Timestamps are valid only if `Seconds` is within `[-62135596800, +253402300799]` (spanning `0001-01-01T00:00:00Z` to `9999-12-31T23:59:59.999999999Z`), and `Nanos` is within `[0, 999999999]`.
   - Out-of-range seconds or nanoseconds, or negative nanoseconds cause `IsValid()` to return false and `CheckValid()` to return an error.
   - Nil receiver reports `IsValid() == false` and `CheckValid()` returns a non-nil error.

4. **Wire and JSON Serialization**:
   - `proto.Marshal` and `proto.Unmarshal` preserve binary representations across wire serialization.
   - `protojson.Marshal` serializes the well-known timestamp type to canonical RFC 3339 formatted JSON string (e.g., `"2026-08-27T20:00:00.500Z"`).
   - `protojson.Unmarshal` parses RFC 3339 strings into `*timestamppb.Timestamp`.
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: Convert between Go time.Time and Protocol Buffers Timestamp using timestamppb New, AsTime, IsValid, and CheckValid with zero and range validation
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/google.golang.org/protobuf@v1.33.0
Demonstrate these symbols/APIs:
  - google.golang.org/protobuf/types/known/timestamppb.New
  - google.golang.org/protobuf/types/known/timestamppb.Timestamp.AsTime
  - google.golang.org/protobuf/types/known/timestamppb.Timestamp.CheckValid
  - google.golang.org/protobuf/types/known/timestamppb.Timestamp.IsValid

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:2d5029c1472ca7cf40539b6b9147aba2de5b347c71cf40bcceafb4c883212c5f","contract":["timestamppb.New converts time.Time into *timestamppb.Timestamp with Seconds and Nanos normalized to UTC, correctly mapping zero time and sub-second nanoseconds.","timestamppb.Timestamp.AsTime converts the protobuf message back to time.Time in UTC, and calling AsTime on a nil receiver safely returns time.Unix(0, 0).UTC().","timestamppb.Timestamp.CheckValid and IsValid validate timestamp bounds from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999999Z and reject negative or overflowing nanoseconds.","timestamppb.Timestamp supports protobuf wire serialization and protojson serialization formatting as an RFC 3339 string."],"goal":"Convert between Go time.Time and Protocol Buffers Timestamp using timestamppb New, AsTime, IsValid, and CheckValid with zero and range validation","kind":"HOW","packages":["pkg:golang/google.golang.org/protobuf@v1.33.0"],"schemaVersion":1,"symbols":["google.golang.org/protobuf/types/known/timestamppb.New","google.golang.org/protobuf/types/known/timestamppb.Timestamp.AsTime","google.golang.org/protobuf/types/known/timestamppb.Timestamp.CheckValid","google.golang.org/protobuf/types/known/timestamppb.Timestamp.IsValid"]},"contractCommand":["go","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.33.0"],"schemaVersion":1,"subject":"pkg:golang/google.golang.org/protobuf@v1.33.0","symbols":["google.golang.org/protobuf/types/known/timestamppb.New","google.golang.org/protobuf/types/known/timestamppb.Timestamp.AsTime","google.golang.org/protobuf/types/known/timestamppb.Timestamp.CheckValid","google.golang.org/protobuf/types/known/timestamppb.Timestamp.IsValid"],"verifierAdapter":"golang@1"}
go.mod
module example.com/timestamppb-verify

go 1.22.0

require google.golang.org/protobuf v1.33.0
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.33.0 h1:uNO2rsAINq/JlFpSdYEKIZ0uKD/R9cpdv0T+yoGwGmI=
google.golang.org/protobuf v1.33.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos=
spec.json
{
  "schemaVersion": 1,
  "goal": "Convert between Go time.Time and Protocol Buffers Timestamp using timestamppb New, AsTime, IsValid, and CheckValid with zero and range validation",
  "kind": "HOW",
  "packages": [
    "pkg:golang/google.golang.org/protobuf@v1.33.0"
  ],
  "symbols": [
    "google.golang.org/protobuf/types/known/timestamppb.New",
    "google.golang.org/protobuf/types/known/timestamppb.Timestamp.AsTime",
    "google.golang.org/protobuf/types/known/timestamppb.Timestamp.CheckValid",
    "google.golang.org/protobuf/types/known/timestamppb.Timestamp.IsValid"
  ]
}
timestamp_test.go
package timestamppbtest

import (
	"testing"
	"time"

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

func TestTimestampNewAndAsTime(t *testing.T) {
	pst := time.FixedZone("PST", -8*3600)

	tests := []struct {
		name      string
		input     time.Time
		wantSec   int64
		wantNanos int32
	}{
		{
			name:      "unix epoch",
			input:     time.Unix(0, 0).UTC(),
			wantSec:   0,
			wantNanos: 0,
		},
		{
			name:      "positive timestamp with nanoseconds",
			input:     time.Date(2026, 8, 27, 20, 30, 45, 123456789, time.UTC),
			wantSec:   time.Date(2026, 8, 27, 20, 30, 45, 0, time.UTC).Unix(),
			wantNanos: 123456789,
		},
		{
			name:      "non-UTC timezone normalized to UTC",
			input:     time.Date(2026, 8, 27, 12, 30, 45, 500000000, pst),
			wantSec:   time.Date(2026, 8, 27, 20, 30, 45, 0, time.UTC).Unix(),
			wantNanos: 500000000,
		},
		{
			name:      "zero time value (0001-01-01T00:00:00Z)",
			input:     time.Time{},
			wantSec:   -62135596800,
			wantNanos: 0,
		},
		{
			name:      "pre-epoch date (1950-01-01)",
			input:     time.Date(1950, 1, 1, 0, 0, 0, 999, time.UTC),
			wantSec:   time.Date(1950, 1, 1, 0, 0, 0, 0, time.UTC).Unix(),
			wantNanos: 999,
		},
	}

	for _, tc := range tests {
		t.Run(tc.name, func(t *testing.T) {
			ts := timestamppb.New(tc.input)
			if ts == nil {
				t.Fatalf("timestamppb.New(%v) returned nil", tc.input)
			}
			if got := ts.GetSeconds(); got != tc.wantSec {
				t.Errorf("GetSeconds() = %d, want %d", got, tc.wantSec)
			}
			if got := ts.GetNanos(); got != tc.wantNanos {
				t.Errorf("GetNanos() = %d, want %d", got, tc.wantNanos)
			}

			// AsTime should round-trip back to original instantaneous time in UTC
			gotTime := ts.AsTime()
			if !gotTime.Equal(tc.input) {
				t.Errorf("AsTime() = %v, want %v", gotTime, tc.input)
			}
			if gotTime.Location() != time.UTC {
				t.Errorf("AsTime() location = %v, want UTC", gotTime.Location())
			}
		})
	}

	// Verify timestamppb.Now() returns a valid recent timestamp
	now := time.Now()
	tsNow := timestamppb.Now()
	if !tsNow.IsValid() {
		t.Errorf("timestamppb.Now() returned invalid timestamp: %v", tsNow)
	}
	if diff := tsNow.AsTime().Sub(now); diff > time.Minute || diff < -time.Minute {
		t.Errorf("timestamppb.Now() time drift too high: got %v, expected near %v", tsNow.AsTime(), now)
	}

	// Verify nil receiver returns time.Unix(0, 0).UTC() safely without panic
	var nilTs *timestamppb.Timestamp
	if got := nilTs.AsTime(); !got.Equal(time.Unix(0, 0).UTC()) || got.Location() != time.UTC {
		t.Errorf("(*timestamppb.Timestamp)(nil).AsTime() = %v, want %v", got, time.Unix(0, 0).UTC())
	}
}

func TestTimestampValidation(t *testing.T) {
	// Valid cases
	validCases := []*timestamppb.Timestamp{
		timestamppb.New(time.Unix(0, 0)),
		timestamppb.New(time.Now()),
		{Seconds: -62135596800, Nanos: 0},                  // min timestamp: 0001-01-01T00:00:00Z
		{Seconds: 253402300799, Nanos: 999999999},          // max timestamp: 9999-12-31T23:59:59.999999999Z
		{Seconds: 0, Nanos: 500000000},
	}

	for _, ts := range validCases {
		if !ts.IsValid() {
			t.Errorf("expected %v to be valid", ts)
		}
		if err := ts.CheckValid(); err != nil {
			t.Errorf("CheckValid() for %v returned unexpected error: %v", ts, err)
		}
	}

	// Nil receiver validation
	var nilTs *timestamppb.Timestamp
	if nilTs.IsValid() {
		t.Errorf("nil timestamp must report IsValid() == false")
	}
	if err := nilTs.CheckValid(); err == nil {
		t.Errorf("nil timestamp must return non-nil error from CheckValid()")
	}

	// Invalid cases: out-of-range nanos, negative nanos, out-of-range seconds
	invalidCases := []struct {
		name string
		ts   *timestamppb.Timestamp
	}{
		{
			name: "negative nanos",
			ts:   &timestamppb.Timestamp{Seconds: 0, Nanos: -1},
		},
		{
			name: "nanos overflow (>= 1e9)",
			ts:   &timestamppb.Timestamp{Seconds: 0, Nanos: 1000000000},
		},
		{
			name: "seconds below minimum bound (< -62135596800)",
			ts:   &timestamppb.Timestamp{Seconds: -62135596801, Nanos: 0},
		},
		{
			name: "seconds above maximum bound (> 253402300799)",
			ts:   &timestamppb.Timestamp{Seconds: 253402300800, Nanos: 0},
		},
	}

	for _, tc := range invalidCases {
		t.Run(tc.name, func(t *testing.T) {
			if tc.ts.IsValid() {
				t.Errorf("expected IsValid() == false for %s (%v)", tc.name, tc.ts)
			}
			if err := tc.ts.CheckValid(); err == nil {
				t.Errorf("expected CheckValid() to fail for %s (%v)", tc.name, tc.ts)
			}
		})
	}
}

func TestTimestampSerialization(t *testing.T) {
	origTime := time.Date(2026, 8, 27, 20, 0, 0, 500000000, time.UTC)
	orig := timestamppb.New(origTime)

	// Binary proto serialization round-trip
	data, err := proto.Marshal(orig)
	if err != nil {
		t.Fatalf("proto.Marshal failed: %v", err)
	}
	var unmarshaled timestamppb.Timestamp
	if err := proto.Unmarshal(data, &unmarshaled); err != nil {
		t.Fatalf("proto.Unmarshal failed: %v", err)
	}
	if !proto.Equal(orig, &unmarshaled) {
		t.Errorf("unmarshaled %v != original %v", &unmarshaled, orig)
	}

	// JSON format serialization (well-known timestamp formats as RFC 3339 string)
	jsonBytes, err := protojson.Marshal(orig)
	if err != nil {
		t.Fatalf("protojson.Marshal failed: %v", err)
	}
	wantJSON := `"2026-08-27T20:00:00.500Z"`
	if string(jsonBytes) != wantJSON {
		t.Errorf("protojson.Marshal() = %s, want %s", string(jsonBytes), wantJSON)
	}

	// JSON format parsing
	var fromJSON timestamppb.Timestamp
	if err := protojson.Unmarshal([]byte(`"2026-08-27T20:00:00.500Z"`), &fromJSON); err != nil {
		t.Fatalf("protojson.Unmarshal failed: %v", err)
	}
	if !proto.Equal(orig, &fromJSON) {
		t.Errorf("fromJSON %v != orig %v", &fromJSON, orig)
	}
}

原始种子者

匿名