Metadata-Version: 2.4
Name: fond
Version: 0.5.0
Summary: Foundation for Cooking, Foundation for Life.
Author-Email: chaz <bright.lid5647@fastmail.com>
License-Expression: MPL-2.0
License-File: LICENSE
Requires-Python: >=3.14
Requires-Dist: lazy-bear>=0.0.29; python_version < "3.15"
Requires-Dist: orjson>=3.13.0
Requires-Dist: tzdata>=2026.6
Requires-Dist: tzlocal>=5.3.1; sys_platform == "win32"
Provides-Extra: db
Requires-Dist: sqlalchemy>=2.0; extra == "db"
Provides-Extra: pydantic
Requires-Dist: pydantic>=2.14.2; extra == "pydantic"
Provides-Extra: profile
Requires-Dist: rich>=15.0.0; extra == "profile"
Description-Content-Type: text/markdown

# Fond

Foundation for Cooking, Foundation for Life.

[![pypi version](https://img.shields.io/pypi/v/fond.svg)](https://pypi.org/project/fond/)

> **Experimental:** This package is under active development. APIs may change without notice.

A C++26 header-only library and the Python package built on it: the building blocks we kept rewriting
for every project, in one self-contained place. The same C++ sits under both sides, so the headers you
vendor or compile against are the ones behind fond's Python tools: a file lock, a TOML table or a
MessagePack blob behaves the same from either language. External dependencies are kept to a minimum on
purpose (on Python, pydantic and tzdata), so one install brings the whole toolbox.

## Requirements

- A C++26 compiler: GCC 16 (primary, and it brings C++26 reflection with `-freflection`), or Clang + libc++ as the fallback
- Python 3.14+

Optional C++ integrations (CPython, CTRE, glm, Lua/sol2, SDL3, ...) are detected with `__has_include` and
switch on only when present.

## Three ways to use fond

None of these is the "real" one.

### 1. Vendored C++

Carry fond as a git submodule and link the one `fond::fond` target:

```cmake
set(FOND_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/vendor/fond" CACHE PATH "fond checkout")
include("${FOND_ROOT}/cmake/FondTarget.cmake")
target_link_libraries(app PRIVATE fond::fond)
```

`FOND_ROOT` is a cache variable, so when fond is vendored at several layers, the top-level checkout
wins and the build gets exactly one fond.

### 2. Build-time, for Python extensions

The pybind11 pattern: your build pulls the headers in, the code compiles into your own wheel, and your
users never install fond.

```toml
[build-system]
requires = ["scikit-build-core", "fond>=0.4.7"]
build-backend = "scikit_build_core.build"
```

```cmake
execute_process(COMMAND "${Python_EXECUTABLE}" -c "import fond; print(fond.get_cmake_dir())"
                OUTPUT_VARIABLE FOND_CMAKE_DIR OUTPUT_STRIP_TRAILING_WHITESPACE COMMAND_ERROR_IS_FATAL ANY)
include("${FOND_CMAKE_DIR}/FondTarget.cmake")
```

For the bindings themselves, `fond/py_tools/` wraps the raw CPython API in typed handles (`Module`,
`Dict`, `Tuple`, `Iterator`, `Class<>`, ...) with error guards, GIL helpers and type-slot macros. No
pybind11 needed.

```cpp
#include <fond/macros/strong_enum.hpp>
#include <fond/py_tools/handles/module.hpp>
#include <fond/py_tools/handles/str.hpp>
#include <fond/py_tools/int_enum.hpp>
#include <fond/py_tools/utils/err.hpp>
#include <fond/strings/ops.hpp>

STRONG_ENUM_STR(Mode, uint8_t, Debug, Release);

using namespace Fond::Py;

// shout(text: str) -> str. python_error() or any C++ exception becomes a Python exception at the boundary.
static PyObject* shout(PyObject*, PyObject* arg) {
  return guarded<"shout failed">([&]() -> PyObject* {
    if (!PyUnicode_Check(arg)) {
      PyErr_SetString(PyExc_TypeError, "shout() takes a str");
      python_error();
    }
    return String::From(Fond::Str::upper(String::borrow(arg).view())).release();
  });
}

static PyMethodDef demo_methods[] = {{"shout", shout, METH_O, "Upper-case a string."}, {}};
static PyModuleDef demo_module    = {
    .m_base     = PyModuleDef_HEAD_INIT,
    .m_name     = "demo",
    .m_doc      = "fond's README example.",
    .m_size     = -1,
    .m_methods  = demo_methods,
    .m_slots    = nullptr,
    .m_traverse = nullptr,
    .m_clear    = nullptr,
    .m_free     = nullptr,
};

PyMODINIT_FUNC PyInit_demo(void) {
  Module module = Module::Create(&demo_module);
  if (!module || !module.Add("Mode", make_int_enum<Mode>("Mode", "demo"))) return nullptr;  // the C++ enum as an IntEnum
  return module.release();
}
```

`demo.shout("hi")` gives `"HI"`, `demo.shout(3)` raises TypeError, and `list(demo.Mode)` is
`[<Mode.Debug: 0>, <Mode.Release: 1>]`, built from the C++ names so the two can't drift apart.

### 3. The Python package

```bash
uv add fond            # extras: fond[profile] (rich reports), fond[db] (SQLAlchemy)
```

`from fond import X` is the public, stable surface. Every other import path is internal and may move.

## Python tools

```python
from fond import Struct, field, MaybeIDK, lru_cache, now

class Point(Struct, frozen=True):
    x: float
    y: float = 0.0
    tags: list[str] = field(default_factory=list)

p = Point(1.5)                       # __init__, __eq__, __repr__ written for you; slotted
port = MaybeIDK().value_or(8080)     # std::optional in Python: empty is nullopt, and None is a value

@lru_cache(maxsize=256)              # functools-style; LRUCache is the same cache as a plain mapping
def area(w: int, h: int) -> int: return w * h

stamp = now()                        # EpochTimestamp: an int of epoch time that knows its precision
```

- **Records**: `Struct` / `@struct` (slotted, frozen, lazy fields, converters), `to_dict`, `is_built`
- **Optionals**: `MaybeIDK`, the `std::optional` API (`value_or`, `transform`, `and_then`, ...)
- **Collections**: `OrderedSet`, `FrozenDict` / `freeze`, `LRUCache` / `lru_cache` / `cache` / `once`, `SimpooQueue`, sentinels
- **Files**: `FileLock` (shared/exclusive, self-cleaning lock files), `atomic_write`, `Pathy`, `stat_info`, `.gitignore` matching
- **TOML**: Python bindings for [toml++](https://github.com/marzer/tomlplusplus): `toml_loads` / `toml_load_file` and
  `toml_dumps` / `toml_dump_file`, so you can write TOML too (the stdlib's `tomllib` only reads)
- **MessagePack**: `msgpack_pack` / `msgpack_unpack`, to and from bytes or files in one call
- **Time**: `EpochTimestamp`, durations to and from `"1h 30m"`, timers
- **Config**: `SettingsManager` (one JSON file), `ConfigManager` (TOML layers + env overrides into Pydantic)
- **Events**: `FSM`, `Signal`, `Bus`
- **Patterns**: `SingletonBase` / `SingletonWrap` (lazy, thread-safe singletons), `MISSING` / `NOTSET`
- **Numbers**: fixed-width ints (`int8_t`...), `float32_t`, `i8`...`u64` wrap/clamp, `Dollars`, `Vec2`/`Vec3`/`Vec4`
- **Profiling**: `fond.tools.utils.profiler` (benchmark, compare, import timing)
- **CLIs**: `generate-macros`, `amalgamate` (merge headers into one), `fond-dev`

### Experimental

These bend Python on purpose. They work, and they may change shape.

**Namespaces**: several named groups in one file, none of them types.

```python
from fond import namespace

class Angle(metaclass=namespace):
    PI = 3.141592653589793

    def radians(degrees: float) -> float:
        return degrees * Angle.PI / 180
```

**pycub**: C-style `# if` blocks, resolved before Python tokenizes the file (`fond-dev pycub install` once).

```python
# -*- coding: pycub -*-
# if __APPLE__
CACHE = "~/Library/Caches/app"
# elif _WIN32
CACHE = "%LOCALAPPDATA%/app"
# else
CACHE = "~/.cache/app"
# endif
```

**Privates**: C++ `private`, enforced by rewriting the class's bytecode. Anything imported from
`fond.tools.experiments` is considered unstable at this time.

```python
from fond.tools.experiments.privates import PrivateMeta, Private

class Account(metaclass=PrivateMeta):
    balance: Private[int]

    def __init__(self) -> None:
        self.balance = 0     # fine inside the class; Account().balance doesn't exist outside
```

## What's inside the C++

```toml
# server.toml
host = "example.com"
port = 443
mode = "Release"
```

```cpp
#include <fond/macros/strong_enum.hpp>
#include <fond/toml/define.hpp>
#include <fond/toml/reader.hpp>

#include <print>

STRONG_ENUM_STR(Mode, uint8_t, Debug, Release);  // names, from_string(), all_names(), no hand-written tables

struct ServerConfig {
  std::string host = "localhost";
  int         port = 8080;
  std::string mode = "Debug";
  TOML_DEFINE(ServerConfig, host, port, mode)    // toml_unpack() / toml_pack(), field by field
};

int main() {
  auto cfg  = ServerConfig::toml_unpack(Fond::Toml::Reader::parse_file("server.toml").as_table());
  Mode mode = Mode::from_string(cfg.mode).value_or(Mode::Debug);
  std::println("{}:{} in {}", cfg.host, cfg.port, mode.name());  // example.com:443 in Release
}
```

- **collections**: policy-based Set/Map (ordered, frozen), Arena, Pool, SlotMap, Deque, BitFlag, Trie, LRU caches, ring buffers, sparse sets
- **bytes / msgpack / toml / lua**: endian-aware binary readers and writers, a toml++ wrapper, plus `*_DEFINE` macros for struct serialization
- **py_tools**: typed CPython handles, the code behind fond's own extensions
- **logger**: `BasicLogger<Sinks...>` with sinks composed at compile time
- **argparse**: Python-style argument parsing
- **config**: ConfigManager with TOML and env-var overrides, KeyStore
- **strings / cli**: string helpers, UTF-8, fuzzy matching, a Rich-style console
- **math**: constexpr Vec/Mat4/quaternion, compile-time math, money, glm interop
- **mixins**: `Selfaboo` (CRTP `self()`, plus the type's own name, its base's and its lineage at compile time),
  `SingletonBase` (lazy, thread-safe `Get()` / `Reset()`), `Hashable` (a `TypeID` that matches across clang, GCC
  and MSVC), `IDMixin` (incrementing IDs per tag type)
- **types**: UUID, reflection and type-name helpers
- **time / concurrency / events / hashlib / files**: timers and epochs, thread pool and queues, events and FSM, SHA-256/CRC64/SipHash, file locks, atomic writes, walking and watching

## License

[Mozilla Public License 2.0](https://www.mozilla.org/en-US/MPL/2.0/). Use fond in anything, commercial or not; if you ship changes to
fond's own files, share those changes.
