o
odin.langpkg.dev
packages / library / odin-toml

odin-toml

cfe2ad0library

A comprehensive TOML parser/serialiser for Odin

MIT · updated 11 months ago

TOML Parser for Odin

A comprehensive TOML (Tom's Obvious, Minimal Language) parser with ability to marshal Odin structures to TOML format, and unmarshal TOML data into Odin structures.

Features

  • ✅ Complete TOML v1.0.0 support
  • ✅ Marshal Odin structures to TOML format
  • ✅ Unmarshal TOML data to Odin structures with reflection

Installation

Simply copy the TOML package files into your project:

git clone https://github.com/yourusername/odin-toml.git
cp -r odin-toml/*.odin your-project/toml/

Usage

Basic Parsing

package main

import "toml"
import "core:fmt"

main :: proc() {
    // Parse a TOML string
    input := `
        title = "Example"
        
        [server]
        host = "localhost"
        port = 8080
        
        [database]
        connection_string = "postgresql://localhost/mydb"
        pool_size = 10
    `
    
    result := toml.parse(input)
    if result.success {
        // Access parsed data
        if root, ok := result.value.(^map[string]toml.Value); ok {
            if title, ok := root["title"].(string); ok {
                fmt.println("Title:", title)
            }
        }
    }
}

Unmarshaling to Structures

package main

import "toml"
import "core:fmt"

Config :: struct {
    title: string,
    server: struct {
        host: string,
        port: i64,
    },
    database: struct {
        connection_string: string,
        pool_size: i64,
    },
}

main :: proc() {
    config: Config
    err := toml.unmarshal_file("config.toml", &config)
    
    if err == .None {
        fmt.println("Title:", config.title)
        fmt.println("Server:", config.server.host, config.server.port)
        fmt.println("Database pool size:", config.database.pool_size)
    }
}

Marshaling Structures to TOML

package main

import "toml"
import "core:os"

Config :: struct {
    app_name: string,
    version: string,
    
    server: struct {
        host: string,
        port: i64,
        enable_ssl: bool,
    },
    
    features: []string,
}

main :: proc() {
    config := Config{
        app_name = "MyApp",
        version = "1.0.0",
        server = {
            host = "0.0.0.0",
            port = 443,
            enable_ssl = true,
        },
        features = {"auth", "api", "websocket"},
    }
    
    // Marshal to TOML format
    data, err := toml.marshal(config)
    if err == .None {
        // Write to file
        os.write_entire_file("output.toml", data)
    }
}

Public API

Core Types

// Value represents any TOML value
Value :: union {
    Null,
    string,
    i64,
    f64,
    bool,
    time.Time,
    []Value,
    ^map[string]Value,
}

// Parser result
Parser_Result :: struct {
    success: bool,
    value:   Value,
    errors:  []string,
    allocator: mem.Allocator,
}

Functions

parse(input: string) -> Parser_Result

Parses a TOML string and returns a parse result containing the parsed value tree.

unmarshal(toml_string: string, target: any) -> Unmarshal_Error

Unmarshals a TOML string into a target structure using reflection. The target must be a pointer to a struct.

unmarshal_file(filename: string, target: any) -> Unmarshal_Error

Reads and unmarshals a TOML file into a target structure. The target must be a pointer to a struct.

marshal(data: any) -> ([]u8, Marshal_Error)

Marshals an Odin structure into TOML format. Returns the TOML data as bytes.

Error Types

Unmarshal_Error :: enum {
    None,
    File_Not_Found,
    Parse_Failed,
    Type_Mismatch,
    Invalid_Target,
}

Marshal_Error :: enum {
    None,
    Invalid_Input,
    Unsupported_Type,
}

Features in Detail

Case-Insensitive Field Matching

The unmarshaler will match TOML keys to struct fields case-insensitively:

// This struct...
Person :: struct {
    FirstName: string,
    LastName: string,
}

// ...can unmarshal this TOML:
// firstname = "John"
// lastname = "Doe"

Automatic Type Conversions

The library automatically handles reasonable type conversions:

  • Integers to floats (e.g., 4242.0)
  • Floats to integers for whole numbers (e.g., 10.010)

Multiline String Support

Automatically uses TOML multiline string syntax for strings containing newlines:

text := "Line 1\nLine 2\nLine 3"
// Marshals to:
// text = """
// Line 1
// Line 2
// Line 3"""

Running Tests

The library includes comprehensive test suites:

odin build . -out:toml
./toml --test  # Run all tests

License

MIT License

Copyright (c) 2025 Maksim Kozhukh

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Acknowledgments