Skip to content

ThirdLetterC/toml

Repository files navigation

toml

TOML v1.1 parser in C23.

  • Requires a C23-capable compiler (-std=c23 or -std=c2x).
  • Implements TOML v1.1.

Usage

Parsing a TOML document creates a tree data structure rooted at toml_result_t::toptab. Use toml_get() for a single key lookup or toml_seek() for dotted multipart keys. Always call toml_free(result) to release the associated memory.

You can simply compile src/toml.c and include include/toml/toml.h in your project without building a separate library. See include/toml/toml.h for the full API surface and data types.

The following is a simple example (mirrors examples/simple.c):

/*
 * Parse the config file simple.toml:
 *
 * [server]
 * host = "www.example.com"
 * port = [8080, 8181, 8282]
 *
 */
#include "toml/toml.h"

#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>

static void error(const char *msg, const char *msg1) {
  fprintf(stderr, "ERROR: %s%s\n", msg, msg1 ? msg1 : "");
}

int main() {
  constexpr int kExitOk = 0;
  constexpr int kExitFail = 1;
  int rc = kExitFail;

  constexpr const char *PATH = "simple.toml";

  // Parse the toml file
  auto result = toml_parse_file_ex(PATH);

  // Check for parse error
  if (!result.ok) {
    error(result.errmsg, nullptr);
    toml_free(result);
    return rc;
  }

  // Extract values
  auto host = toml_seek(result.toptab, "server.host");
  auto port = toml_seek(result.toptab, "server.port");

  // Print server.host
  if (host.type != TOML_STRING) {
    error("missing or invalid 'server.host' property in config", nullptr);
    goto cleanup;
  }
  printf("server.host = %s\n", host.u.s);

  // Print server.port
  if (port.type != TOML_ARRAY) {
    error("missing or invalid 'server.port' property in config", nullptr);
    goto cleanup;
  }
  if (port.u.arr.size < 0) {
    error("invalid 'server.port' array size", nullptr);
    goto cleanup;
  }
  printf("server.port = [");
  for (int32_t i = 0; i < port.u.arr.size; i++) {
    auto elem = port.u.arr.elem[i];
    if (elem.type != TOML_INT64) {
      error("server.port element not an integer", nullptr);
      goto cleanup;
    }
    printf("%s%" PRId64, i ? ", " : "", elem.u.int64);
  }
  printf("]\n");

  rc = kExitOk;

cleanup:
  toml_free(result);
  return rc;
}

Building

With just:

just build
just run
just test

Manual build:

cc -std=c2x -Wall -Wextra -Wpedantic -Werror -Iinclude -o examples/simple \
  examples/simple.c src/toml.c

About

A fork of https://github.com/cktan/tomlc17 written in C23

Resources

License

Security policy

Stars

Watchers

Forks

Contributors