// Copyright 2024 Google LLC
// SPDX-License-Identifier: Apache-2.0
package base
import (
"context"
)
// A ContextKey is a unique, typed key for a value stored in a context.
type ContextKey[T any] struct {
key *int
}
// NewContextKey returns a context key for a value of type T.
func NewContextKey[T any]() ContextKey[T] {
return ContextKey[T]{key: new(int)}
}
// NewContext returns ctx augmented with this key and the given value.
func (k ContextKey[T]) NewContext(ctx context.Context, value T) context.Context {
return context.WithValue(ctx, k.key, value)
}
// FromContext returns the value associated with this key in the context,
// or the internal.Zero value for T if the key is not present.
func (k ContextKey[T]) FromContext(ctx context.Context) T {
t, _ := ctx.Value(k.key).(T)
return t
}