Language values and documents
Your application keeps its own structs, records, dataclasses and maps. The typed layer copies them into native documents and copies documents back into them. The native document API stays available beside it for work that needs native fidelity or no conversion.
Choose an interface
| Use | When you want to |
|---|---|
| Language values (encode, decode, typed rows) | Write and read ordinary application data in the types of your language. |
| Documents | Reuse a value in several calls without converting it again, keep duplicate keys and member order exactly, or batch native work. |
| Parse and serialize | Read or write text or bytes at a file or network boundary. See Formats and conversion. |
| Builders and node reads | Construct or walk documents node by node. See Documents and Building documents. |
Example
The example stores three people from language values, runs a query written in the selected format, and decodes each row into a value of the language. The captured result is the decoded rows, encoded again for display.
Store Go structs and read typed rows
queryText holds this document:
| Offset (hex) | Bytes (hex) | Meaning |
|---|---|---|
| 00 | 54 52 4F 4E | magic TRON |
| 04 | 5C 3F6E616D65 | txt "?name" |
| 0A | 0E 0D 00 0100 010000 00 04000000 | array leaf, size 13, shift 0, bitmap 0001, count 1 (root): @4 |
| 17 | 2C 3F65 | txt "?e" |
| 1A | 4C 6E616D65 | txt "name" |
| 1F | 5C 3F6E616D65 | txt "?name" |
| 25 | 0E 15 00 0700 030000 00 17000000 1A0000 00 1F000000 | array leaf, size 21, shift 0, bitmap 0007, count 3 (root): @17 → @1A → @1F |
| 3A | 0E 0D 00 0100 010000 00 25000000 | array leaf, size 13, shift 0, bitmap 0001, count 1 (root): @25 |
| 47 | 5C 3F6E616D65 | txt "?name" |
| 4D | 0E 0D 00 0100 010000 00 47000000 | array leaf, size 13, shift 0, bitmap 0001, count 1 (root): @47 |
| 5A | 5C 7768657265 | txt "where" |
| 60 | 0F 0A 5A000000 3A00 0000 | map leaf, size 10: @5A → @3A |
| 6A | 4C 66696E64 | txt "find" |
| 6F | 0F 0A 6A000000 0A00 0000 | map leaf, size 10: @6A → @A |
| 79 | 7C 6F726465724279 | txt "orderBy" |
| 81 | 0F 0A 79000000 4D00 0000 | map leaf, size 10: @79 → @4D |
| 8B | 07 12 2A000000 6000 0000 6F000000 8100 0000 | map branch, size 18, depth 0 (root), slots 1, 3, 5: @60 → @6F → @81 |
| 9D | 8B000000 00000000 | root → @8B; previous: none |
type Person struct {
Name string `json:"name"`
Role string `json:"role"`
Age int `json:"age"`
}
type Name struct {
Name string `json:"name"`
}
opened, err := stardust.Open(databasePath, stardust.Options{})
if err != nil {
return err
}
defer opened.Close()
people := map[string]Person{
"#_ada": {Name: "Ada", Role: "engineer", Age: 36},
"#_bob": {Name: "Bob", Role: "engineer", Age: 41},
"#_cy": {Name: "Cy", Role: "designer", Age: 29},
}
if _, err := stardust.MergePatchValue(opened, people, nil); err != nil {
return err
}
definition, err := stardust.Parse(queryText, stardust.TRON)
if err != nil {
return err
}
defer definition.Close()
query, err := opened.Query(definition)
if err != nil {
return err
}
defer query.Close()
rows, err := query.Run(nil, stardust.RunOptions{}, nil)
if err != nil {
return err
}
defer rows.Close()
var names []Name
for row, err := range stardust.Values[Name](rows) {
if err != nil {
return err
}
names = append(names, row)
}
result, err := stardust.Encode(names)
if err != nil {
return err
}
defer result.Close()| Offset (hex) | Bytes (hex) | Meaning |
|---|---|---|
| 00 | 54 52 4F 4E | magic TRON |
| 04 | 4C 6E616D65 | txt "name" |
| 09 | 3C 416461 | txt "Ada" |
| 0D | 0F 0A 04000000 0900 0000 | map leaf, size 10: @4 → @9 |
| 17 | 4C 6E616D65 | txt "name" |
| 1C | 3C 426F62 | txt "Bob" |
| 20 | 0F 0A 17000000 1C00 0000 | map leaf, size 10: @17 → @1C |
| 2A | 4C 6E616D65 | txt "name" |
| 2F | 2C 4379 | txt "Cy" |
| 32 | 0F 0A 2A000000 2F00 0000 | map leaf, size 10: @2A → @2F |
| 3C | 0E 15 00 0700 030000 00 0D000000 200000 00 32000000 | array leaf, size 21, shift 0, bitmap 0007, count 3 (root): @D → @20 → @32 |
| 51 | 3C000000 00000000 | root → @3C; previous: none |
Standard JSON values
Any value that the standard JSON encoder of your language accepts also converts here, and decode reads back what encode writes: encoding/json in Go, json.dumps in Python, serde_json in Rust, cheshire or data.json in Clojure and core:encoding/json in Odin. Native tags come first, so instants, durations and links become #utc, #dur and #link values instead of JSON text. Several languages accept more, such as Python sets and UUIDs, or Clojure java.time values. A value is refused only where that encoder refuses it, or where a document cannot hold it: a non-finite number, an integer outside i64, a decimal, instant or duration without an exact native form, or a cycle. The host mapping gives each type.
Ownership and errors
Encode returns a new owned document that holds a snapshot of the value. Close it as you close any document. Decode borrows a document only for the call and returns independent values. It never closes or keeps the document. Typed row iteration borrows the rows and reads one page at a time. Close the rows yourself. Every page of one cursor reads the same store snapshot, so iteration never repeats the query.
A value-argument operation accepts a language value or a document. It passes a document through unchanged. It encodes a language value into a temporary document, calls the native operation once, and closes the temporary document on success and failure.
A conversion failure is invalid_argument with a code and a value path such as people[1].age. A failed decode returns no partly filled value.
Costs
Encode and decode copy every value. A document that you pass directly is not copied. Type inspection belongs only to the typed layer, and each language keeps per-type plans where it inspects types at run time. No conversion writes or reads DUST, EDN or TRON text, and JSON text appears only where a Go value supplies its own MarshalJSON or UnmarshalJSON method. Those formats are optional boundaries, not an intermediate transport.
The conversion rules and the host mapping below give each type, the null and missing-field rules and the strict mode.
Operations
| Operation | Returns | Summary |
|---|---|---|
| FromValue | document | from_value(value) copies host values into an owned document. |
| Document.ToValue | value | document.to_value() copies a document into host values. |
FromValue
func FromValue(value any) (*Document, error)Parameters
| Parameter | Type | Ownership | Default | Meaning |
|---|---|---|---|---|
value | any | Value | Required | A host value to copy into native document nodes. |
Errors
| Status | When |
|---|---|
StatusInvalidArgument | the value has a host type with no document form (one the language's standard JSON encoder also refuses), a number outside i64 or finite f64, a decimal or time with no exact native form, a failing conversion method, or a cycle |
StatusOutOfMemory | native memory is exhausted |
Notes
Host maps cannot preserve duplicate keys. Use native documents when member order or duplicate keys matter.
Examples
Copy a host integer into a native document
result, err := stardust.FromValue(int64(41))
if err != nil {
return err
}
defer result.Close()| Offset (hex) | Bytes (hex) | Meaning |
|---|---|---|
| 00 | 54 52 4F 4E | magic TRON |
| 04 | 02 29000000000000 00 | i64 41 |
| 0D | 04000000 00000000 | root → @4; previous: none |
C exports: stardust_document_builder_create, stardust_document_builder_add_many, stardust_document_builder_seal, stardust_document_builder_error, stardust_document_builder_release
Document.ToValue
func (d *Document) ToValue() (any, error)Errors
| Status | When |
|---|---|
StatusClosed | the document is closed |
Notes
Host map semantics determine how duplicate keys are represented. The copied value survives document closure.
Examples
Copy a native input into a host value
inputText holds this document:
| Offset (hex) | Bytes (hex) | Meaning |
|---|---|---|
| 00 | 54 52 4F 4E | magic TRON |
| 04 | 1C 78 | txt "x" |
| 06 | 02 29000000000000 00 | i64 41 |
| 0F | 0F 0A 04000000 0600 0000 | map leaf, size 10: @4 → @6 |
| 19 | 0F000000 00000000 | root → @F; previous: none |
input, err := stardust.Parse(inputText, stardust.TRON)
if err != nil {
return err
}
defer input.Close()
value, err := input.ToValue()
if err != nil {
return err
}
result, err := stardust.FromValue(value)
if err != nil {
return err
}
defer result.Close()| Offset (hex) | Bytes (hex) | Meaning |
|---|---|---|
| 00 | 54 52 4F 4E | magic TRON |
| 04 | 1C 78 | txt "x" |
| 06 | 02 29000000000000 00 | i64 41 |
| 0F | 0F 0A 04000000 0600 0000 | map leaf, size 10: @4 → @6 |
| 19 | 0F000000 00000000 | root → @F; previous: none |
C exports: stardust_document_count, stardust_document_read_many, stardust_document_i64, stardust_document_f64
Typed operations
These helpers convert language values or call native operations. The nesting limit for typed documents is 128 levels.
DurationFromTicks
func DurationFromTicks(ticks int64) (time.Duration, error)duration_from_ticks(ticks) converts signed native 100 ns ticks to the language's standard duration. This conversion performs no native call. Precision loss and values outside the host range fail. Failures: invalid_argument when the value has the wrong type, loses precision or exceeds the target range.
DurationToTicks
func DurationToTicks(value time.Duration) (int64, error)duration_to_ticks(duration) converts a standard duration to signed native 100 ns ticks. This conversion performs no native call. Precision loss and values outside the native range fail instead of truncating or saturating. Failures: invalid_argument when the value has the wrong type, loses precision or exceeds the target range.
InstantFromTicks
func InstantFromTicks(ticks int64) (time.Time, error)instant_from_ticks(ticks) converts signed native 100 ns ticks since the Unix epoch to the language's standard timestamp. This conversion performs no native call. Precision loss and values outside the host range fail. Failures: invalid_argument when the value has the wrong type, loses precision or exceeds the target range.
InstantToTicks
func InstantToTicks(value time.Time) (int64, error)instant_to_ticks(instant) converts a standard timestamp to signed native 100 ns ticks since the Unix epoch. This conversion performs no native call. Precision loss and values outside the native range fail. Failures: invalid_argument when the value has the wrong type, loses precision or exceeds the target range.
Encode
func Encode[T any](value T) (*Document, error)encode(value) copies a language value into a new owned document that holds an immutable snapshot. The caller closes it. Conversion walks the value directly into one preorder builder batch and serializes no text; only a Go json.Marshaler's JSON output is parsed, by the native JSON codec. Failures carry the value path, such as people[3].age, and leave no document: the temporary builder always closes. Failures: invalid_argument when the value has no document form (a type the language's standard JSON encoder also refuses), a number is outside i64 or finite f64, a decimal, instant or duration has no exact native form, a conversion method of the value fails, the nesting exceeds the depth limit, or the value contains a cycle. out_of_memory when native memory is exhausted.
Decode
func Decode[T any](document *Document, options ...DecodeOptions) (T, error)decode(document, type) copies a document into an independent language value of the requested type. It borrows the document only for the call and never closes or retains it. Reads use bounded bulk node reads. A failure reports the value path and returns no partially filled value. Typed objects refuse duplicate keys; unknown keys are ignored unless strict mode is on. A missing field keeps the language default; explicit null needs a nullable target. Failures: invalid_argument when a node does not match the target type, a number is outside the target range or, as an integer, has no exact form in it, a text does not parse as the target or its key type, a union has several matching variants, a conversion method of the target fails, an object repeats a key or, where a strict mode is offered and on, has an undeclared key. Narrow floating targets round to nearest. closed when the source is closed.
Values
func Values[T any](rows *Rows, options ...DecodeOptions) iter.Seq2[T, error]values(rows, type) lazily decodes the rows of a query cursor one at a time, reading one native page at a time. It borrows the rows and never closes them: close the rows yourself. Each internally read page closes when iteration advances, ends, fails or stops early. All pages read the snapshot of the run that created the cursor, so typed iteration never requeries between pages. A failure is reported once, and then iteration ends. Failures: invalid_argument when a node does not match the target type, a number is outside the target range or, as an integer, has no exact form in it, a text does not parse as the target or its key type, a union has several matching variants, a conversion method of the target fails, an object repeats a key or, where a strict mode is offered and on, has an undeclared key. Narrow floating targets round to nearest. closed when the source is closed.
BuildValue
func BuildValue(expression any, explain *BuildExplain) (*Program, error)build_value(expression) accepts a language value or a borrowed document in place of the document argument of the low-level operation. A document is passed through unchanged. A language value is encoded into a temporary document, the low-level operation runs once, and the temporary document closes on success and failure. A string is a string value; it is never parsed as text. The result is the low-level operation's native owner or record. It calls the low-level build operation. Failures: those of encode for a language value, then those of the low-level operation.
EvaluateValue
func EvaluateValue(program *Program, input any, explain *EvalExplain) (*Document, error)evaluate_value(program, input) accepts a language value or a borrowed document in place of the document argument of the low-level operation. A document is passed through unchanged. A language value is encoded into a temporary document, the low-level operation runs once, and the temporary document closes on success and failure. A string is a string value; it is never parsed as text. The result is the low-level operation's native owner or record. It calls the low-level evaluate operation. Failures: those of encode for a language value, then those of the low-level operation.
QueryValue
func QueryValue(database *Database, definition any) (*Query, error)query_value(database, definition) accepts a language value or a borrowed document in place of the document argument of the low-level operation. A document is passed through unchanged. A language value is encoded into a temporary document, the low-level operation runs once, and the temporary document closes on success and failure. A string is a string value; it is never parsed as text. The result is the low-level operation's native owner or record. It calls the low-level query operation. Failures: those of encode for a language value, then those of the low-level operation.
ExpressionValue
func ExpressionValue(database *Database, definition any, explain *BuildExplain) (*Program, error)expression_value(database, definition) accepts a language value or a borrowed document in place of the document argument of the low-level operation. A document is passed through unchanged. A language value is encoded into a temporary document, the low-level operation runs once, and the temporary document closes on success and failure. A string is a string value; it is never parsed as text. The result is the low-level operation's native owner or record. It calls the low-level expression operation. Failures: those of encode for a language value, then those of the low-level operation.
RunQueryValue
func RunQueryValue(query *Query, parameters any, options RunOptions, explain *QueryExplain) (*Rows, error)run_query_value(query, parameters, options) accepts a language value or a borrowed document in place of the document argument of the low-level operation. A document is passed through unchanged. A language value is encoded into a temporary document, the low-level operation runs once, and the temporary document closes on success and failure. A string is a string value; it is never parsed as text. The result is the low-level operation's native owner or record. It calls the low-level run operation. Failures: those of encode for a language value, then those of the low-level operation.
MutationValue
func MutationValue(database *Database, definition any) (*Mutation, error)mutation_value(database, definition) accepts a language value or a borrowed document in place of the document argument of the low-level operation. A document is passed through unchanged. A language value is encoded into a temporary document, the low-level operation runs once, and the temporary document closes on success and failure. A string is a string value; it is never parsed as text. The result is the low-level operation's native owner or record. It calls the low-level mutation operation. Failures: those of encode for a language value, then those of the low-level operation.
RunMutationValue
func RunMutationValue(mutation *Mutation, parameters any, options RunOptions, explain *MutationExplain) (Commit, error)run_mutation_value(mutation, parameters, options) accepts a language value or a borrowed document in place of the document argument of the low-level operation. A document is passed through unchanged. A language value is encoded into a temporary document, the low-level operation runs once, and the temporary document closes on success and failure. A string is a string value; it is never parsed as text. The result is the low-level operation's native owner or record. It calls the low-level run operation. Failures: those of encode for a language value, then those of the low-level operation.
MergePatchValue
func MergePatchValue(database *Database, patch any, explain *PatchExplain) (Commit, error)merge_patch_value(database, patch) accepts a language value or a borrowed document in place of the document argument of the low-level operation. A document is passed through unchanged. A language value is encoded into a temporary document, the low-level operation runs once, and the temporary document closes on success and failure. A string is a string value; it is never parsed as text. The result is the low-level operation's native owner or record. It calls the low-level merge_patch operation. Failures: those of encode for a language value, then those of the low-level operation.
PatchDefinitionValue
func PatchDefinitionValue(database *Database, kind, path string, patch any) (Commit, error)patch_definition_value(database, kind, path, patch) accepts a language value or a borrowed document in place of the document argument of the low-level operation. A document is passed through unchanged. A language value is encoded into a temporary document, the low-level operation runs once, and the temporary document closes on success and failure. A string is a string value; it is never parsed as text. The result is the low-level operation's native owner or record. It calls the low-level patch_definition operation. Failures: those of encode for a language value, then those of the low-level operation.
Conversion rules
| Value | Rule |
|---|---|
standard | Every value that the language's standard JSON encoder accepts converts: encoding/json in Go, json.dumps in Python, serde_json in Rust, cheshire or data.json in Clojure and core:encoding/json in Odin. Decode reads back what encode writes. Refusals remain only where that encoder refuses, or where a document cannot hold the value: a non-finite number, an integer outside i64, an inexact decimal, instant or duration, and a cycle. |
null | A nullable target (pointer, option, Maybe, nil slice or map, None, nil) accepts null. A non-nullable target refuses it with wrong_kind. Explicit null is not a missing field. |
boolean | Only booleans: no truthiness and no number or string coercion. |
integer | Numbers are i64 or f64. A host integer of any width or signedness converts when it fits i64; a larger one fails with out_of_range, in both directions. Narrower targets are range-checked (out_of_range). |
real | Finite f64 only; NaN and infinities are refused. An integer decodes into a floating target only when exactly representable, and a real into an integer target only when finite, integral and in range. f32 narrowing refuses overflow and rounds to nearest. An exact decimal (Python Decimal, Clojure BigDecimal) is an i64 when integral and in range, otherwise the f64 of its shortest spelling; any other decimal fails with inexact_number. |
text | Valid UTF-8, copied without normalization. Invalid UTF-8 and unpaired surrogates are refused. A string argument is a string value; it is never parsed as document text. Values that the standard JSON encoder writes as text stay text: UUIDs, dates and times that are not instants, Go TextMarshaler values, and Go and Clojure byte arrays as base64. Text that does not parse as a typed target fails with invalid_value. |
array | Ordered collections, including tuples, sets and Java collections. A fixed-length target needs the exact length (length_mismatch). A nil slice or list encodes null; an allocated empty one encodes an empty array. |
object | Struct, record or dataclass fields and maps. Field names follow the standard encoder's tags and embedding rules; Go also matches a key case-insensitively after an exact match, as encoding/json does. Map keys that are not strings become member keys as the standard encoder spells them (decimal integers, true, false, enum names, MarshalText text) and parse back into typed keys. Typed decode refuses a repeated key (duplicate_field); native documents keep both members. Unknown keys are ignored unless strict mode refuses them (unknown_field). A missing field keeps the language default or fails as required (missing_field). |
enum | Enums use the standard encoder's form: Rust variants as serde represents them, Python Enum members as their value, Odin enums by name. Odin unions write their active variant and decode into the one variant whose shape matches (ambiguous_variant otherwise). |
tagged | Native tags take priority over any JSON spelling. Links, UTC instants and durations use the native {#link id}, {#utc text} and {#dur text} objects through the Link type and standard-library instant and duration types. Rust uses #[serde(with = "stardust::Utc")] and #[serde(with = "stardust::Dur")] field adapters to select native tags without guessing from record names. Extra types are only for native values that the standard library cannot represent, such as signed Rust durations. An ordinary object is never reinterpreted as a tagged value. A time value that is not a whole number of 100 ns ticks is refused. Direct converters report inexact_number; Rust Serde adapter errors use the custom-hook codes unsupported_type on encode and wrong_kind on decode, with the field path. |
hooks | Conversion methods run as the standard encoder runs them: Go Encoder and Decoder hooks first, then json.Marshaler, encoding.TextMarshaler and their decode methods; Rust Serialize and Deserialize; Odin registered converters. A failing Go JSON or text method fails with hook_failed; other hooks return their own error. Only Go's JSON methods exchange JSON text, through the native JSON codec. |
limits | Recursive conversions refuse nesting beyond the depth limit with too_deep. Go and Python untyped decode traverse iteratively and accept deeper documents. Cyclic host values fail with cycle, or too_deep in Clojure. Every failure has status invalid_argument, a code and a value path such as people[3].age or tags["a.b"]. Failed conversions return no partial value or document. |
Host mapping
Typed encode and decode, and the untyped from_value and to_value where the language offers them, use this mapping. Each conversion walks values directly; no text format is involved.
| Value | Host | Document | Back | Meaning |
|---|---|---|---|---|
null | nil | null | nil | Nil slices and maps also become null. |
integer | signed integers | i64 | int64 | Signed host integers become i64. |
float | float32 or float64 | f64 | float64 | The conversion refuses non-finite numbers. |
text | string | UTF-8 string | string | The conversion refuses incorrect UTF-8. |
array | slices and arrays | array | []any (ToValue) or the target type (Decode) | Every slice and array type converts; a byte slice is base64 text. |
object | maps and structs | object | map[string]any (ToValue) or the target type (Decode) | Map members use byte-sorted key order; struct fields follow encoding/json tags and embedding. |
map_keys | integer or TextMarshaler map keys | member key text | the same key types (Decode) | Integer keys are decimal text and TextMarshaler keys their text, as encoding/json writes them. |
bytes | []byte | base64 string | []byte (Decode) | As encoding/json writes byte slices. A [N]byte array stays an array of numbers. |
enum | TextMarshaler or json.Marshaler types | their text or parsed JSON | TextUnmarshaler or json.Unmarshaler (Decode) | Go has no enum types. MarshalJSON output is parsed by the native JSON codec; UnmarshalJSON receives the node's native JSON text. |
text_values | json.Number | i64 or f64 | json.Number (Decode) | Text that is not a JSON number fails with invalid_value. |
decimal | json.Number with a fraction | f64 | json.Number (Decode) | Go has no decimal type. |
collections | arrays, slices and maps of any element type | array or object | the same types (Decode) | Typed collections need no []any or map[string]any copy. |
unsigned | unsigned integers | i64 | unsigned integers (Decode) | A value that fits i64 becomes an i64; a larger one fails with out_of_range in both directions. |
non_finite | NaN or infinite float | refused | not produced | JSON has no spelling for them, and documents hold finite f64 only. |
time | time.Time or time.Duration | UTC or duration tagged object | time.Time or time.Duration (Decode) | Values must be whole 100 ns ticks. ToValue returns the tagged object as a map. |
to_value_numbers | document number | i64 or f64 | int64 or float64 | The conversion tries typed i64 reads before f64. |
duplicate_keys | document object | duplicate members | first value | Host maps retain the first value for a duplicate key. |