values

package
v0.4.18 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 18, 2026 License: MIT Imports: 11 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Shared values

Value is two words: R uint64 and P unsafe.Pointer. The operation supplies its Type; presence is separate. Type defines nominal identity and the Raw/Pointer/Pair representation. Shape describes storage.

P must be a real GC-visible pointer or nil. Never hide pointers in R or put integer payloads in P.

Payloads

  • Integers: decoded bits in R; narrow signed values are sign-extended.
  • Floats: IEEE bits in R; float32 uses the low 32 bits.
  • Strings/immutable bytes: length in R, backing pointer in P. Borrowing allocates no wrapper; the backing storage must remain valid and immutable.
  • Mutable slices: uint32 length/capacity in R, backing pointer in P. Header copies preserve aliases.
  • Functions: program-local reference index + 1 in R; zero means nil. Closures retain immutable capture cells in P; mutable captured variables share cells.
  • Time: Unix nanoseconds plus a reserved zero sentinel when they fit; otherwise a 12-byte integer payload preserves Unix seconds and nanoseconds. The instant immediately before the epoch uses a shared payload to avoid the zero sentinel. AsTime returns UTC and preserves precision/range, not timezone or monotonic readings. Legacy string timestamps remain readable.
  • KVO records/collections: compact typed pairs with a physical representation ID.

TypedPair packs tag 0110, a 28-bit representation ID and a 32-bit auxiliary value in R, with the payload pointer in P. Register immutable Shape metadata once; IDs are process-lifetime and never reclaimed. An encoded byte span uses its auxiliary word for length. Concrete scalar code must not interpret arbitrary numeric bits as tags: its declared type wins.

Interfaces

TypeTable packs/unpacks exact dynamic types. Scalars use marker pointers in P and retain all 64 payload bits in R. Check markers before interpreting tags. Only (R=0, P=nil) is a nil interface; typed nil, false and numeric zero are not. Use Unpack; P need not point to a box.

Prefix Remaining R payload
0000 60-bit concrete type ID; P is the direct pointer or fallback box
0100 60-bit plain string length
10 / 11 32-bit length and 30-bit spare capacity for the selected byte/any slice type
0001 16-bit exact type ID and 44-bit string length
0011 16-bit exact type ID, 12-bit spare capacity and 32-bit length
0101 16-bit exact type ID, 22-bit spare capacity and 22-bit length

| 0110 | 28-bit representation ID and 32-bit auxiliary value |

Implicit slice tags select exact linked types. Capacity is length + spare. Values that do not fit use a Value box; functions also box in interfaces. JSON maps/arrays still allocate their storage even when their interface header needs no box. Equality/hash respects named types, comparability, NaNs and signed zero. Program-local type IDs and markers cannot be copied into another program without repacking.

Aggregate storage

NewStructShape and NewPointerShape create nominal identities; construct and reuse them during setup. The linker snapshots their graph. VM structs/arrays use flattened, GC-scanned cells. Register aggregate values point to immutable snapshots; loads/stores copy aggregate cells. Pointer moves preserve aliases. An extra cell keeps trailing zero-sized field addresses inside the allocation.

Shape.Stored borrows a view; snapshot it before exposing an immutable value. Shape.Store copies aggregates and clears unused scalar halves. Never mutate an aggregate snapshot. Map keys/values must be snapshots, though referenced maps, slices and pointers retain normal aliases.

Shape helpers operate on VM cells, not arbitrary native Go pointers. nativebind supplies Go layouts and field operations. KVO uses these same native operations. Raw codec fields remain codec metadata; convert them to Value with the declared encoding.

See EVM and KVO access.

Documentation

Overview

Package values defines two-word values shared by KVO adapters and EVM. Concrete types and presence are supplied separately; interface values encode their dynamic type using a program-local TypeTable.

Index

Constants

View Source
const NativeAddress uint64 = 1

NativeAddress marks a pointer into live Go memory. A pointer with R=0 refers to VM cells. The pointer's static type determines whether it carries this discriminator; opaque interface receivers continue to use their own ABI.

Variables

View Source
var (
	IntType     = NewType("int", Raw)
	UintType    = NewType("uint", Raw)
	UintptrType = NewType("uintptr", Raw)
	Int8        = NewType("int8", Raw)
	Int16       = NewType("int16", Raw)
	Int32       = NewType("int32", Raw)
	Uint8       = NewType("uint8", Raw)
	Uint16      = NewType("uint16", Raw)
	Uint32      = NewType("uint32", Raw)
	Float32Type = NewType("float32", Raw)
)
View Source
var (
	Int64      = NewType("i64", Raw)
	Uint64     = NewType("u64", Raw)
	Float64    = NewType("f64", Raw)
	Boolean    = NewType("bool", Raw)
	StringType = NewOwnedType("string", Pair, ownString)
	AnyType    = NewType("any", Pair)
	ErrorType  = NewType("error", Pair)
)
View Source
var TimeType = NewOwnedType("time.Time", Pair, func(v Value, b OwnershipBudget) (Value, error) {
	if v.P == nil {
		return v, nil
	}
	if err := b.ChargeAllocation(v.R); err != nil {
		return Value{}, err
	}
	return Bytes(append([]byte(nil), v.AsBytes()...)), nil
})

Functions

func CellAt

func CellAt(p unsafe.Pointer, n uint64) unsafe.Pointer

Types

type Codec

type Codec[T any] struct {
	Type   reflect.Type
	Decode func(Value) T
	Encode func(T) Value
}

Codec converts between a cell and a Go value. Its functions do not inspect runtime types. Type is declaration metadata, used only when binding a codec. Strings and bytes borrow their input storage in both directions.

func BoolCodec

func BoolCodec[T ~bool]() Codec[T]

func BytesCodec

func BytesCodec[T ~[]byte]() Codec[T]

func Float32Codec

func Float32Codec[T ~float32]() Codec[T]

func Float64Codec

func Float64Codec[T ~float64]() Codec[T]

func SignedCodec

func SignedCodec[T Signed]() Codec[T]

func StringCodec

func StringCodec[T ~string]() Codec[T]

func TimeCodec

func TimeCodec() Codec[time.Time]

func UnsignedCodec

func UnsignedCodec[T Unsigned]() Codec[T]

type ComparisonError

type ComparisonError struct {
	Type string
	Hash bool
}

ComparisonError is a Go language panic condition, distinct from corrupt interface storage. EVM may recover it; invalid type indexes stay fatal.

func (*ComparisonError) Error

func (e *ComparisonError) Error() string

type DynamicType

type DynamicType struct {
	Shape      *Shape
	Comparable bool
}

type Field

type Field struct {
	Embedded bool
	Tag      string
	Name     string
	Shape    *Shape
	Offset   uint64
}

type Kind

type Kind uint8
const (
	BoolKind Kind = iota + 1
	IntKind
	UintKind
	FloatKind
	StringKind
	PointerKind
	StructKind
	ArrayKind
	SliceKind
	MapKind
	ComplexKind
	FunctionKind
	InterfaceKind
	// TypedPairKind carries a registered physical layout and auxiliary word.
	TypedPairKind
	TimestampKind
)

type Map

type Map struct {
	Key   *Shape
	Types *TypeTable
	// contains filtered or unexported fields
}

Map stores immutable key/value snapshots. Mutable values inside them (pointers, maps and slices) retain Go aliasing. Deleted entries remain only in iterators.

func NewMap

func NewMap(key *Shape, ts *TypeTable) *Map

func (*Map) Clear

func (m *Map) Clear()

func (*Map) Delete

func (m *Map) Delete(k Value, h uint64) error

func (*Map) DeleteContext

func (m *Map) DeleteContext(ctx context.Context, k Value, h uint64) error

func (*Map) Entries

func (m *Map) Entries() []*MapEntry

Entries snapshots the existing iteration range; insertions may be skipped. Updates are observed and deleted entries are skipped by the iterator.

func (*Map) EntryCount

func (m *Map) EntryCount() uint64

func (*Map) Find

func (m *Map) Find(k Value, h uint64) (*MapEntry, bool, error)

func (*Map) FindContext

func (m *Map) FindContext(ctx context.Context, k Value, h uint64) (*MapEntry, bool, error)

func (*Map) Len

func (m *Map) Len() int

func (*Map) ProbeCount

func (m *Map) ProbeCount(hash uint64) uint64

func (*Map) Put

func (m *Map) Put(k, v Value, h uint64) error

func (*Map) PutContext

func (m *Map) PutContext(ctx context.Context, k, v Value, h uint64) error

type MapEntry

type MapEntry struct {
	Key, Value Value
	Live       bool
}

type Method

type Method struct {
	ID        string
	Signature *Shape
}

Method is a receiver-free interface requirement. ID includes the defining package path for unexported methods.

type NativeField

type NativeField struct {
	Offset uintptr
	Get    func(unsafe.Pointer) Value
	Set    func(unsafe.Pointer, Value)
}

type NativeLayout

type NativeLayout struct {
	Size   uint64
	New    func() unsafe.Pointer
	Load   func(unsafe.Pointer) Value
	Store  func(unsafe.Pointer, Value)
	Fields []NativeField
}

NativeLayout supplies operations on Go memory, independently of VM cells. Load returns decoded scalars/strings, native pointer targets, or a borrowed native aggregate address. VM aggregate conversion remains an explicit step.

type OwnFunc

type OwnFunc func(Value, OwnershipBudget) (Value, error)

OwnFunc discharges borrowed-storage dependencies while preserving the logical value. It may return already independent values unchanged. Mutable identity needs an explicit contract; a shallow copy is not generally sufficient.

type OwnershipBudget

type OwnershipBudget interface {
	ChargeAllocation(uint64) error
	ContextErr() error
}

OwnershipBudget is supplied at ownership boundaries, never on ordinary reads. ChargeAllocation must succeed before allocating a clone's backing storage.

type Repr

type Repr uint8
const (
	Raw     Repr = 1
	Pointer Repr = 2
	Pair         = Raw | Pointer
)

type RepresentationID

type RepresentationID uint32

RepresentationID identifies immutable physical-layout metadata. Several representations may share a logical Type. IDs are process-local, never reused, and must not be persisted or allocated per value or transaction.

func RegisterRepresentation

func RegisterRepresentation(shape *Shape) RepresentationID

RegisterRepresentation publishes a physical layout for a compact typed pair. The supplied shape and its reachable metadata must remain immutable.

func (RepresentationID) Shape

func (id RepresentationID) Shape() *Shape

type Shape

type Shape struct {
	Native *NativeLayout // optional live Go representation, distinct from Cells
	// DisplayName is optional source-language spelling, prepared at compile time.
	DisplayName string
	Methods     []Method

	Params, Results []*Shape
	// PointerLike gives opaque typed pairs pointer nil semantics: P == nil is
	// the zero value regardless of representation metadata. Other pairs may
	// legitimately carry nonzero auxiliary data with a nil pointer.
	PointerLike bool
	Variadic    bool
	Type        *Type
	Kind        Kind
	Bits        uint8
	Elem, Key   *Shape
	Fields      []Field
	Len         uint64
	Cells       uint64
}

Shape describes typed VM storage. Descriptors, including recursive graphs, are built before use and never mutated by execution. Link snapshots them. Scalar cells hold one Value. Structs/arrays flatten their members into cells; their register values point to immutable snapshots (nil means all zero).

func NewPointerShape

func NewPointerShape(elem *Shape) *Shape

NewPointerShape declares a pointer to VM cell storage. Reuse the result when declaring signatures and TypeDecls. Live native Go pointers instead use the NativeSchema produced by bindings, which supplies their native layout.

func NewStructShape

func NewStructShape(name string, fields ...Field) *Shape

NewStructShape declares a nominal VM struct using the same Shape and Field metadata as compiled structs. It copies the fields and computes cell offsets; supplied offsets are ignored. Child shapes must be fully laid out already. Build and retain shapes during setup. Type identity is by pointer, not name.

func (*Shape) Aggregate

func (s *Shape) Aggregate() bool

func (*Shape) Comparable

func (s *Shape) Comparable() bool

func (*Shape) Equal

func (s *Shape) Equal(a, b Value, ts *TypeTable) (bool, error)

func (*Shape) EqualContext

func (s *Shape) EqualContext(ctx context.Context, a, b Value, ts *TypeTable) (bool, error)

EqualContext allows cancellation during traversal of compound values.

func (*Shape) GetField

func (s *Shape) GetField(p unsafe.Pointer, i int) Value

GetField borrows a field of VM cell storage. Aggregate fields point into that storage; use the field shape's Store to copy them. p must be nonnil storage for this struct shape, never a pointer to a native Go struct.

func (*Shape) Hash

func (s *Shape) Hash(v Value, ts *TypeTable) (uint64, error)

func (*Shape) HashContext

func (s *Shape) HashContext(ctx context.Context, v Value, ts *TypeTable) (uint64, error)

HashContext allows cancellation during traversal of compound values.

func (*Shape) NativeStorage

func (s *Shape) NativeStorage() bool

NativeStorage reports whether this shape supports live native allocation. VM collection and interface layouts remain distinct from Go storage.

func (*Shape) New

func (s *Shape) New() unsafe.Pointer

New allocates zeroed VM cell storage for this shape, not a native Go object. The extra cell gives even a trailing zero-sized field an address in the allocation, matching VM allocations. All writes use Go write barriers.

func (*Shape) SetField

func (s *Shape) SetField(p unsafe.Pointer, i int, v Value)

SetField writes a field of VM cell storage. Scalar pointers alias their targets; aggregate fields copy their cells, using the same Store as the VM.

func (*Shape) Store

func (s *Shape) Store(p unsafe.Pointer, v Value)

func (*Shape) Stored

func (s *Shape) Stored(p unsafe.Pointer) Value

func (*Shape) Work

func (s *Shape) Work(v Value, limit uint64, ts *TypeTable) (uint64, bool)

Work bounds traversal of a value before hashing/comparison. It follows value fields only, never pointers; repeated string fields count each traversal.

type Signed

type Signed interface {
	~int | ~int8 | ~int16 | ~int32 | ~int64
}

type Type

type Type struct {
	// contains filtered or unexported fields
}

Type is external metadata. Identity is by pointer, not by name.

func NewOwnedType

func NewOwnedType(name string, repr Repr, own OwnFunc) *Type

func NewType

func NewType(name string, repr Repr) *Type

func (*Type) CanOwn

func (t *Type) CanOwn() bool

func (*Type) Name

func (t *Type) Name() string

func (*Type) Own

func (t *Type) Own(v Value, b OwnershipBudget) (Value, error)

func (*Type) Repr

func (t *Type) Repr() Repr

type TypeTable

type TypeTable struct {
	// contains filtered or unexported fields
}

TypeTable owns the program-local identities and encoding of interface values. Entry zero is nil. The table and its descriptors are immutable after creation.

func NewTypeTable

func NewTypeTable(types []DynamicType) *TypeTable

func (*TypeTable) Comparable

func (ts *TypeTable) Comparable(id uint64) bool

func (*TypeTable) Index

func (ts *TypeTable) Index(v Value) uint64

Index extracts the dynamic type ID; Unpack validates the payload. Scalar markers must be checked first: their R contains all 64 bits.

func (*TypeTable) Inline

func (ts *TypeTable) Inline(id uint64, v Value) (Value, bool)

Inline packs a concrete payload without allocation. Callers box the payload when it does not fit. Aggregates must already be immutable snapshots.

func (*TypeTable) Unpack

func (ts *TypeTable) Unpack(v Value) (*Shape, Value, error)

type Unsigned

type Unsigned interface {
	~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr
}

type Value

type Value struct {
	R uint64
	P unsafe.Pointer
}

func Bool

func Bool(v bool) Value

func Bytes

func Bytes(b []byte) Value

Bytes borrows an immutable byte span. R is its byte length, unlike a mutable VM slice whose header packs length and capacity. The external type distinguishes byte spans, strings and VM slices. The backing bytes must outlive this value.

func CellSlice

func CellSlice(p unsafe.Pointer, n uint64) []Value

func Float

func Float(v float64) Value

func Float32

func Float32(v float32) Value

func Int

func Int(v int64) Value

func SliceValue

func SliceValue(p unsafe.Pointer, length, capacity uint32) Value

func String

func String(v string) Value

String retains the immutable string data without allocating a wrapper.

func Time

func Time(t time.Time) Value

Time stores nanoseconds in one word when they fit, with zero reserved for time.Time{}. Dates outside that range use a 12-byte integer payload (uint32 nanoseconds, int64 Unix seconds, big endian). No precision or date range is lost. Like database timestamps, the value denotes an instant, without a monotonic clock reading or timezone. AsTime returns UTC.

func TypedPair

func TypedPair(id RepresentationID, p unsafe.Pointer, aux uint32) Value

TypedPair keeps a real GC-visible pointer and a 32-bit auxiliary word in one cell. The ID must come from RegisterRepresentation. Auxiliary data commonly holds the length of an immutable byte span; it is not a second pointer.

func Uint

func Uint(v uint64) Value

func (Value) AsBool

func (v Value) AsBool() bool

func (Value) AsBytes

func (v Value) AsBytes() []byte

func (Value) AsFloat

func (v Value) AsFloat() float64

func (Value) AsFloat32

func (v Value) AsFloat32() float32

func (Value) AsInt

func (v Value) AsInt() int64

func (Value) AsString

func (v Value) AsString() string

AsString requires StringType. The data must remain valid and immutable.

func (Value) AsTime

func (v Value) AsTime() time.Time

func (Value) AsUint

func (v Value) AsUint() uint64

func (Value) Auxiliary

func (v Value) Auxiliary() uint32

func (Value) Representation

func (v Value) Representation() RepresentationID

Representation returns zero for an untagged value. Concrete scalar callers must not interpret arbitrary numeric bits as tags: their external type wins.

func (Value) SliceCap

func (v Value) SliceCap() uint32

func (Value) SliceLen

func (v Value) SliceLen() uint32

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL