rustyon

package module
v1.0.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: 19 Imported by: 0

README

rustyon

Go Reference CI Release Go version Docs 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 and convert RON to and from JSON.
  • Zero dependencies, fuzz tested, Go 1.24+.

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.

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.

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

Performance

Everything is linear in the input size. Parsing into a dynamic tree runs within 20 percent of encoding/json; typed Marshal and Unmarshal are about 2.3x and 3x slower than encoding/json. A 13 KB file encodes in about 0.13 ms and decodes in about 0.3 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 None = Option{}

None is the empty Option.

Functions

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 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 and can be changed with a `ron:"name"` tag. The options omitempty and omitzero skip empty or zero fields, and "-" skips a field. A blank field of type struct{} named _ with the tag `ron:"Name,tuple"` sets the struct's RON name and, with the tuple option, encodes the struct as a tuple struct (a, b).
  • Pointers map to Option: nil is None and anything else is Some(v).
  • Nil interfaces map to None.
  • Types registered as enum variants (see Registry) map to Name, Name(a, b) or Name(field: v).
  • Value trees are written as they are.
  • Types implementing Marshaler or encoding.TextMarshaler are marshaled with those methods; text becomes a RON string.

Channels, functions and complex numbers cannot be encoded.

func MarshalIndent

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 RegisterEnum

func RegisterEnum[I any](variants ...VariantSpec)

RegisterEnum registers the interface type I as an enum with the given variants in DefaultRegistry. It panics if I is not an interface type, if a variant does not implement I, or if names or types are duplicated. Registering the same interface again adds variants to it.

Example
package main

import (
	"fmt"
	"log"

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

type Shape interface{ isShape() }

type Circle struct{ Radius float64 }

type Square struct {
	_    struct{} `ron:",tuple"`
	Side float64
}

type Dot struct{}

func (Circle) isShape() {}
func (Square) isShape() {}
func (Dot) isShape()    {}

func main() {
	// In real code this goes into an init function.
	rustyon.RegisterEnum[Shape](
		rustyon.Variant[Circle]("Circle"),
		rustyon.Variant[Square]("Square"),
		rustyon.Variant[Dot]("Dot"),
	)

	var shapes []Shape
	err := rustyon.Unmarshal([]byte(`[Circle(radius: 1.5), Square(2.0), Dot]`), &shapes)
	if err != nil {
		log.Fatal(err)
	}
	for _, s := range shapes {
		fmt.Printf("%T %+v\n", s, s)
	}
	out, _ := rustyon.Marshal(shapes)
	fmt.Println(string(out))
}
Output:
rustyon_test.Circle {Radius:1.5}
rustyon_test.Square {_:{} Side:2}
rustyon_test.Dot {}
[Circle(radius:1.5),Square(2.0),Dot]

func RegisterEnumIn

func RegisterEnumIn[I any](r *Registry, variants ...VariantSpec)

RegisterEnumIn is like RegisterEnum but registers into r.

func RegisterUnitEnum

func RegisterUnitEnum[T comparable](names map[T]string)

RegisterUnitEnum registers T as an enum whose variants carry no data, such as a set of integer constants. names maps each value to its variant name. Values of T encode as bare identifiers and decode from identifiers or strings. It panics if a name is invalid or used twice.

Example
package main

import (
	"fmt"
	"log"

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

type Level int

const (
	Easy Level = iota
	Hard
)

func main() {
	rustyon.RegisterUnitEnum(map[Level]string{Easy: "Easy", Hard: "Hard"})

	var l Level
	if err := rustyon.Unmarshal([]byte("Hard"), &l); err != nil {
		log.Fatal(err)
	}
	out, _ := rustyon.Marshal(struct{ Difficulty Level }{l})
	fmt.Println(l == Hard, string(out))
}
Output:
true (difficulty:Hard)

func RegisterUnitEnumIn

func RegisterUnitEnumIn[T comparable](r *Registry, names map[T]string)

RegisterUnitEnumIn is like RegisterUnitEnum but registers into r.

func Unmarshal

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.

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

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

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.

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.

type MapEntry

type MapEntry struct {
	Key   Value
	Value Value
}

MapEntry is a single key value pair of a Map.

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

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

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.

type Unit

type Unit struct{}

Unit is the unit value ().

func (Unit) Kind

func (Unit) Kind() Kind

Kind returns KindUnit.

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 command
Command rustyon formats, validates and converts RON (Rusty Object Notation) files.
Command rustyon formats, validates and converts RON (Rusty Object Notation) files.
internal
fields
Package fields computes and caches the RON view of Go struct types: field names, tag options and embedded struct promotion.
Package fields computes and caches the RON view of Go struct types: field names, tag options and embedded struct promotion.
syntax
Package syntax holds the RON lexer, literal decoding and the comment preserving formatter.
Package syntax holds the RON lexer, literal decoding and the comment preserving formatter.
Package ronjson converts between RON and JSON.
Package ronjson converts between RON and JSON.

Jump to

Keyboard shortcuts

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