tinytoml

package module
v0.0.0-...-6862ba8 Latest Latest
Warning

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

Go to latest
Published: Mar 5, 2025 License: BSD-3-Clause Imports: 9 Imported by: 0

README

TinyTOML

A minimal TOML parser and encoder for Go that focuses on common configuration needs while maintaining strict TOML compatibility within its supported feature set.

Features

  • Basic TOML types:
    • Strings with escape sequences (\n, \t, \r, \)
    • Numbers (integers and floats, with sign support)
    • Booleans
    • Arrays (homogeneous, nested, and mixed-type)
  • Tables with dot notation
  • Dotted keys within tables
  • Table merging (last value wins)
  • Struct tags (toml:) for custom field names
  • Comment handling (inline and full-line)
  • Flexible whitespace handling
  • Type conversion following Go's standard rules
  • Strict parsing rules with detailed error messages

Installation

go get github.com/LixenWraith/tinytoml

Implementation Details

Limitations
  • No support for:
    • Table arrays
    • Hex/octal/binary/exponential number formats
    • Multi-line keys or strings
    • Inline table declarations
    • Inline array declarations within tables
    • Empty table declarations
    • Datetime types
    • Unicode escape sequences
    • Key character escaping
    • Literal strings (single quotes)
    • Comments are discarded in parse, not supported in encode
Implementation Choices
  • Follows encoding/json-style interface for Marshal/Unmarshal
  • Maps must have string keys
  • Keys must start with letter/underscore, followed by letters/numbers/dashes/underscores
  • Strings are always double-quoted
  • Recursive handling of nested structures
  • Integer bounds checking
  • Float format validation
  • Detailed error reporting

Usage

Basic Example
package main

import (
    "fmt"
    "log"
    "github.com/LixenWraith/tinytoml"
)

func main() {
    input := `
name = "Complex \nApp"
debug = true
workers = 42
rate = 3.14

# Array examples
ports = [8080, -6379]
hosts = ["local host", "bare_host"]

[server]
host = "localhost"
port = 8080

[database.primary]
host = "db1"
host.ip = "1.1.1.1"
host.port = 5432`

    var data any
    if err := tinytoml.Unmarshal([]byte(input), &data); err != nil {
        log.Fatal(err)
    }

    output, err := tinytoml.Marshal(data)
    if err != nil {
        log.Fatal(err)
    }

    fmt.Printf("Generated TOML:\n%s", output)
}
Configuration Management

TinyTOML is particularly useful for application configuration. Here's a typical usage pattern:

type ServerConfig struct {
    Server struct {
        Host string `toml:"host"`
        Port int    `toml:"port"`
        Name string `toml:"name"`
    } `toml:"server"`
    
    Database struct {
        Host     string `toml:"host"`
        Port     int    `toml:"port"`
        User     string `toml:"user"`
        Password string `toml:"password"`
    } `toml:"database"`
}

func main() {
    var config ServerConfig
    
    // Load existing config or use defaults
    if data, err := os.ReadFile("config.toml"); err == nil {
        if err := tinytoml.Unmarshal(data, &config); err != nil {
            log.Fatal(err)
        }
    } else {
        config = getDefaultConfig()
    }

    // Save config
    data, err := tinytoml.Marshal(config)
    if err != nil {
        log.Fatal(err)
    }
    os.WriteFile("config.toml", data, 0644)
}

See [examples/] directory for more comprehensive examples including:

  • Basic roundtrip conversion
  • Default configuration management
  • JSON/TOML configuration comparison

API

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

Converts a Go value into TOML format. Supports structs, maps (with string keys), and basic types.

Unmarshal(data []byte, v any) error

Parses TOML data into a Go value. Target must be a pointer to a struct or map.

Error Handling

TinyTOML provides error messages with context:

unmarshalErr := tinytoml.Unmarshal([]byte("[invalid table]"), &data)
// github.com/LixenWraith/tinytoml.tokenizeLine: invalid table name [line 1]

marshalErr := tinytoml.Marshal(make(chan int))
// github.com/LixenWraith/tinytoml.Marshal: unsupported type

License

BSD-3

Documentation

Overview

Package tinytoml provides a simplified TOML encoder and decoder

Package tinytoml implements a minimalist TOML parser and encoder that supports core TOML functionality while maintaining simplicity.

Features:

  • Basic value types: strings, integers, floats, booleans
  • Arrays of basic types, nested arrays, and mixed-type arrays
  • Nested tables using dotted notation
  • Dotted keys within tables (e.g. server.network.ip = "1.1.1.1")
  • Struct tags for custom field names (e.g. `toml:"name"`)
  • Comment handling (inline and single-line)
  • Whitespace tolerance
  • Table merging (last value wins)
  • Basic string escape sequences (\n, \t, \r, \\)

Limitations:

  • No support for table arrays
  • No support for hex, octal, binary, or exponential number formats
  • No multi-line keys or strings
  • No inline table declarations
  • No inline array declarations within tables
  • No empty table declarations
  • No datetime types
  • No unicode escape sequences
  • No key character escaping
  • No literal strings (single quotes)
  • Comments are discarded during parsing

The package aims for simplicity over completeness, making it suitable for basic configuration needs while maintaining strict TOML compatibility within its supported feature set.

Package tinytoml provides a simplified TOML encoder and decoder

Index

Constants

This section is empty.

Variables

SupportedTypes lists all Go types that can be marshaled/unmarshaled Includes basic types, composites and their variants

Functions

func Marshal

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

Marshal converts a Go value into TOML format. It supports basic types (string, int, float, bool), arrays, and nested structures. Maps must have string keys. Struct fields can use 'toml' tags for customization.

func Unmarshal

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

Unmarshal parses TOML data into a Go value. The target must be a pointer to a struct or map. It supports basic types, arrays, and nested structures through tables.

Types

This section is empty.

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

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