rustyon

package module
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 14, 2026 License: BSD-3-Clause Imports: 22 Imported by: 0

README

rustyon

Go Reference CI Coverage OpenSSF Scorecard Release Go version Docs Playground Zero dependencies

rustyon is a Go implementation of Rusty Object Notation (RON), the human-readable serialization format used in the Rust ecosystem. It is an independent implementation and is not affiliated with the ron-rs project.

// Read and write files like this from Go.
#![enable(implicit_some)]
GameConfig(
    window_size: (800, 600),
    window_title: "Rusty Game",
    difficulty: Hard,
    spawn: Circle(radius: 2.5),
    key_bindings: {"up": Up, "down": Down},
)

Features

  • Marshal / Unmarshal with an encoding/json style API, struct tags, omitempty and omitzero, Encoder and Decoder for streams.
  • Rust enums on Go interfaces. Register variants once and Circle(radius: 1.0) decodes into your Circle type.
  • Dynamic Value tree for documents with an unknown shape, including 128-bit integers.
  • Formatter that keeps comments, like gofmt for .ron files.
  • Full ron-rs grammar: raw strings, byte strings, nested block comments, number suffixes, #![enable(...)] extensions.
  • rustyon CLI to format, validate, query and convert RON to and from JSON, YAML and TOML.
  • Zero dependencies in the library, fuzz tested, Go 1.24+. The CLI is a separate module, so its YAML and TOML libraries never reach your build.

Install

go get github.com/peltonapp/rustyon-go

The package name is rustyon:

import "github.com/peltonapp/rustyon-go"

Quick start

type Config struct {
    WindowTitle string    // matches window_title
    WindowSize  [2]int    // matches (800, 600)
    MaxFPS      *int      // Option<u32>: None or Some(60)
    Tags        []string  `ron:"labels,omitempty"`
}

var c Config
err := rustyon.Unmarshal(data, &c)

out, err := rustyon.MarshalIndent(c, "", "    ")

Go field names become snake_case by default, so Go structs line up with Rust structs without tags. Pointers map to Option: nil is None, anything else is Some(v). The wiki has the full type mapping.

Field naming

snake_case stays the default. Pick another strategy for a whole encoder or decoder, or per struct with a serde style rename_all option on the blank field. Explicit ron:"name" tags always win.

out, err := rustyon.MarshalWith(cfg, rustyon.EncodeOptions{FieldNaming: rustyon.CamelCase})
err = rustyon.UnmarshalWith(data, &cfg, rustyon.DecodeOptions{FieldNaming: rustyon.CamelCase})

type Window struct {
    _     struct{} `ron:",rename_all=PascalCase"` // also: camelCase, SCREAMING_SNAKE_CASE, kebab-case, identity, ...
    Title string                                  // Title
}

Flatten

Like serde's flatten: embedded structs and struct fields tagged ron:",flatten" are written inline, and a map[string]T field tagged ron:",flatten" collects every field no other field matches.

type Item struct {
    Common `ron:",flatten"`            // id and name appear directly in Item
    Extra  map[string]any `ron:",flatten"` // all other fields
}

Pretty printing options

MarshalIndent covers the common case. MarshalWithConfig (or Encoder.SetPrettyConfig) mirrors ron-rs's PrettyConfig: compact arrays, structs and maps, separate tuple members, a depth limit, \u{..} escapes for non-ASCII text, custom line break, indent, prefix and separator after the colon, and // [0] index comments for lists. The output always parses back to the same value.

out, err := rustyon.MarshalWithConfig(v, rustyon.PrettyConfig{CompactArrays: true, DepthLimit: 2})

Raw values and generics

rustyon.Raw (like json.RawMessage) keeps one RON value as text, so a part of a document can be decoded later or passed through. UnmarshalAs[T] and DecodeAs[T] return the value instead of filling a pointer.

type Envelope struct {
    Kind    string
    Payload rustyon.Raw // captured as written, comments included
}
cfg, err := rustyon.UnmarshalAs[Config](data)

Enums

Go has no sum types, so a Rust enum becomes an interface and each variant a type that implements it:

type Shape interface{ isShape() }

type Circle struct{ Radius float64 }        // Circle(radius: 1.0)
type Rect struct {                          // Rect(2.0, 3.0)
    _    struct{} `ron:",tuple"`
    W, H float64
}
type Empty struct{}                         // Empty

func (Circle) isShape() {}
func (Rect) isShape()   {}
func (Empty) isShape()  {}

func init() {
    rustyon.RegisterEnum[Shape](
        rustyon.Variant[Circle]("Circle"),
        rustyon.Variant[Rect]("Rect"),
        rustyon.Variant[Empty]("Empty"),
    )
}

var shapes []Shape
err := rustyon.Unmarshal([]byte(`[Circle(radius: 1.5), Rect(2.0, 3.0), Empty]`), &shapes)

Enums without data, like enum Difficulty { Easy, Hard }, map onto Go constants with rustyon.RegisterUnitEnum.

Enums that use serde's other representations register with RegisterEnumWith and match what ron-rs reads and writes (checked against the ron-rs oracle):

// #[serde(tag = "type")]            (type: "Circle", radius: 1.0)
rustyon.RegisterEnumWith[Shape](rustyon.EnumOptions{Tag: "type"}, variants...)
// #[serde(tag = "t", content = "c")] (t: Circle, c: (radius: 1.0))
rustyon.RegisterEnumWith[Shape](rustyon.EnumOptions{Tag: "t", Content: "c"}, variants...)
// #[serde(untagged)]                (radius: 1.0), first variant that fits wins
rustyon.RegisterEnumWith[Shape](rustyon.EnumOptions{Untagged: true}, variants...)

Dynamic values

v, err := rustyon.Parse([]byte(`Point(x: 1, y: -2)`))
s := v.(rustyon.Struct)
y, _ := s.Get("y") // rustyon.Int

Formatting

pretty, err := rustyon.Format(src) // comments stay where they were

CLI

go install github.com/peltonapp/rustyon-go/cmd/rustyon@latest

rustyon fmt -w config.ron       # format in place, keeps comments
rustyon validate *.ron          # check syntax
rustyon to-json save.ron        # RON to JSON
rustyon from-json data.json     # JSON to RON
rustyon to-yaml save.ron        # RON to YAML
rustyon from-yaml cfg.yaml      # YAML to RON
rustyon to-toml save.ron        # RON to TOML
rustyon from-toml cfg.toml      # TOML to RON
rustyon get 'items[0].name' save.ron   # print one value

Binaries for Linux, macOS, Windows and FreeBSD are attached to the releases tagged cmd/rustyon/v*. The CLI is its own Go module (github.com/peltonapp/rustyon-go/cmd/rustyon) with its own version tags, so the library stays free of dependencies.

Syntax errors point at the problem:

$ rustyon validate game.ron
game.ron:3:16: expected ',' or ')'
 3 |     size: (800 600),
   |                ^

Conversions. to-* and from-* read a file or standard input and write to standard output. from-json, from-yaml and from-toml take -structs to write mappings whose keys are identifiers as structs (key: value) instead of maps ({"key": value}), and -indent to change or disable pretty printing. Like JSON, YAML and TOML cannot hold everything RON can, so struct and variant names are dropped. YAML keeps the field order. TOML has no null and needs a table at the top level: None fields are left out, None inside an array is an error, and keys are written sorted. Dates and times in TOML become strings.

get. rustyon get <path> [file] prints the RON value at a path and exits with status 1 if it does not exist. A path is built from three steps:

Step Selects
.name struct field, or map entry with a string or identifier key (leading dot is optional)
[N] list or tuple element, -1 is the last; map entry with integer key N
["key"] map entry with a string key (Go escapes), or struct field

Examples: items[0].name, .config.port, players["alice"], tags[-1]. Some(x) is looked through, and . selects the whole document. Use -indent "" for compact output.

Performance

Everything is linear in the input size. Typed Unmarshal decodes straight from the text without building an intermediate tree and runs on par with encoding/json; parsing into a dynamic tree is about twice as fast as encoding/json decoding into any; typed Marshal is about 2.3x slower than encoding/json. Format keeps comments and is several times slower than json.Indent. A 13 KB file encodes in about 0.13 ms, decodes in about 0.09 ms and formats in about 0.18 ms on an Apple M2. Charts, Big O tables and methodology are on the Performance wiki page.

Documentation

Contributing

Contributions are welcome. Please read CONTRIBUTING.md; all commits need a DCO sign-off (git commit -s).

License

BSD-3-Clause. The RON format was created by the ron-rs authors.

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

Examples

Constants

This section is empty.

Variables

View Source
var DefaultRegistry = NewRegistry()

DefaultRegistry is the registry used by Marshal, Unmarshal and by encoders and decoders that have no registry set.

View Source
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.

View Source
var None = Option{}

None is the empty Option.

Functions

func DecodeAs added in v1.1.0

func DecodeAs[T any](dec *Decoder) (T, error)

DecodeAs reads the next value from dec into a new value of type T, like Decoder.Decode.

func Equal

func Equal(a, b Value) bool

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

func Format(src []byte) ([]byte, error)

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

func FormatIndent(src []byte, indent string) ([]byte, error)

FormatIndent is like Format but uses indent for each nesting level.

func FromValue

func FromValue(v Value, target any) error

FromValue stores a parsed Value in the Go value pointed to by target, following the rules of Unmarshal.

func Marshal

func Marshal(v any) ([]byte, error)

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

func MarshalIndent(v any, prefix, indent string) ([]byte, error)

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

func Unmarshal(data []byte, v any) error

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.

func Valid

func Valid(data []byte) bool

Valid reports whether data is a syntactically valid RON document.

Types

type Bool

type Bool bool

Bool is a boolean value.

func (Bool) Kind

func (Bool) Kind() Kind

Kind returns KindBool.

type Bytes

type Bytes []byte

Bytes is a byte string value such as b"\x00\xff".

func (Bytes) Kind

func (Bytes) Kind() Kind

Kind returns KindBytes.

type Char

type Char rune

Char is a character value such as 'a'.

func (Char) Kind

func (Char) Kind() Kind

Kind returns KindChar.

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

func NewDecoder(r io.Reader) *Decoder

NewDecoder returns a new decoder that reads from r. The decoder reads all of r on the first call to Decode.

func (*Decoder) Decode

func (dec *Decoder) Decode(v any) error

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) More

func (dec *Decoder) More() bool

More reports whether there is another value to decode.

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

func (dec *Decoder) SetRegistry(r *Registry)

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

func ParseDocument(data []byte) (*Document, error)

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

func ParseEditable(src []byte) (*Editable, error)

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

func (e *Editable) Append(path string, v Value) error

Append adds v at the end of the list that path selects. See Editable.Insert.

func (*Editable) Bytes added in v1.1.0

func (e *Editable) Bytes() []byte

Bytes returns the current text of the document.

func (*Editable) Delete added in v1.1.0

func (e *Editable) Delete(path string) error

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

func (e *Editable) Format(indent string) []byte

Format returns the document reformatted like FormatIndent does, with all comments kept.

func (*Editable) Get added in v1.1.0

func (e *Editable) Get(path string) (Value, bool)

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

func (e *Editable) Insert(path string, i int, v Value) error

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

func (e *Editable) Set(path string, v Value) error

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

func (e *Editable) SetRON(path, ron string) error

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

func (*Editable) String added in v1.1.0

func (e *Editable) String() string

String returns the current text of the document.

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

func NewEncoder(w io.Writer) *Encoder

NewEncoder returns a new encoder that writes to w.

func (*Encoder) Encode

func (enc *Encoder) Encode(v any) error

Encode writes the RON encoding of v followed by a newline.

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

func (enc *Encoder) SetImplicitSome(on bool)

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

func (enc *Encoder) SetIndent(prefix, indent string)

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

func (enc *Encoder) SetRegistry(r *Registry)

SetRegistry sets the enum registry. A nil registry selects DefaultRegistry.

func (*Encoder) SetStructNames

func (enc *Encoder) SetStructNames(on bool)

SetStructNames makes the encoder write struct names, for example Config(port: 80) instead of (port: 80).

func (*Encoder) SetUnwrapNewtypes

func (enc *Encoder) SetUnwrapNewtypes(on bool)

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

type EnumOptions struct {
	Tag      string
	Content  string
	Untagged bool
}

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 Field

type Field struct {
	Name  string
	Value Value
}

Field is a single named field of a Struct.

func (Field) String added in v1.1.0

func (v Field) String() string

String returns the compact RON text of the field, such as x:1.

type Float

type Float float64

Float is a floating point value.

func (Float) Kind

func (Float) Kind() Kind

Kind returns KindFloat.

type Ident

type Ident string

Ident is a bare identifier such as Red. It represents a unit struct or a unit enum variant.

func (Ident) Kind

func (Ident) Kind() Kind

Kind returns KindIdent.

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.

func NewBigInt

func NewBigInt(v *big.Int) Int

NewBigInt returns an Int holding a copy of v.

func NewInt

func NewInt(v int64) Int

NewInt returns an Int holding v.

func NewUint

func NewUint(v uint64) Int

NewUint returns an Int holding v.

func (Int) Big

func (i Int) Big() *big.Int

Big returns a copy of the integer as a big.Int.

func (Int) Cmp

func (i Int) Cmp(j Int) int

Cmp compares i and j and returns -1, 0 or 1.

func (Int) Float64

func (i Int) Float64() float64

Float64 returns the nearest float64 to the integer.

func (Int) Int64

func (i Int) Int64() (int64, bool)

Int64 returns the integer as an int64 and reports whether it fits.

func (Int) Kind

func (Int) Kind() Kind

Kind returns KindInt.

func (Int) Sign

func (i Int) Sign() int

Sign returns -1, 0 or 1 depending on the sign of the integer.

func (Int) String

func (i Int) String() string

String returns the decimal representation of the integer.

func (Int) Uint64

func (i Int) Uint64() (uint64, bool)

Uint64 returns the integer as a uint64 and reports whether it fits.

type InvalidUnmarshalError

type InvalidUnmarshalError struct {
	Type reflect.Type
}

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.

func (Kind) String

func (k Kind) String() string

String returns a human readable name for the kind.

type List

type List []Value

List is a sequence value such as [1, 2, 3].

func (List) Kind

func (List) Kind() Kind

Kind returns KindList.

func (List) String added in v1.1.0

func (v List) String() string

String returns the compact RON text, such as [1,2,3].

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.

func (Map) Get

func (m Map) Get(key Value) (Value, bool)

Get returns the value stored under a key equal to key.

func (Map) Kind

func (Map) Kind() Kind

Kind returns KindMap.

func (*Map) Set

func (m *Map) Set(key, v Value)

Set replaces the value stored under key, or appends a new entry if there is none.

func (Map) String added in v1.1.0

func (v Map) String() string

String returns the compact RON text, such as {"a":1}.

type MapEntry

type MapEntry struct {
	Key   Value
	Value Value
}

MapEntry is a single key value pair of a Map.

func (MapEntry) String added in v1.1.0

func (v MapEntry) String() string

String returns the compact RON text of the entry, such as "a":1.

type Marshaler

type Marshaler interface {
	MarshalRON() ([]byte, error)
}

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).

func Some

func Some(v Value) Option

Some wraps v into an Option.

func (Option) IsNone

func (o Option) IsNone() bool

IsNone reports whether o is None.

func (Option) Kind

func (Option) Kind() Kind

Kind returns KindOption.

func (Option) String added in v1.1.0

func (v Option) String() string

String returns the compact RON text, such as None or Some(1).

type Position

type Position struct {
	Offset int
	Line   int
	Column int
}

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.

func (Position) String

func (p Position) String() string

String returns the position as "line:column".

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) Decode added in v1.1.0

func (r Raw) Decode(v any) error

Decode decodes the value in r into v, like Unmarshal.

func (Raw) MarshalRON added in v1.1.0

func (r Raw) MarshalRON() ([]byte, error)

MarshalRON returns r, or None when r is nil.

func (*Raw) UnmarshalRON added in v1.1.0

func (r *Raw) UnmarshalRON(b []byte) error

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.

func NewRegistry

func NewRegistry() *Registry

NewRegistry returns an empty registry.

type String

type String string

String is a string value.

func (String) Kind

func (String) Kind() Kind

Kind returns KindString.

type Struct

type Struct struct {
	Name   string
	Fields []Field
}

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.

func (Struct) Get

func (s Struct) Get(name string) (Value, bool)

Get returns the value of the field with the given name.

func (Struct) Kind

func (Struct) Kind() Kind

Kind returns KindStruct.

func (*Struct) Set

func (s *Struct) Set(name string, v Value)

Set replaces the value of the field with the given name, or appends a new field if there is none.

func (Struct) String added in v1.1.0

func (v Struct) String() string

String returns the compact RON text, such as Point(x:1,y:2).

type SyntaxError

type SyntaxError struct {
	Msg string
	Pos Position
}

SyntaxError describes malformed RON input.

func (*SyntaxError) Error

func (e *SyntaxError) Error() string

type Tuple

type Tuple struct {
	Name   string
	Values []Value
}

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.

func (Tuple) Kind

func (Tuple) Kind() Kind

Kind returns KindTuple.

func (Tuple) String added in v1.1.0

func (v Tuple) String() string

String returns the compact RON text, such as Name(1,2) or (1,2).

type Unit

type Unit struct{}

Unit is the unit value ().

func (Unit) Kind

func (Unit) Kind() Kind

Kind returns KindUnit.

func (Unit) String added in v1.1.0

func (v Unit) String() string

String returns the compact RON text "()".

type UnknownFieldError

type UnknownFieldError struct {
	Field string
	Type  reflect.Type
	Path  string
}

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

type Unmarshaler interface {
	UnmarshalRON([]byte) error
}

Unmarshaler is implemented by types that can unmarshal a RON value themselves. UnmarshalRON receives the value re-encoded as compact RON.

type UnsupportedTypeError

type UnsupportedTypeError struct {
	Type reflect.Type
}

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

type UnsupportedValueError struct {
	Value reflect.Value
	Msg   string
}

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

func Parse(data []byte) (Value, error)

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

func ToValue

func ToValue(v any) (Value, error)

ToValue converts a Go value into a Value tree using the same rules as Marshal.

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.

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.

Jump to

Keyboard shortcuts

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