libfyaml README

The project's README from github.com/pantoniou/libfyaml. As one markdown file: README.md.

libfyaml 1.0-beta2

Autotools CI CMake CI License: MIT Language: C

libfyaml is a high-performance YAML 1.2 and JSON parser/emitter with zero-copy operation, full document and event APIs, and the two major 1.0 features:

The 1.0 series adds a clear progression:

Why 1.0-beta2 matters

1.0.0-beta2 is a correctness and portability release. It adds no new API.

The linker interface version moves to 8:1:6: the interfaces are unchanged.

Generic runtime

The center of the generic API is fy_generic.

fy_generic is the sum-type value used to represent YAML and JSON data in C. It carries one runtime value of one type: null, bool, int, float, string, sequence, mapping, or YAML-specific wrappers.

It is a single pointer-sized word with inline storage for common small values, including 61-bit signed integers on 64-bit builds, short strings, and inline 32-bit floats.

The rest of the generic API is about working with fy_generic values:

That gives C a Python-like data model:

If you know Python dict / list workflows, serde_json::Value, tagged unions, or other sum-type/value-tree APIs, generics are the direct fit.

Reflection / meta-type

The reflection subsystem provides schema-driven typed serdes:

Reflection is the typed layer for stable C data models.

Python binding

The Python binding in python-libfyaml/ is built on the generic runtime. It is a direct bridge into the C generics API:

See the binding reference at python-libfyaml/docs/API.md.

Which layer should I use?

Core API

Choose the core library when you need:

Generic API

Choose generics when you need:

Reflection API

Choose reflection when you need:

Quick look

Generic literals in C

#include <libfyaml/libfyaml-generic.h>

fy_generic config = fy_mapping(
    "server", fy_mapping(
        "host", "localhost",
        "port", 8080,
        "tls",  true),
    "features", fy_sequence("http", "metrics", "admin"));

Generic parse and transform

fy_generic doc = fy_parse(
    "values: [1, 2, 3, 4]",
    FYOPPF_DISABLE_DIRECTORY | FYOPPF_INPUT_TYPE_STRING,
    NULL);

fy_generic values = fy_get(doc, "values", fy_invalid);
fy_generic first = fy_first(values);

Reflection-based typed parse

#include <libfyaml/libfyaml-reflection.h>

struct fy_reflection *rfl = fy_reflection_from_c_file_with_cflags(
    "schema.h", "", false, true, NULL);

struct fy_type_context_cfg cfg = {
    .rfl = rfl,
    .entry_type = "struct app_config",
};
struct fy_type_context *ctx = fy_type_context_create(&cfg);

Documentation roadmap

Start with these pages:

Reference pages:

Examples

The refreshed examples directory now covers the new alpha workflows:

See examples/README.md for the full list.

Existing strengths still apply

libfyaml also remains:

Supported platforms

libfyaml is built and tested on these platforms:

Platform Versions Architectures Compilers
Linux (Ubuntu) 22.04, 24.04, 26.04 x86-64, arm64 gcc, clang
Linux (other distributions) Debian stable and testing, Fedora, Arch, Rocky Linux 9, Alpine (musl), Nix x86-64 gcc
Linux (other architectures) Ubuntu / Debian i386, armv7, riscv64, ppc64 (big-endian) gcc
macOS 15, 26 arm64 Apple clang, gcc
Windows Server 2022, Server 2025, 11 x64, arm64, x86 (Win32) MSVC, clang, MinGW-w64 gcc
FreeBSD 15.1 x86-64 clang
NetBSD 11.0 x86-64 gcc
OpenBSD 7.9 x86-64 clang
illumos (OmniOS) r151058 x86-64 gcc

Pushes and pull requests build a subset of these. The full CMake matrix, including ASAN builds on Linux and macOS, runs daily, and every platform above runs weekly.

Some features depend on the platform:

Installation

Using CMake

find_package(libfyaml 1.0 REQUIRED)
target_link_libraries(your_app PRIVATE libfyaml::libfyaml)

If the installed package was built with libclang support, the CMake package also exports libfyaml_HAS_LIBCLANG.

Using pkg-config

pkg-config --cflags libfyaml
pkg-config --libs libfyaml

Building from source

Using CMake:

mkdir build && cd build
cmake ..
cmake --build .
ctest --progress -j"$(nproc)"

Using Autotools:

./bootstrap.sh
./configure
make
make check

Optional dependencies

Documentation builds

Sphinx documentation targets require the Python documentation toolchain:

PDF documentation also requires a LaTeX toolchain with:

On Debian/Ubuntu, the practical package set is:

python3 -m pip install sphinx sphinx_rtd_theme sphinx-markdown-builder linuxdoc
sudo apt-get install latexmk tex-gyre texlive-fonts-recommended texlive-latex-base texlive-latex-recommended texlive-latex-extra

Then build the docs with:

cmake --build build --target doc-html
cmake --build build --target doc-latexpdf

Python binding

The binding lives in python-libfyaml/. Run its tests with:

cd python-libfyaml
python3 -m pytest tests/

The binding is part of the 1.0 release story and shows the generic runtime's data model in regular use. v1.0.0-alpha3 improved the Windows story for the binding, v1.0.0-alpha4 repaired the wheel and sdist packaging flow, v1.0.0-alpha5 broadened build and CI coverage, and v1.0.0-alpha6 expands generic formatting/document handling. v1.0.0-alpha7 adds transparent parse caching, optimized generic emission, and Stable ABI Python wheels. v1.0.0-alpha8 adds durable storage, auto-anchor emission, stronger comment round-tripping, and more complete generic helper APIs. v1.0.0-beta1 starts the beta cycle with additional conversion, predicate, iteration, formatting, and correctness fixes on top of that alpha surface. v1.0.0-beta2 fixes the fuzzing reports and extends the supported platforms.

License

libfyaml is fully MIT licensed.

libfyaml (pantoniou/libfyaml)

Searching Database…

Что это?libfyaml — это высокопроизводительный парсер/эмиттер YAML 1.2 и JSON для C, созданный для работы без копирования данных с полными API дерева документа и потоковой передачи событий, и он проходит полный тестовый набор YAML.
Это библиотека, которую я подключаю к коду, или отдельный инструмент CLI?Это библиотека на C, которую вы подключаете к своей программе; в ней также есть привязка Python, построенная поверх его generic-рантайма, но отдельного инструмента CLI не описано.
Как добавить libfyaml в свой проект?Соберите его из исходников с помощью CMake, pkg-config или Autotools, затем подключите полученную библиотеку к своему проекту на C.
Нужен ли libclang для использования reflection API?Только если хотите создавать метаданные reflection прямо из аннотированных заголовков C; если вместо этого используете упакованные reflection-блобы, рантайм-зависимость от libclang не нужна.
Все ли функции доступны на каждой платформе?Подсистема generic (а значит, и привязки Python) требует statement expressions GCC или Clang на платформе с порядком байтов little-endian, поэтому не работает с MSVC и на платформах big-endian, а сборка мусора durable-arena работает только на Linux и macOS.
Какие операционные системы и архитектуры реально тестируются?Он собирается и тестируется на Linux (x86-64, arm64, а также i386/armv7/riscv64/ppc64), macOS (arm64), Windows (x64, arm64, x86), FreeBSD, NetBSD, OpenBSD и illumos.
В чём разница между API core, generics и reflection?Core API даёт низкоуровневый контроль над парсером/эмиттером/событиями/деревом документа; API generics позволяет работать с YAML/JSON как со значениями dict/list/scalar в питоновском стиле через sum-type fygeneric; reflection позволяет десериализовать YAML прямо в типизированные нативные структуры C (и эмиттировать из них) с использованием метаданных.
Что такое fygeneric?fygeneric — это единственное значение sum-type размером с указатель, используемое для представления любых данных YAML или JSON в C: null, bool, int, float, string, sequence или mapping, со встроенным хранением малых значений вроде 61-битных целых и коротких строк.
Чем важен релиз 1.0-beta2?Это релиз корректности и переносимости без нового API: он чинит десятки багов, найденных фаззингом (утечки памяти, двойные освобождения, use-after-free, неограниченная рекурсия), и расширяет протестированную поддержку на FreeBSD, NetBSD, OpenBSD, illumos, MinGW-w64 и другие архитектуры.
Можно ли сериализовать/десериализовать прямо в свои структуры C?Да, reflection API извлекает метаданные типов из аннотированных заголовков C (через libclang или упакованные блобы метаданных) и использует их, чтобы десериализовать YAML прямо в нативные структуры C и эмиттировать структуры обратно в YAML.
Creator
pantoniou
Size
16.4 MB
Stars
346
Age
7y
Commits · 90 Days