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 DecodeAs[T any](dec *Decoder) (T, error)
- 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 MarshalWith(v any, opts EncodeOptions) ([]byte, error)
- func MarshalWithConfig(v any, cfg PrettyConfig) ([]byte, error)
- func RegisterEnum[I any](variants ...VariantSpec)
- func RegisterEnumIn[I any](r *Registry, variants ...VariantSpec)
- func RegisterEnumWith[I any](opts EnumOptions, variants ...VariantSpec)
- func RegisterEnumWithIn[I any](r *Registry, opts EnumOptions, 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 UnmarshalAs[T any](data []byte, opts ...DecodeOptions) (T, error)
- func UnmarshalWith(data []byte, v any, opts DecodeOptions) error
- func Valid(data []byte) bool
- type Bool
- type Bytes
- type Char
- type DecodeOptions
- type Decoder
- type Document
- type Editable
- func (e *Editable) Append(path string, v Value) error
- func (e *Editable) Bytes() []byte
- func (e *Editable) Delete(path string) error
- func (e *Editable) Extensions() Extensions
- func (e *Editable) Format(indent string) []byte
- func (e *Editable) Get(path string) (Value, bool)
- func (e *Editable) Insert(path string, i int, v Value) error
- func (e *Editable) Set(path string, v Value) error
- func (e *Editable) SetRON(path, ron string) error
- func (e *Editable) String() string
- type EncodeOptions
- type Encoder
- func (enc *Encoder) Encode(v any) error
- func (enc *Encoder) SetFieldNaming(n NamingStrategy)
- func (enc *Encoder) SetImplicitSome(on bool)
- func (enc *Encoder) SetIndent(prefix, indent string)
- func (enc *Encoder) SetPrettyConfig(cfg *PrettyConfig)
- func (enc *Encoder) SetRegistry(r *Registry)
- func (enc *Encoder) SetStructNames(on bool)
- func (enc *Encoder) SetUnwrapNewtypes(on bool)
- type EnumOptions
- 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 NamingStrategy
- type Option
- type Position
- type PrettyConfig
- type Raw
- 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 ErrPathNotFound = errors.New("rustyon: path not found")
ErrPathNotFound is wrapped by the errors that Editable methods return when a path does not select anything in the document.
var None = Option{}
None is the empty Option.
Functions ¶
func DecodeAs ¶ added in v1.1.0
DecodeAs reads the next value from dec into a new value of type T, like Decoder.Decode.
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 accepts exactly the documents Parse accepts, and the result has the same value as the input. 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 (see NamingStrategy for other styles) 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). The option rename_all=camelCase on that field renames the struct's fields, see NamingStrategy. Embedded structs, and fields of struct type with the option flatten, have their fields written inline in the parent, as serde's flatten does. A field of type map[string]T with the option flatten collects all fields that no other field matches when decoding, and is written as fields after the regular ones.
- 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.
Example (Flatten) ¶
package main
import (
"fmt"
"log"
"github.com/peltonapp/rustyon-go"
)
func main() {
type Common struct {
ID int
Name string
}
type Item struct {
Common `ron:",flatten"`
Extra map[string]any `ron:",flatten"` // collects unknown fields
}
var it Item
err := rustyon.Unmarshal([]byte(`(id: 7, name: "sword", damage: 12, tags: ["a"])`), &it)
if err != nil {
log.Fatal(err)
}
fmt.Println(it.ID, it.Name, it.Extra["damage"])
out, _ := rustyon.Marshal(it)
fmt.Println(string(out))
}
Output: 7 sword 12 (id:7,name:"sword",damage:12,tags:["a"])
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 MarshalWith ¶ added in v1.1.0
func MarshalWith(v any, opts EncodeOptions) ([]byte, error)
MarshalWith is like Marshal with the given options.
func MarshalWithConfig ¶ added in v1.1.0
func MarshalWithConfig(v any, cfg PrettyConfig) ([]byte, error)
MarshalWithConfig is like Marshal but writes pretty printed output laid out as cfg says.
Example ¶
package main
import (
"fmt"
"log"
"github.com/peltonapp/rustyon-go"
)
func main() {
type Level struct {
Name string
Tiles []int
Spawn [2]int
Memo string
Nested struct{ Deep []int }
}
l := Level{Name: "café", Tiles: []int{1, 2, 3}, Spawn: [2]int{4, 5}, Memo: "x"}
l.Nested.Deep = []int{9}
out, err := rustyon.MarshalWithConfig(l, rustyon.PrettyConfig{
CompactArrays: true,
EscapeNonASCII: true,
DepthLimit: 1,
Indent: " ",
})
if err != nil {
log.Fatal(err)
}
fmt.Println(string(out))
}
Output: ( name: "caf\u{e9}", tiles: [1, 2, 3], spawn: [4, 5], memo: "x", nested: (deep: [9]), )
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 RegisterEnumWith ¶ added in v1.1.0
func RegisterEnumWith[I any](opts EnumOptions, variants ...VariantSpec)
RegisterEnumWith is like RegisterEnum with a choice of representation, such as the internally tagged enums serde produces with #[serde(tag = "type")]:
rustyon.RegisterEnumWith[Shape](rustyon.EnumOptions{Tag: "type"},
rustyon.Variant[Circle]("Circle"),
rustyon.Variant[Empty]("Empty"),
)
It panics for invalid options and, in addition to the cases of RegisterEnum, when the interface is already registered with another representation.
func RegisterEnumWithIn ¶ added in v1.1.0
func RegisterEnumWithIn[I any](r *Registry, opts EnumOptions, variants ...VariantSpec)
RegisterEnumWithIn is like RegisterEnumWith but registers into r.
Example ¶
package main
import (
"fmt"
"log"
"github.com/peltonapp/rustyon-go"
)
type exAnimal interface{ isAnimal() }
type exDog struct{ Name string }
type exFish struct{ Fins int }
func (exDog) isAnimal() {}
func (exFish) isAnimal() {}
func main() {
reg := rustyon.NewRegistry()
// Like #[serde(tag = "type")] in Rust.
rustyon.RegisterEnumWithIn[exAnimal](reg, rustyon.EnumOptions{Tag: "type"},
rustyon.Variant[exDog]("Dog"),
rustyon.Variant[exFish]("Fish"),
)
out, err := rustyon.MarshalWith([]exAnimal{exDog{"Rex"}, exFish{2}}, rustyon.EncodeOptions{Registry: reg})
if err != nil {
log.Fatal(err)
}
fmt.Println(string(out))
var animals []exAnimal
err = rustyon.UnmarshalWith(out, &animals, rustyon.DecodeOptions{Registry: reg})
fmt.Println(animals, err)
}
Output: [(type:"Dog",name:"Rex"),(type:"Fish",fins:2)] [{Rex} {2}] <nil>
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.
Unmarshal decodes straight from the text into v without building a Value tree, except for the parts of the input that go into an empty interface, a Value, an enum registered with the registry or a type with an Unmarshaler or encoding.TextUnmarshaler method. If decoding fails, v may be partially modified. Each such method is called at most once per value, including when a later part of the input is invalid.
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]
func UnmarshalAs ¶ added in v1.1.0
func UnmarshalAs[T any](data []byte, opts ...DecodeOptions) (T, error)
UnmarshalAs decodes data into a new value of type T. It is Unmarshal without the pointer, for example
cfg, err := rustyon.UnmarshalAs[Config](data)
The optional opts select the field naming, unknown field handling and registry like UnmarshalWith. Only the first is used.
Example ¶
package main
import (
"fmt"
"github.com/peltonapp/rustyon-go"
)
func main() {
type Config struct{ MaxFPS int }
c, err := rustyon.UnmarshalAs[Config]([]byte(`(max_fps: 60)`))
fmt.Println(c.MaxFPS, err)
}
Output: 60 <nil>
func UnmarshalWith ¶ added in v1.1.0
func UnmarshalWith(data []byte, v any, opts DecodeOptions) error
UnmarshalWith is like Unmarshal with the given options.
Types ¶
type DecodeOptions ¶ added in v1.1.0
type DecodeOptions struct {
// FieldNaming is the default field naming. The zero value is [SnakeCase].
FieldNaming NamingStrategy
// DisallowUnknownFields makes decoding fail on fields without a Go field,
// as [Decoder.DisallowUnknownFields].
DisallowUnknownFields bool
// Registry is the enum registry, or nil for [DefaultRegistry].
Registry *Registry
}
DecodeOptions configures UnmarshalWith. The zero value gives the same behavior as Unmarshal.
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) SetFieldNaming ¶ added in v1.1.0
func (dec *Decoder) SetFieldNaming(n NamingStrategy)
SetFieldNaming sets how Go field names without a tag name map to RON field names. The default is SnakeCase. A rename_all option on a struct overrides it for that struct. Names still match case-insensitively when no exact match exists.
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.
The accepted grammar is the one ron-rs accepts when deserializing into its dynamic value type, including its quirks such as ranges (1..5) and the recursion limit.
type Editable ¶ added in v1.1.0
type Editable struct {
// contains filtered or unexported fields
}
Editable is a RON document that can be edited in place while keeping its comments and layout. It is created with ParseEditable.
Paths ¶
Values are addressed with the same path syntax as the get command of the rustyon tool:
items[0].name a field of the first element of a list .config.port a leading dot is optional tags[-1] negative indexes count from the end users["alice"] a map entry with a string key
A path is a sequence of steps. A step .name selects a struct field, or a map entry whose key is the string or identifier name. A step [N] selects a list or tuple element, or a map entry with the integer key N. A step ["key"] selects a map entry with that string key, or a struct field. The empty path and "." select the whole document. Some(x) is looked through, so a step applies to x; None has nothing to step into. Map keys that are not strings, identifiers or integers cannot be addressed.
Edits ¶
An edit is a text change at the place the path selects, so everything else in the document is preserved byte for byte: comments, spelling of literals, blank lines and indentation. After every edit the result is parsed again; if an edit would produce a document that does not parse, the document is left unchanged and an error is returned. An Editable is not safe for concurrent use.
func ParseEditable ¶ added in v1.1.0
ParseEditable parses src, which must be a valid RON document, for editing. It accepts exactly the documents Parse accepts.
Example ¶
package main
import (
"fmt"
"log"
"github.com/peltonapp/rustyon-go"
)
func main() {
src := []byte(`// server settings
(
host: "localhost", // where to listen
port: 8080,
users: ["ann", "bob"],
)`)
doc, err := rustyon.ParseEditable(src)
if err != nil {
log.Fatal(err)
}
port, _ := doc.Get("port")
fmt.Println("port was", port)
if err := doc.Set("port", rustyon.NewInt(9090)); err != nil {
log.Fatal(err)
}
if err := doc.Append("users", rustyon.String("cy")); err != nil {
log.Fatal(err)
}
if err := doc.Delete("users[0]"); err != nil {
log.Fatal(err)
}
// A missing field is added at the end.
if err := doc.Set("debug", rustyon.Bool(true)); err != nil {
log.Fatal(err)
}
fmt.Print(doc)
}
Output: port was 8080 // server settings ( host: "localhost", // where to listen port: 9090, users: ["bob", "cy"], debug: true, )
func (*Editable) Append ¶ added in v1.1.0
Append adds v at the end of the list that path selects. See Editable.Insert.
func (*Editable) Delete ¶ added in v1.1.0
Delete removes the value that path selects together with its field name or map key. The comments directly above the element (without a blank line in between) and the comments after it on its line are removed with it; all other comments stay. Deleting the last remaining element leaves an empty collection. Delete returns an error that wraps ErrPathNotFound if the path selects nothing, and an error if the path selects the whole document.
Example ¶
package main
import (
"fmt"
"log"
"github.com/peltonapp/rustyon-go"
)
func main() {
doc, err := rustyon.ParseEditable([]byte("(\n a: 1,\n // b is unused\n b: 2,\n c: Some((x: 3)),\n)"))
if err != nil {
log.Fatal(err)
}
// The comment above b goes with it. Paths look through Some.
if err := doc.Delete("b"); err != nil {
log.Fatal(err)
}
if err := doc.Delete("c.x"); err != nil {
log.Fatal(err)
}
fmt.Println(doc)
}
Output: ( a: 1, c: Some(()), )
func (*Editable) Extensions ¶ added in v1.1.0
func (e *Editable) Extensions() Extensions
Extensions returns the extensions enabled by the document's attributes.
func (*Editable) Format ¶ added in v1.1.0
Format returns the document reformatted like FormatIndent does, with all comments kept.
func (*Editable) Get ¶ added in v1.1.0
Get returns the value that path selects. It reports false if the path is malformed or selects nothing. The value is parsed from the current text, so it reflects all edits made so far.
func (*Editable) Insert ¶ added in v1.1.0
Insert inserts v as element i of the list that path selects, so that it ends up at index i. i must be between 0 and the length of the list. The new element follows the layout of its neighbors: on its own line if the elements are written one per line, otherwise inline. Comments stay with the elements they belong to.
Example ¶
package main
import (
"fmt"
"log"
"github.com/peltonapp/rustyon-go"
)
func main() {
doc, err := rustyon.ParseEditable([]byte("[\n 1,\n // three\n 3,\n]"))
if err != nil {
log.Fatal(err)
}
if err := doc.Insert("", 1, rustyon.NewInt(2)); err != nil {
log.Fatal(err)
}
fmt.Println(doc)
}
Output: [ 1, 2, // three 3, ]
func (*Editable) Set ¶ added in v1.1.0
Set replaces the value that path selects with v. The comments around the old value stay where they are; comments inside the old value go with it. The new value is written on one line.
If the path ends in a name or key that does not exist, it is added: as a new field at the end of a struct (or of an empty () or Name()), or as a new entry at the end of a map. A new map key is written as an identifier if the existing keys are identifiers and as a string otherwise; a step [N] adds the integer key N. A new element cannot be added with Set to a list or tuple, use Editable.Insert or Editable.Append for lists.
Every parent of the last step must exist, otherwise Set returns an error that wraps ErrPathNotFound. Set with an empty path replaces the whole document value. The path addresses the node itself: setting a field whose value is Some(1) replaces all of Some(1).
func (*Editable) SetRON ¶ added in v1.1.0
SetRON is like Editable.Set but takes the new value as RON text. The text must be exactly one value, with no surrounding comments, and is inserted as written, including any line breaks. It must be valid where it is inserted, for example Some 1 is only valid in a document that enables implicit_some.
Example ¶
package main
import (
"fmt"
"log"
"github.com/peltonapp/rustyon-go"
)
func main() {
doc, err := rustyon.ParseEditable([]byte(`(range: 1..3, name: "x") // keep me`))
if err != nil {
log.Fatal(err)
}
// Literals can be written exactly as they should appear.
if err := doc.SetRON("range", "0x10..=0x20"); err != nil {
log.Fatal(err)
}
fmt.Println(doc)
}
Output: (range: 0x10..=0x20, name: "x") // keep me
type EncodeOptions ¶ added in v1.1.0
type EncodeOptions struct {
// FieldNaming is the default field naming. The zero value is [SnakeCase].
FieldNaming NamingStrategy
// StructNames writes struct names, as [Encoder.SetStructNames].
StructNames bool
// ImplicitSome writes non-nil pointers without Some, as
// [Encoder.SetImplicitSome].
ImplicitSome bool
// UnwrapNewtypes writes single field tuple structs as their inner value,
// as [Encoder.SetUnwrapNewtypes].
UnwrapNewtypes bool
// Registry is the enum registry, or nil for [DefaultRegistry].
Registry *Registry
// Pretty selects pretty printed output with the given layout. Nil gives
// compact output.
Pretty *PrettyConfig
}
EncodeOptions configures MarshalWith. The zero value gives the same output as Marshal.
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) SetFieldNaming ¶ added in v1.1.0
func (enc *Encoder) SetFieldNaming(n NamingStrategy)
SetFieldNaming sets how Go field names without a tag name become RON field names. The default is SnakeCase. A rename_all option on a struct overrides it for that struct.
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) SetPrettyConfig ¶ added in v1.1.0
func (enc *Encoder) SetPrettyConfig(cfg *PrettyConfig)
SetPrettyConfig makes the encoder write pretty printed output laid out as cfg says. A nil cfg restores compact output. It replaces the setting of Encoder.SetIndent.
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 EnumOptions ¶ added in v1.1.0
EnumOptions selects how the variants of an enum are written, using serde's names for the representations. The zero value is the default external representation of RON, as used by RegisterEnum: Circle(radius: 1.0).
- Tag only (internally tagged): the variant is a struct that has an extra field with the variant name as a string. Circle becomes (type: "Circle", radius: 1.0), a unit variant (type: "Empty"). Variants must be structs, or newtypes around a struct or a map with string keys, as in serde. Tuple variants cannot be encoded.
- Tag and Content (adjacently tagged): (t: Circle, c: (radius: 1.0)), with the tag as an identifier like serde writes it. Unit variants omit the content: (t: Empty). Decoding accepts the tag as a string too.
- Untagged: the variant is written as its content alone, (radius: 1.0). Decoding tries the variants in registration order and takes the first that fits: a struct variant fits when the input has all of its fields, except pointer, interface, omitempty and omitzero fields, which may be missing. Unit variants fit () only.
The tag and content names must be valid identifiers and different from each other, and a tagged struct variant must not have a field of the same name as the tag. A type that is a variant of several enums with different representations or names is only treated as a variant when it is stored in one of their interfaces, not when it is encoded or decoded on its own.
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 NamingStrategy ¶ added in v1.1.0
type NamingStrategy uint8
NamingStrategy selects how Go field names without an explicit tag name are written as RON field names. The zero value is SnakeCase, which is the default of every function in this package.
Set it for a whole encoder or decoder with Encoder.SetFieldNaming, Decoder.SetFieldNaming, EncodeOptions or DecodeOptions, or for a single struct with a rename_all option on its blank field, as serde does:
type Config struct {
_ struct{} `ron:",rename_all=camelCase"`
WindowSize int // window_size becomes windowSize
}
The option accepts the serde names: "snake_case", "camelCase", "PascalCase", "SCREAMING_SNAKE_CASE", "kebab-case", "SCREAMING-KEBAB-CASE", "lowercase", "UPPERCASE" and "identity" (the Go name as it is). Unknown values are ignored. An explicit `ron:"name"` tag on a field always wins, and an embedded struct that has its own rename_all keeps it for its fields.
Names that are not plain RON identifiers, such as the kebab-case ones, are written as raw identifiers (r#window-size).
Example ¶
package main
import (
"fmt"
"log"
"github.com/peltonapp/rustyon-go"
)
func main() {
type Window struct {
WindowTitle string
MaxFPS int
}
out, err := rustyon.MarshalWith(Window{"main", 60}, rustyon.EncodeOptions{FieldNaming: rustyon.CamelCase})
if err != nil {
log.Fatal(err)
}
fmt.Println(string(out))
// A rename_all option on the struct overrides the default, as in serde.
type Fixed struct {
_ struct{} `ron:",rename_all=SCREAMING_SNAKE_CASE"`
MaxFPS int
Tagged int `ron:"keep"`
}
out, _ = rustyon.MarshalWith(Fixed{MaxFPS: 60, Tagged: 1}, rustyon.EncodeOptions{FieldNaming: rustyon.CamelCase})
fmt.Println(string(out))
var w Window
err = rustyon.UnmarshalWith([]byte(`(windowTitle: "x", maxFps: 30)`), &w, rustyon.DecodeOptions{FieldNaming: rustyon.CamelCase})
fmt.Println(w, err)
}
Output: (windowTitle:"main",maxFps:60) (MAX_FPS:60,keep:1) {x 30} <nil>
const ( SnakeCase NamingStrategy = NamingStrategy(fields.Snake) // max_hp CamelCase NamingStrategy = NamingStrategy(fields.Camel) // maxHp PascalCase NamingStrategy = NamingStrategy(fields.Pascal) // MaxHp ScreamingSnakeCase NamingStrategy = NamingStrategy(fields.ScreamingSnake) // MAX_HP KebabCase NamingStrategy = NamingStrategy(fields.Kebab) // r#max-hp ScreamingKebabCase NamingStrategy = NamingStrategy(fields.ScreamingKebab) // r#MAX-HP LowerCase NamingStrategy = NamingStrategy(fields.Lower) // maxhp UpperCase NamingStrategy = NamingStrategy(fields.Upper) // MAXHP Identity NamingStrategy = NamingStrategy(fields.Identity) // MaxHP )
The field naming strategies. The examples show the name for the Go field MaxHP, or for the words max and hp.
func (NamingStrategy) Name ¶ added in v1.1.0
func (n NamingStrategy) Name(goName string) string
Name converts a Go field name according to the strategy.
func (NamingStrategy) String ¶ added in v1.1.0
func (n NamingStrategy) String() string
String returns the serde name of the strategy, for example "camelCase".
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 PrettyConfig ¶ added in v1.1.0
type PrettyConfig struct {
// Prefix starts every line after the first. It is the prefix of
// [MarshalIndent].
Prefix string
// Indent is written once per nesting level. The default is four spaces.
Indent string
// NewLine separates lines. The default is "\n". With EnumerateArrays it
// must contain a line break.
NewLine string
// Separator is written after the colon of a field or map entry. The
// default is a single space.
Separator string
// DepthLimit limits the pretty printing depth: collections nested more
// than DepthLimit levels deep are written inline. With DepthLimit 1 only
// the outermost collection is spread over lines. Zero means no limit.
DepthLimit int
// CompactArrays writes lists on one line, as [1, 2, 3].
CompactArrays bool
// CompactStructs writes structs on one line, as (a: 1, b: 2).
CompactStructs bool
// CompactMaps writes maps on one line, as {"a": 1, "b": 2}.
CompactMaps bool
// SeparateTupleMembers puts every member of a tuple on its own line.
// Without it, tuples of simple values stay on one line.
SeparateTupleMembers bool
// EnumerateArrays writes a comment with the index, such as // [0], before
// every element of a list that is spread over several lines.
EnumerateArrays bool
// EscapeNonASCII writes every non-ASCII character in strings and chars
// as a \u{...} escape.
EscapeNonASCII bool
}
PrettyConfig controls the layout of pretty printed output. It mirrors the options of ron-rs's PrettyConfig that make sense for Go. The zero value gives the layout of MarshalIndent with four spaces: one element per line, trailing commas, ": " after field names.
Whatever the configuration, the output parses back to the same value. Because of that, Prefix, Indent, NewLine and Separator must consist of spaces, tabs and line breaks only.
A collection that is written on one line ("inline") is written on one line together with everything in it, with ", " between elements.
type Raw ¶ added in v1.1.0
type Raw []byte
Raw holds one RON value as text, like encoding/json's RawMessage. Use it to delay decoding of part of a document, or to pass a value through unchanged:
type Envelope struct {
Kind string
Payload rustyon.Raw // decoded later, once Kind is known
}
When decoding, a Raw captures the text of the value exactly as written, including comments inside it, as long as the document does not enable any extensions. With extensions the value is stored as compact RON printed from its parse tree, so that the text means the same without them.
When encoding, the text must be a single valid RON value or encoding fails. The value is parsed and written in the layout of the surrounding output, so comments and spacing inside it are not kept. A nil Raw encodes as None.
Example ¶
package main
import (
"fmt"
"log"
"github.com/peltonapp/rustyon-go"
)
func main() {
type Envelope struct {
Kind string
Payload rustyon.Raw // decoded once Kind is known
}
var e Envelope
err := rustyon.Unmarshal([]byte(`(kind: "point", payload: (x: 3, y: 4 /* kept */))`), &e)
if err != nil {
log.Fatal(err)
}
fmt.Println(string(e.Payload))
var p struct{ X, Y int }
if err := e.Payload.Decode(&p); err != nil {
log.Fatal(err)
}
fmt.Println(p.X, p.Y)
out, _ := rustyon.Marshal(e)
fmt.Println(string(out))
}
Output: (x: 3, y: 4 /* kept */) 3 4 (kind:"point",payload:(x:3,y:4))
func (Raw) MarshalRON ¶ added in v1.1.0
MarshalRON returns r, or None when r is nil.
func (*Raw) UnmarshalRON ¶ added in v1.1.0
UnmarshalRON stores a copy of b in r.
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
module
|
|
|
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. |
|
path
Package path parses the path syntax that selects a value inside a RON document.
|
Package path parses the path syntax that selects a value inside a RON document. |
|
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. |
|
playground
|
|
|
wasm
command
Command wasm exposes rustyon to the browser playground through syscall/js.
|
Command wasm exposes rustyon to the browser playground through syscall/js. |
|
Package ronjson converts between RON and JSON.
|
Package ronjson converts between RON and JSON. |