Documentation
¶
Overview ¶
Package rustyon implements Rusty Object Notation (RON), the human readable data format used throughout the Rust ecosystem.
rustyon is an independent implementation and is not affiliated with the ron-rs project. It follows the grammar of current ron-rs releases, including raw strings, byte strings, nested block comments, integer and float suffixes and the #![enable(...)] extensions.
The package offers four layers:
- Marshal, Unmarshal, Encoder and Decoder convert between RON and Go values, in the style of encoding/json.
- Parse and Value give a dynamic tree for documents whose shape is not known in advance.
- Registry maps Rust enums onto Go interfaces so that variants such as Circle(radius: 1.0) decode into concrete Go types.
- Format pretty prints RON documents while preserving comments.
A short example:
type Config struct {
WindowTitle string
MaxFPS *int
}
var c Config
err := rustyon.Unmarshal([]byte(`(window_title: "Game", max_fps: Some(60))`), &c)
Go field names are converted to snake_case by default, so WindowTitle matches window_title. See Marshal and Unmarshal for the full mapping.
Index ¶
- Variables
- func Equal(a, b Value) bool
- func Format(src []byte) ([]byte, error)
- func FormatIndent(src []byte, indent string) ([]byte, error)
- func FromValue(v Value, target any) error
- func Marshal(v any) ([]byte, error)
- func MarshalIndent(v any, prefix, indent string) ([]byte, error)
- func RegisterEnum[I any](variants ...VariantSpec)
- func RegisterEnumIn[I any](r *Registry, variants ...VariantSpec)
- func RegisterUnitEnum[T comparable](names map[T]string)
- func RegisterUnitEnumIn[T comparable](r *Registry, names map[T]string)
- func Unmarshal(data []byte, v any) error
- func Valid(data []byte) bool
- type Bool
- type Bytes
- type Char
- type Decoder
- type Document
- type Encoder
- type Extensions
- type Field
- type Float
- type Ident
- type Int
- type InvalidUnmarshalError
- type Kind
- type List
- type Map
- type MapEntry
- type Marshaler
- type MarshalerError
- type Option
- type Position
- type Registry
- type String
- type Struct
- type SyntaxError
- type Tuple
- type Unit
- type UnknownFieldError
- type UnmarshalTypeError
- type Unmarshaler
- type UnsupportedTypeError
- type UnsupportedValueError
- type Value
- type VariantSpec
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var DefaultRegistry = NewRegistry()
DefaultRegistry is the registry used by Marshal, Unmarshal and by encoders and decoders that have no registry set.
var None = Option{}
None is the empty Option.
Functions ¶
func Equal ¶
Equal reports whether a and b are structurally equal. Floats compare by value, except that NaN equals NaN so that documents containing NaN compare equal to themselves. Nil values are equal only to nil.
func Format ¶
Format reformats a RON document in a canonical style while preserving comments, literal spellings (number bases, raw strings, escapes) and the author's choice between single line and multi line collections:
- A collection whose contents span several lines in the input, or that contains comments, is written with one element per line, indented by four spaces, with trailing commas.
- A collection written on one line stays on one line, with ", " between elements and ": " after keys.
- A single nested collection inside a tuple, such as Some((...)), hugs its parent's parentheses.
- Single blank lines between elements are kept; longer runs are collapsed.
Format is idempotent. It returns a *SyntaxError if src is not valid RON.
Example ¶
package main
import (
"log"
"os"
"github.com/peltonapp/rustyon-go"
)
func main() {
src := []byte(`(name:"x", // the name
tags:[1,2,3])`)
out, err := rustyon.Format(src)
if err != nil {
log.Fatal(err)
}
os.Stdout.Write(out)
}
Output: ( name: "x", // the name tags: [1, 2, 3], )
func FormatIndent ¶
FormatIndent is like Format but uses indent for each nesting level.
func FromValue ¶
FromValue stores a parsed Value in the Go value pointed to by target, following the rules of Unmarshal.
func Marshal ¶
Marshal returns the compact RON encoding of v.
Go values map to RON as follows:
- bool, integers, floats and strings map to the matching literals. Integers of any size are supported through big.Int.
- []byte maps to a byte string b"...".
- Slices and arrays map to lists [a, b].
- Maps map to {k: v}, with entries sorted by key.
- Structs map to (field: value). Field names default to the snake_case form of the Go name and can be changed with a `ron:"name"` tag. The options omitempty and omitzero skip empty or zero fields, and "-" skips a field. A blank field of type struct{} named _ with the tag `ron:"Name,tuple"` sets the struct's RON name and, with the tuple option, encodes the struct as a tuple struct (a, b).
- Pointers map to Option: nil is None and anything else is Some(v).
- Nil interfaces map to None.
- Types registered as enum variants (see Registry) map to Name, Name(a, b) or Name(field: v).
- Value trees are written as they are.
- Types implementing Marshaler or encoding.TextMarshaler are marshaled with those methods; text becomes a RON string.
Channels, functions and complex numbers cannot be encoded.
func MarshalIndent ¶
MarshalIndent is like Marshal but writes one element per line. Each line starts with prefix followed by one copy of indent per nesting level.
Example ¶
package main
import (
"fmt"
"log"
"github.com/peltonapp/rustyon-go"
)
func main() {
type Player struct {
Name string
MaxHP int
Pos struct {
_ struct{} `ron:",tuple"`
X, Y float64
}
}
p := Player{Name: "Ferris", MaxHP: 100}
p.Pos.X, p.Pos.Y = 1, 2.5
out, err := rustyon.MarshalIndent(p, "", " ")
if err != nil {
log.Fatal(err)
}
fmt.Println(string(out))
}
Output: ( name: "Ferris", max_hp: 100, pos: (1.0, 2.5), )
func RegisterEnum ¶
func RegisterEnum[I any](variants ...VariantSpec)
RegisterEnum registers the interface type I as an enum with the given variants in DefaultRegistry. It panics if I is not an interface type, if a variant does not implement I, or if names or types are duplicated. Registering the same interface again adds variants to it.
Example ¶
package main
import (
"fmt"
"log"
"github.com/peltonapp/rustyon-go"
)
type Shape interface{ isShape() }
type Circle struct{ Radius float64 }
type Square struct {
_ struct{} `ron:",tuple"`
Side float64
}
type Dot struct{}
func (Circle) isShape() {}
func (Square) isShape() {}
func (Dot) isShape() {}
func main() {
// In real code this goes into an init function.
rustyon.RegisterEnum[Shape](
rustyon.Variant[Circle]("Circle"),
rustyon.Variant[Square]("Square"),
rustyon.Variant[Dot]("Dot"),
)
var shapes []Shape
err := rustyon.Unmarshal([]byte(`[Circle(radius: 1.5), Square(2.0), Dot]`), &shapes)
if err != nil {
log.Fatal(err)
}
for _, s := range shapes {
fmt.Printf("%T %+v\n", s, s)
}
out, _ := rustyon.Marshal(shapes)
fmt.Println(string(out))
}
Output: rustyon_test.Circle {Radius:1.5} rustyon_test.Square {_:{} Side:2} rustyon_test.Dot {} [Circle(radius:1.5),Square(2.0),Dot]
func RegisterEnumIn ¶
func RegisterEnumIn[I any](r *Registry, variants ...VariantSpec)
RegisterEnumIn is like RegisterEnum but registers into r.
func RegisterUnitEnum ¶
func RegisterUnitEnum[T comparable](names map[T]string)
RegisterUnitEnum registers T as an enum whose variants carry no data, such as a set of integer constants. names maps each value to its variant name. Values of T encode as bare identifiers and decode from identifiers or strings. It panics if a name is invalid or used twice.
Example ¶
package main
import (
"fmt"
"log"
"github.com/peltonapp/rustyon-go"
)
type Level int
const (
Easy Level = iota
Hard
)
func main() {
rustyon.RegisterUnitEnum(map[Level]string{Easy: "Easy", Hard: "Hard"})
var l Level
if err := rustyon.Unmarshal([]byte("Hard"), &l); err != nil {
log.Fatal(err)
}
out, _ := rustyon.Marshal(struct{ Difficulty Level }{l})
fmt.Println(l == Hard, string(out))
}
Output: true (difficulty:Hard)
func RegisterUnitEnumIn ¶
func RegisterUnitEnumIn[T comparable](r *Registry, names map[T]string)
RegisterUnitEnumIn is like RegisterUnitEnum but registers into r.
func Unmarshal ¶
Unmarshal parses the RON document in data and stores the result in the value pointed to by v. It is the inverse of Marshal and accepts the following in addition to the mapping described there:
- Struct fields match by name exactly, then case-insensitively. Unknown fields are ignored unless Decoder.DisallowUnknownFields is used. Struct names in the input are not checked.
- Structs also decode from tuples (by position) and from maps with string keys.
- Pointers accept None, Some(v) and a plain v (implicit_some).
- Tuple structs with a single field accept the plain inner value (unwrap_newtypes).
- Strings accept chars and identifiers, floats accept integers.
Decoding into an empty interface produces nil for () and None, bool, int64 (or uint64, or *big.Int when needed), float64, string, rune for chars, []byte, []any for lists and tuples, map[any]any for maps, map[string]any for structs and string for identifiers. Decode into a Value to keep the full structure including names.
Example ¶
package main
import (
"fmt"
"log"
"github.com/peltonapp/rustyon-go"
)
func main() {
type Config struct {
WindowTitle string
WindowSize [2]int
MaxFPS *int
Tags []string
}
src := []byte(`
// Rust style config
Config(
window_title: "Rusty Game",
window_size: (800, 600),
max_fps: Some(60),
tags: ["fast", "fun"],
)`)
var c Config
if err := rustyon.Unmarshal(src, &c); err != nil {
log.Fatal(err)
}
fmt.Println(c.WindowTitle, c.WindowSize, *c.MaxFPS, c.Tags)
}
Output: Rusty Game [800 600] 60 [fast fun]
Types ¶
type Decoder ¶
type Decoder struct {
// contains filtered or unexported fields
}
A Decoder reads and decodes RON values from an input stream. The stream can hold several values separated by whitespace or comments; each call to Decoder.Decode reads the next one. Extension attributes are accepted before the first value.
func NewDecoder ¶
NewDecoder returns a new decoder that reads from r. The decoder reads all of r on the first call to Decode.
func (*Decoder) Decode ¶
Decode reads the next RON value from the input and stores it in v. It returns io.EOF when there are no more values.
func (*Decoder) DisallowUnknownFields ¶
func (dec *Decoder) DisallowUnknownFields()
DisallowUnknownFields makes Decode return an UnknownFieldError when the input contains a struct field that has no matching Go field.
func (*Decoder) SetRegistry ¶
SetRegistry sets the enum registry. A nil registry selects DefaultRegistry.
type Document ¶
type Document struct {
Extensions Extensions
Value Value
}
Document is a parsed RON document: an optional set of extensions and a single value.
func ParseDocument ¶
ParseDocument parses a RON document including its extension attributes.
type Encoder ¶
type Encoder struct {
// contains filtered or unexported fields
}
An Encoder writes RON values to an output stream.
Example ¶
package main
import (
"log"
"os"
"github.com/peltonapp/rustyon-go"
)
func main() {
enc := rustyon.NewEncoder(os.Stdout)
enc.SetStructNames(true)
enc.SetImplicitSome(true)
type Window struct {
Title string
Width *int
}
w := 640
if err := enc.Encode(Window{"main", &w}); err != nil {
log.Fatal(err)
}
}
Output: #![enable(implicit_some)]Window(title:"main",width:640)
func NewEncoder ¶
NewEncoder returns a new encoder that writes to w.
func (*Encoder) SetImplicitSome ¶
SetImplicitSome makes the encoder write non-nil pointers as their plain value instead of Some(value) and enables the implicit_some extension in the output.
func (*Encoder) SetIndent ¶
SetIndent makes the encoder write pretty printed output with one element per line, as MarshalIndent does. An empty indent restores compact output.
func (*Encoder) SetRegistry ¶
SetRegistry sets the enum registry. A nil registry selects DefaultRegistry.
func (*Encoder) SetStructNames ¶
SetStructNames makes the encoder write struct names, for example Config(port: 80) instead of (port: 80).
func (*Encoder) SetUnwrapNewtypes ¶
SetUnwrapNewtypes makes the encoder write tuple structs with a single field as their inner value and enables the unwrap_newtypes extension in the output.
type Extensions ¶
type Extensions uint8
Extensions is a set of RON extensions enabled through an #![enable(...)] attribute at the start of a document.
const ( // ImplicitSome allows Some(x) to be written as x. ImplicitSome Extensions = 1 << iota // UnwrapNewtypes allows newtype structs such as Meters(5.0) to be // written as their inner value 5.0. UnwrapNewtypes // UnwrapVariantNewtypes allows newtype variants that wrap a struct to // omit the inner parentheses: Shape(x: 1) instead of Shape((x: 1)). UnwrapVariantNewtypes // ExplicitStructNames requires struct names to be written. ExplicitStructNames )
RON extensions as defined by ron-rs.
func (Extensions) Names ¶
func (e Extensions) Names() []string
Names returns the RON names of the enabled extensions.
type Ident ¶
type Ident string
Ident is a bare identifier such as Red. It represents a unit struct or a unit enum variant.
type Int ¶
type Int struct {
// contains filtered or unexported fields
}
Int is an integer of arbitrary size. RON allows integers up to 128 bits, which do not fit into Go's builtin integer types. Values that fit into an int64 are stored inline; larger ones use a big.Int. The zero value represents 0.
type InvalidUnmarshalError ¶
InvalidUnmarshalError describes an invalid argument passed to Unmarshal. The argument must be a non-nil pointer.
func (*InvalidUnmarshalError) Error ¶
func (e *InvalidUnmarshalError) Error() string
type Kind ¶
type Kind uint8
Kind identifies the concrete type of a Value.
const ( KindUnit Kind = iota + 1 // () KindBool // true, false KindInt // 42, -0x2A, 1_000u32 KindFloat // 1.5, -inf, NaN KindString // "text", r#"raw"# KindChar // 'c' KindBytes // b"bytes" KindList // [a, b] KindMap // {k: v} KindTuple // (a, b), Name(a, b) KindStruct // (f: v), Name(f: v) KindOption // None, Some(v) KindIdent // Name (unit struct or unit enum variant) )
The kinds of RON values.
type Map ¶
type Map []MapEntry
Map is a map value such as {"a": 1}. Entries keep the order of the source document. Keys can be any value.
type Marshaler ¶
Marshaler is implemented by types that can marshal themselves into RON. MarshalRON must return a single valid RON value.
type MarshalerError ¶
type MarshalerError struct {
Type reflect.Type
Err error
Method string // "MarshalRON" or "MarshalText"
}
MarshalerError wraps an error returned by a Marshaler or encoding.TextMarshaler.
func (*MarshalerError) Error ¶
func (e *MarshalerError) Error() string
func (*MarshalerError) Unwrap ¶
func (e *MarshalerError) Unwrap() error
type Option ¶
type Option struct {
Value Value
}
Option is an optional value. A nil Value represents None, anything else represents Some(Value).
type Position ¶
Position is a location in a RON document. Line and Column are 1-based; Column counts Unicode code points. Offset is the 0-based byte offset.
type Registry ¶
type Registry struct {
// contains filtered or unexported fields
}
Registry maps Go types to Rust style enums. Go has no sum types, so an enum is modelled as an interface type whose implementations are the variants:
type Shape interface{ isShape() }
type Circle struct{ Radius float64 } // struct variant: Circle(radius: 1.0)
type Rect struct { // tuple variant: Rect(2.0, 3.0)
_ struct{} `ron:",tuple"`
W, H float64
}
type Empty struct{} // unit variant: Empty
type Label string // newtype variant: Label("x")
func (Circle) isShape() {}
func (Rect) isShape() {}
func (Empty) isShape() {}
func (Label) isShape() {}
rustyon.RegisterEnum[Shape](
rustyon.Variant[Circle]("Circle"),
rustyon.Variant[Rect]("Rect"),
rustyon.Variant[Empty]("Empty"),
rustyon.Variant[Label]("Label"),
)
Enums whose variants carry no data can also be modelled as integer or string constants with RegisterUnitEnum.
Most programs use DefaultRegistry through the package level Register functions. A separate Registry can be passed to an Encoder or Decoder. A Registry is safe for concurrent use. Lookups are lock free; registering is meant to happen at program start.
type Struct ¶
Struct is a struct such as (x: 1, y: 2), a named struct such as Point(x: 1, y: 2) or a struct enum variant. Name is empty for anonymous structs.
type SyntaxError ¶
SyntaxError describes malformed RON input.
func (*SyntaxError) Error ¶
func (e *SyntaxError) Error() string
type Tuple ¶
Tuple is a tuple such as (1, 2), a tuple struct such as Point(1, 2) or a tuple enum variant. Name is empty for anonymous tuples.
type UnknownFieldError ¶
UnknownFieldError is returned by a Decoder with Decoder.DisallowUnknownFields set when a struct field in the input has no matching Go field.
func (*UnknownFieldError) Error ¶
func (e *UnknownFieldError) Error() string
type UnmarshalTypeError ¶
type UnmarshalTypeError struct {
Value string // description of the RON value, e.g. "string" or "tuple Circle"
Type reflect.Type // Go type that could not hold the value
Path string // path to the value within the document, e.g. "servers[0].port"
Msg string // optional detail
}
UnmarshalTypeError describes a RON value that cannot be stored in a Go value of a specific type.
func (*UnmarshalTypeError) Error ¶
func (e *UnmarshalTypeError) Error() string
type Unmarshaler ¶
Unmarshaler is implemented by types that can unmarshal a RON value themselves. UnmarshalRON receives the value re-encoded as compact RON.
type UnsupportedTypeError ¶
UnsupportedTypeError is returned by Marshal for Go values that have no RON representation, such as channels and functions.
func (*UnsupportedTypeError) Error ¶
func (e *UnsupportedTypeError) Error() string
type UnsupportedValueError ¶
UnsupportedValueError is returned by Marshal for Go values that cannot be encoded, such as a unit enum value without a registered name.
func (*UnsupportedValueError) Error ¶
func (e *UnsupportedValueError) Error() string
type Value ¶
type Value interface {
Kind() Kind
// contains filtered or unexported methods
}
Value is a node of a parsed RON document. It is implemented by Unit, Bool, Int, Float, String, Char, Bytes, List, Map, Tuple, Struct, Option and Ident.
A Value can be passed to Marshal and can be the target of Unmarshal, which makes it possible to work with RON documents whose shape is not known in advance.
func Parse ¶
Parse parses a RON document into a Value. Extension attributes are accepted but not returned; use ParseDocument to inspect them.
Example ¶
package main
import (
"fmt"
"log"
"github.com/peltonapp/rustyon-go"
)
func main() {
v, err := rustyon.Parse([]byte(`Point(x: 1, y: -2)`))
if err != nil {
log.Fatal(err)
}
s := v.(rustyon.Struct)
y, _ := s.Get("y")
fmt.Println(s.Name, len(s.Fields), y.(rustyon.Int).String())
}
Output: Point 2 -2
type VariantSpec ¶
type VariantSpec struct {
// contains filtered or unexported fields
}
VariantSpec describes one variant of an enum. Create it with Variant.
func Variant ¶
func Variant[T any](name string) VariantSpec
Variant declares that the Go type T is the enum variant called name. T can be a pointer type when the interface is implemented by a pointer receiver.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
rustyon
command
Command rustyon formats, validates and converts RON (Rusty Object Notation) files.
|
Command rustyon formats, validates and converts RON (Rusty Object Notation) files. |
|
internal
|
|
|
fields
Package fields computes and caches the RON view of Go struct types: field names, tag options and embedded struct promotion.
|
Package fields computes and caches the RON view of Go struct types: field names, tag options and embedded struct promotion. |
|
syntax
Package syntax holds the RON lexer, literal decoding and the comment preserving formatter.
|
Package syntax holds the RON lexer, literal decoding and the comment preserving formatter. |
|
Package ronjson converts between RON and JSON.
|
Package ronjson converts between RON and JSON. |