mirror of
https://github.com/xiaozhou233/JuiceAgent.git
synced 2026-12-05 21:15:56 +08:00
Compare commits
36
Commits
v4.1.1
..
4b9d371357
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4b9d371357 | ||
|
|
c710547cc8 | ||
|
|
4bb0d6ecd1 | ||
|
|
0e1280ef7f | ||
|
|
6eb1925ec3 | ||
|
|
59e705510e | ||
|
|
c548022068 | ||
|
|
6a43b3437a | ||
|
|
8cd4c54c07 | ||
|
|
3796cca9a1 | ||
|
|
80f926fde6 | ||
|
|
9351556cda | ||
|
|
19b1bfb88a | ||
|
|
3cd28c9bcb | ||
|
|
124c656400 | ||
|
|
e6da1d6fff | ||
|
|
08fe3a8815 | ||
|
|
9aebf29bb5 | ||
|
|
13145f77c9 | ||
|
|
5b0a26d49e | ||
|
|
4c3798735b | ||
|
|
5cf0d6ebd8 | ||
|
|
fd6fe0abdb | ||
|
|
5170d50517 | ||
|
|
af22f80b23 | ||
|
|
56a1c32f49 | ||
|
|
f38a28e8b3 | ||
|
|
eb7fd31817 | ||
|
|
92ad21003f | ||
|
|
11cf47c4c2 | ||
|
|
3626abb35a | ||
|
|
382bfb7fed | ||
|
|
560215c0ae | ||
|
|
55303b7dc9 | ||
|
|
41049f1852 | ||
|
|
396ec1a96f |
No files matched your search
@@ -0,0 +1,134 @@
|
||||
name: CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ main ]
|
||||
pull_request:
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
build-and-test:
|
||||
name: Build & integration tests (Windows, MinGW)
|
||||
runs-on: windows-latest
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Set up JDK
|
||||
uses: actions/setup-java@v4
|
||||
with:
|
||||
distribution: temurin
|
||||
java-version: '25'
|
||||
|
||||
- name: Set up MinGW-w64 toolchain
|
||||
uses: msys2/setup-msys2@v2
|
||||
with:
|
||||
msystem: MINGW64
|
||||
update: false
|
||||
install: >-
|
||||
mingw-w64-x86_64-gcc
|
||||
mingw-w64-x86_64-binutils
|
||||
mingw-w64-x86_64-cmake
|
||||
mingw-w64-x86_64-ninja
|
||||
|
||||
- name: Configure
|
||||
shell: msys2 {0}
|
||||
run: |
|
||||
# Link the C/C++ runtime statically, like w64devkit (the toolchain the
|
||||
# project is built with locally). Without this the DLLs depend on
|
||||
# libstdc++-6/libgcc_s_seh-1, which can be shadowed by a different
|
||||
# version elsewhere on the machine and fail to load.
|
||||
cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=Release \
|
||||
-DCMAKE_EXE_LINKER_FLAGS="-static-libgcc -static-libstdc++" \
|
||||
-DCMAKE_SHARED_LINKER_FLAGS="-static-libgcc -static-libstdc++"
|
||||
|
||||
- name: Build
|
||||
shell: msys2 {0}
|
||||
run: |
|
||||
cmake --build build
|
||||
|
||||
echo "compiler: $(command -v g++)"
|
||||
echo "target: $(gcc -dumpmachine)"
|
||||
|
||||
echo "--- imports (non-system DLLs) ---"
|
||||
objdump -p build/bin/libagent.dll build/bin/libloader.dll build/bin/libinject.dll \
|
||||
| grep 'DLL Name:' | sed 's/.*DLL Name:[[:space:]]*//' | sort -u
|
||||
|
||||
# Bundle whatever non-system DLLs are still imported, taken from the
|
||||
# toolchain that built them, so the tests can load libagent.dll
|
||||
# without depending on PATH.
|
||||
GCC_BIN="$(dirname "$(command -v gcc)")"
|
||||
deps="$(objdump -p build/bin/libagent.dll build/bin/libloader.dll build/bin/libinject.dll \
|
||||
| grep 'DLL Name:' | sed 's/.*DLL Name:[[:space:]]*//' | sort -u \
|
||||
| grep -viE '^(kernel32|user32|advapi32|ws2_32|shell32|ole32|gdi32|msvcrt|ucrtbase|ntdll|comdlg32|comctl32|psapi|version|iphlpapi|bcrypt|secur32|crypt32|winmm|imm32|netapi32|userenv|rpcrt4|setupapi|mswsock|dnsapi|normaliz)[.]dll$' \
|
||||
| grep -viE '^api-ms-win-')"
|
||||
for dll in $deps; do
|
||||
if [ -f "$GCC_BIN/$dll" ]; then
|
||||
cp -f "$GCC_BIN/$dll" build/bin/
|
||||
echo "bundled $dll"
|
||||
else
|
||||
echo "MISSING $dll (not found in $GCC_BIN)"
|
||||
fi
|
||||
done
|
||||
|
||||
echo "--- build/bin ---"
|
||||
ls -1 build/bin
|
||||
|
||||
- name: Run integration tests
|
||||
shell: pwsh
|
||||
run: |
|
||||
# Fallback for any remaining runtime DLLs.
|
||||
$env:PATH = "C:\msys64\mingw64\bin;$env:PATH"
|
||||
./tests/run-tests.ps1
|
||||
|
||||
- name: Package release zip
|
||||
shell: msys2 {0}
|
||||
run: cmake -P script/package.cmake
|
||||
|
||||
- name: Upload build artifacts
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: JuiceAgent-windows-x64
|
||||
path: dist/JuiceAgent_*.zip
|
||||
if-no-files-found: error
|
||||
retention-days: 14
|
||||
|
||||
build-linux:
|
||||
name: Build (Linux, GCC)
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Install build tools
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y --no-install-recommends \
|
||||
build-essential cmake ninja-build
|
||||
|
||||
- name: Configure
|
||||
run: |
|
||||
cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=Release
|
||||
|
||||
- name: Build
|
||||
run: |
|
||||
cmake --build build
|
||||
|
||||
echo "compiler: $(command -v g++)"
|
||||
echo "target: $(gcc -dumpmachine)"
|
||||
|
||||
echo "--- build/bin ---"
|
||||
ls -1 build/bin
|
||||
|
||||
- name: Package release tarball
|
||||
run: ./script/package.sh
|
||||
|
||||
- name: Upload build artifacts
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: JuiceAgent-linux-x64
|
||||
path: dist/JuiceAgent_*.tar.gz
|
||||
if-no-files-found: error
|
||||
retention-days: 14
|
||||
@@ -1,3 +1,4 @@
|
||||
build/
|
||||
.cache/
|
||||
*.log
|
||||
dist/
|
||||
@@ -0,0 +1,222 @@
|
||||
# AGENTS.md
|
||||
|
||||
Guidance for AI coding agents (and humans) working in this repository.
|
||||
|
||||
## Project at a glance
|
||||
|
||||
JuiceAgent is a JVMTI-based runtime injection framework for Windows. It injects
|
||||
into a running JVM (even with `DisableAttachMechanism=true`, no `-javaagent`),
|
||||
loads a JAR and calls an entry point, and exposes native APIs to
|
||||
redefine/retransform classes, query loaded classes and read bytecode.
|
||||
|
||||
Four binaries:
|
||||
|
||||
| Target | Output | Role |
|
||||
| --- | --- | --- |
|
||||
| `injector` | `injector.exe` | CLI driver: loads `libinject.dll` and injects `libloader.dll` into a target PID |
|
||||
| `libinject` | `libinject.dll` | Reflective DLL injector (exports `inject`, plus JNI bindings) |
|
||||
| `libloader` | `libloader.dll` | **Reflectively loaded** into the target JVM. Attaches to the JVM, reads `config.toml`, registers the embedded JuiceAgent-API jar, bootstraps the agent |
|
||||
| `libagent` | `libagent.dll` | The JVMTI agent. Registers `ClassFileLoadHook` and implements the native side of the JuiceAgent-API |
|
||||
|
||||
## Toolchain
|
||||
|
||||
- Windows x64, MinGW-w64 GCC (the maintainer uses [w64devkit](https://github.com/skeeto/w64devkit)), Ninja, CMake 3.15+
|
||||
- C++20
|
||||
- JDK 17+ for the Java side. `--enable-native-access=ALL-UNNAMED` is required from
|
||||
JDK 22 on to keep `System.load` warning-free (a future JDK will deny native
|
||||
access without it).
|
||||
|
||||
## Build
|
||||
|
||||
```powershell
|
||||
cmake --preset release # or: --preset debug
|
||||
cmake --build build
|
||||
```
|
||||
|
||||
Binaries land in `build/bin`.
|
||||
|
||||
Alternatively, without presets:
|
||||
|
||||
```powershell
|
||||
cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=Release
|
||||
cmake --build build
|
||||
```
|
||||
|
||||
## Test
|
||||
|
||||
Integration tests live in `tests/`. They are plain `main()` programs (not JUnit)
|
||||
that `System.load("resources/libagent.dll")` and call `JuiceAgent.init("")`.
|
||||
Two of them need the `injection` module compiled into `out/production/injection`.
|
||||
|
||||
Build first, then:
|
||||
|
||||
```powershell
|
||||
pwsh tests/run-tests.ps1
|
||||
# or point it at a specific JDK:
|
||||
pwsh tests/run-tests.ps1 -JdkHome "C:\Program Files\Zulu\zulu-25"
|
||||
```
|
||||
|
||||
The runner compiles the modules, refreshes `tests/resources` from `build/bin`
|
||||
(via `tests/copy-bin.bat`), compiles the tests, then runs every test and
|
||||
**asserts on its output**.
|
||||
|
||||
> Running the tests rebuilds the tracked file `tests/injection.jar`. After a local
|
||||
> run, restore it with `git checkout -- tests/injection.jar` before committing.
|
||||
|
||||
## Release
|
||||
|
||||
1. Bump `Version.txt` (`Major` / `Minor` / `Patch`).
|
||||
2. Add `docs/update/vX.Y.Z.md` (bilingual release notes) and an entry in
|
||||
`docs/update/CHANGELOG.md`.
|
||||
3. Commit the docs, then commit `Version X.Y.Z`, then tag `vX.Y.Z`.
|
||||
4. Build the package and attach it to a GitHub Release:
|
||||
|
||||
```powershell
|
||||
cmake -P script/package.cmake # -> dist/JuiceAgent_vX.Y.Z_x64.zip
|
||||
```
|
||||
|
||||
(`script/package.bat` wraps this but ends with `pause`.)
|
||||
|
||||
On Linux, `script/package.sh` packs `injector`, `libloader.so` and
|
||||
`libagent.so` into `dist/JuiceAgent_vX.Y.Z_x64_linux.tar.gz`:
|
||||
|
||||
```bash
|
||||
./script/package.sh
|
||||
```
|
||||
|
||||
`tests/`, `build/`, `dist/` and `*.log` are gitignored; `dist/*.zip` and
|
||||
`dist/*.tar.gz` are **not** committed.
|
||||
|
||||
## Hard rules (each of these was learned by breaking the build or a target JVM)
|
||||
|
||||
### 1. `libloader` must never throw a C++ exception
|
||||
|
||||
`libloader.dll` is loaded by a **reflective loader (manual mapping)**, so its
|
||||
unwind tables are never registered with the OS. A C++ exception thrown inside it
|
||||
**cannot be unwound or caught** - it crashes the target JVM with
|
||||
`EXCEPTION_ILLEGAL_INSTRUCTION` (a `try/catch` there is useless, not a fix).
|
||||
|
||||
- The `loader` target is compiled with `-fno-exceptions` (and
|
||||
`SPDLOG_NO_EXCEPTIONS`) on purpose: any exception-capable code fails the build.
|
||||
- Report problems with `spdlog` + an early `return`, never with `throw`.
|
||||
- This also means library code that can throw (`toml::parse_file`,
|
||||
`std::filesystem`, allocations) must be used in a non-throwing way. toml++
|
||||
switches to the non-throwing `toml::parse_result` API automatically when
|
||||
exceptions are disabled.
|
||||
|
||||
### 2. Config reads are non-throwing
|
||||
|
||||
`includes/JuiceAgent/Config.hpp` intentionally has **no throwing getters**. Use:
|
||||
|
||||
```cpp
|
||||
if (!cfg.contains("JarLoader.Mode")) { spdlog::error("Missing key: JarLoader.Mode"); return; }
|
||||
const std::string mode = cfg.get<std::string>("JarLoader.Mode", "");
|
||||
```
|
||||
|
||||
For required values, check `contains()` first and then `get(path, default)`.
|
||||
|
||||
### 3. Config schema changes are a coordinated edit
|
||||
|
||||
The current schema is v2 (`CONFIG_VERSION` in `includes/JuiceAgent/JuiceAgent.hpp`).
|
||||
It is validated at load time, so a mismatch makes the loader refuse to start.
|
||||
Changing the schema requires updating, together:
|
||||
|
||||
- `CONFIG_VERSION`
|
||||
- `docs/config.md`
|
||||
- the three `examples/*/config.toml`
|
||||
- the config block in `README.md` **and** `README_ZH.md`
|
||||
|
||||
### 4. Keep the MinGW runtime out of the shipped DLLs
|
||||
|
||||
Do not introduce a dependency on `libstdc++-6.dll` / `libgcc_s_seh-1.dll` /
|
||||
`libwinpthread-1.dll`. A DLL that needs them can pick up an incompatible copy
|
||||
from elsewhere on the machine and fail to load (`UnsatisfiedLinkError: The
|
||||
specified procedure could not be found`). w64devkit links the runtime statically;
|
||||
CI passes `-static-libgcc -static-libstdc++` to match.
|
||||
|
||||
### 5. Tests assert on output, not exit codes
|
||||
|
||||
The test programs print diagnostics and **still exit 0** when a step fails. Match
|
||||
an expected marker (e.g. `Bytes: 399`, `Modified!`, `Injection Invoked!`) -
|
||||
checking `$LASTEXITCODE` alone will silently pass broken builds.
|
||||
|
||||
Notes when adding tests:
|
||||
|
||||
- `GetClassBytesByName` only resolves **already loaded** classes; load the target
|
||||
first (`Class.forName("Target")`).
|
||||
- Tests that print to stderr make Windows PowerShell 5.1 unhappy; the runner sets
|
||||
`$ErrorActionPreference = "Continue"` and relies on explicit checks.
|
||||
|
||||
## Layout
|
||||
|
||||
```
|
||||
src/injector injector.exe
|
||||
src/libinject libinject.dll (reflective injector)
|
||||
src/libloader libloader.dll (runs in the target; exception-free)
|
||||
src/libagent libagent.dll (JVMTI agent)
|
||||
services/ IService implementations, self-registered via JUICEAGENT_REGISTER_SERVICE
|
||||
includes/eventbus.hpp typed EventBus
|
||||
includes/JuiceAgent Config.hpp / Logger.hpp / Utils.hpp / JuiceAgent.hpp (CONFIG_VERSION)
|
||||
includes/toml++ vendored
|
||||
includes/spdlog vendored
|
||||
tests/ integration tests + run-tests.ps1 + copy-bin.bat
|
||||
docs/ config.md, advanced.md, Inject.md, update/ (release notes + changelog)
|
||||
examples/ runnable end-to-end examples (each has config.toml + HowToUse)
|
||||
script/ package.cmake / package.bat
|
||||
```
|
||||
|
||||
## Conventions
|
||||
|
||||
### Services and the event bus
|
||||
|
||||
A service derives from `IService` (`src/libagent/includes/services/base.hpp`) and
|
||||
self-registers at file scope:
|
||||
|
||||
```cpp
|
||||
JUICEAGENT_REGISTER_SERVICE(::JuiceAgent::Services::MyService)
|
||||
```
|
||||
|
||||
Subscribe with the typed bus - there is no `EventId` and no `void*` casting:
|
||||
|
||||
```cpp
|
||||
listen<MyService, EventLoaded>(&MyService::onLoaded); // append
|
||||
listenFront<MyService, EventLoaded>(&MyService::onLoaded); // run before others
|
||||
```
|
||||
|
||||
Publish with `EventBus::getInstance().post(event)`. Call `unlistenAll()` in
|
||||
`onShutdown()`.
|
||||
|
||||
### Commit messages
|
||||
|
||||
`Type: subject`, then `- component: detail` bullets. Types used here:
|
||||
`Feat`, `BugFix`, `Refactor`, `Docs`, `CI`, and `Version X.Y.Z` for the release
|
||||
commit.
|
||||
|
||||
### Docs
|
||||
|
||||
`README.md` and `README_ZH.md` are kept in sync; keep both updated. Prose docs
|
||||
live in `docs/` (English). Release notes and the changelog live in `docs/update/`.
|
||||
|
||||
### Line endings
|
||||
|
||||
Tracked text files are **LF in the index, CRLF in the working tree** (no
|
||||
`.gitattributes`). When creating files, write CRLF to avoid noisy diffs.
|
||||
|
||||
## CI
|
||||
|
||||
`.github/workflows/ci.yml` has two jobs:
|
||||
|
||||
- `build-and-test` on `windows-latest`: JDK 25 (Temurin) + MinGW-w64 (MSYS2) +
|
||||
Ninja, then `configure -> build -> tests -> package`, uploading
|
||||
`dist/JuiceAgent_*.zip` as an artifact (14-day retention).
|
||||
- `build-linux` on `ubuntu-latest`: GCC + Ninja, then
|
||||
`configure -> build -> package` only — the integration tests are Windows-only —
|
||||
uploading `dist/JuiceAgent_*.tar.gz`.
|
||||
|
||||
CI-specific notes:
|
||||
|
||||
- It builds with `-static-libgcc -static-libstdc++` and also copies any remaining
|
||||
non-system imported DLLs next to the binaries (see rule 4).
|
||||
- The workflow prints the DLL import list - useful when a load error appears.
|
||||
- GitHub's unauthenticated REST API is limited to 60 requests/hour, so avoid
|
||||
polling workflow status in a loop; install `gh` or use a token instead.
|
||||
+11
-3
@@ -10,13 +10,21 @@ set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
|
||||
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
|
||||
|
||||
set(SRC_DIR ${CMAKE_SOURCE_DIR}/src)
|
||||
link_directories("${CMAKE_SOURCE_DIR}/lib")
|
||||
|
||||
if(WIN32)
|
||||
link_directories("${CMAKE_SOURCE_DIR}/lib")
|
||||
endif()
|
||||
|
||||
# libraries
|
||||
add_subdirectory(${CMAKE_SOURCE_DIR}/includes/ReflectiveDLLInjection)
|
||||
if (WIN32)
|
||||
add_subdirectory(${CMAKE_SOURCE_DIR}/includes/ReflectiveDLLInjection)
|
||||
endif()
|
||||
|
||||
# modules
|
||||
add_subdirectory(${SRC_DIR}/libloader)
|
||||
add_subdirectory(${SRC_DIR}/injector)
|
||||
add_subdirectory(${SRC_DIR}/libinject)
|
||||
if(WIN32)
|
||||
add_subdirectory(${SRC_DIR}/libinject)
|
||||
endif()
|
||||
|
||||
add_subdirectory(${SRC_DIR}/libagent)
|
||||
@@ -0,0 +1,403 @@
|
||||
# Quick Start for Agents
|
||||
|
||||
This guide tells an **agent** how to set up a JuiceAgent injection for a user:
|
||||
ask the right questions, generate the files, run the injection, and verify it.
|
||||
|
||||
Work through the steps in order. The result is a self-contained runtime
|
||||
directory called `app`, plus a short report to the user.
|
||||
|
||||
## Ground rules
|
||||
|
||||
- Only inject into a JVM that the user owns or is authorized to test. If that is
|
||||
unclear, stop and ask before doing anything else.
|
||||
- Do not modify the JuiceAgent native sources. Configuration and payload changes
|
||||
cover almost every request.
|
||||
- Keep every file in one runtime directory: `config.toml`, both JARs and the
|
||||
four binaries. Relative paths only behave predictably when they sit next to
|
||||
each other (see [Step 4](#step-4--write-configtoml)).
|
||||
- Never guess a PID. Confirm it with the user or read it from the process list.
|
||||
|
||||
## Project overview
|
||||
|
||||
JuiceAgent is a JVMTI-based runtime injection framework for Windows. It injects
|
||||
into a running JVM even when `DisableAttachMechanism=true` and without a
|
||||
`-javaagent` flag, loads a JAR and calls an entry point, and exposes native APIs
|
||||
to redefine/retransform classes, query loaded classes and read bytecode.
|
||||
|
||||
## Step 1 — Check the environment (do this yourself, do not ask the user)
|
||||
|
||||
**1.1 JDK.** `javac`, `jar` and `jps` ship with the JDK, so a full JDK is
|
||||
required — a bare JRE is not enough.
|
||||
|
||||
```
|
||||
java -version
|
||||
```
|
||||
|
||||
If the JDK is missing or older than 1.8, ask the user to install JDK 1.8 or
|
||||
higher.
|
||||
|
||||
**1.2 JuiceAgent binaries.** When built from source they are in `build/bin`
|
||||
(release archives put them wherever they were extracted):
|
||||
|
||||
```
|
||||
ls build/bin
|
||||
```
|
||||
|
||||
Expected files:
|
||||
|
||||
```
|
||||
injector.exe libinject.dll libloader.dll libagent.dll
|
||||
```
|
||||
|
||||
If they are missing, ask the user to pick one of:
|
||||
|
||||
- **Method 1 (recommended):** download the latest release from
|
||||
https://github.com/xiaozhou233/JuiceAgent/releases/latest
|
||||
- **Method 2:** build from source — see the "How To Build" section of `README.md`
|
||||
|
||||
**1.3 Create the runtime directory.** Copy the four files into one directory and
|
||||
call it `app` for the rest of this guide. A complete `app` looks like:
|
||||
|
||||
```
|
||||
app/
|
||||
├─ injector.exe libinject.dll libloader.dll libagent.dll
|
||||
├─ config.toml # Step 4
|
||||
├─ payload.jar # Step 3 (Q3)
|
||||
├─ injection/ # Step 3 (Q5), dependency JARs; BuiltIn mode only
|
||||
├─ src/ # payload source, if you generate it
|
||||
└─ build/ # compiler output, one subdirectory per artifact
|
||||
├─ target/ # demo target classes
|
||||
└─ payload/ # payload classes
|
||||
```
|
||||
|
||||
## Step 2 — Gather requirements (ask the user)
|
||||
|
||||
Ask these six questions and translate them into the user's language. Each
|
||||
answer maps to a concrete decision, so do not skip any of them.
|
||||
|
||||
| # | Question | Decides |
|
||||
| --- | --- | --- |
|
||||
| Q1 | Which process do you want to inject into? (PID / process name / start a demo target — recommended) | the target and its working directory |
|
||||
| Q2 | Is the target a standard, unmodified JVM? | whether injection will work at all |
|
||||
| Q3 | What should the injected code do? (verify the link / your own code / modify bytecode) | the payload JAR, entry class and method |
|
||||
| Q4 | Does the payload need JuiceAgent-API? (yes / no / don't know) | `JarLoader.Mode` |
|
||||
| Q5 | Does the payload depend on other libraries? (yes / no) | `JarLoader.InjectionDir` |
|
||||
| Q6 | How should the injection be triggered? (`injector.exe` / JNI JavaInjector) | the commands in Step 5 |
|
||||
|
||||
## Step 3 — Apply the answers
|
||||
|
||||
### Q1 — Target process
|
||||
|
||||
- **PID:** remember it for Step 5.
|
||||
- **Process name:** resolve it to a PID with `jps -l`. Every JVM appears as
|
||||
`java.exe`, so match the main class or JAR path in the `jps -l` output, or use
|
||||
`Get-Process <name>` on Windows.
|
||||
- **Start a demo target (recommended when the user has no target):** write
|
||||
`app/target.java`:
|
||||
|
||||
```java
|
||||
import java.lang.management.ManagementFactory;
|
||||
|
||||
public class target {
|
||||
public static void main(String[] args) {
|
||||
String pid = ManagementFactory.getRuntimeMXBean().getName().split("@")[0];
|
||||
try {
|
||||
while (true) {
|
||||
System.out.println("[Target] I am the target JVM (PID: " + pid + ")");
|
||||
Thread.sleep(1000);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Compile and run it, **with `app` as the working directory**:
|
||||
|
||||
```
|
||||
javac -encoding UTF-8 --release 8 -d app/build/target app/target.java
|
||||
```
|
||||
|
||||
```powershell
|
||||
Start-Process -FilePath java -ArgumentList "-cp","build/target","target" -WorkingDirectory "<path-to-app>"
|
||||
```
|
||||
|
||||
The target prints its PID every second; `jps -l` also lists it.
|
||||
|
||||
> Starting the target with `app` as its working directory is not cosmetic. See
|
||||
> [Step 4](#step-4--write-configtoml) for why the working directory decides which
|
||||
> `config.toml` the injected loader finds.
|
||||
|
||||
### Q2 — Standard JVM
|
||||
|
||||
- **Standard JVM / `DisableAttachMechanism=true`:** continue — JuiceAgent is
|
||||
designed for exactly this case.
|
||||
- **Custom or modified JVM:** continue, but warn the user that JuiceAgent is
|
||||
only tested against a regular JVM and may not work.
|
||||
|
||||
### Q3 — Payload
|
||||
|
||||
**Verify the link.** Write `app/src/Main.java`:
|
||||
|
||||
```java
|
||||
public class Main {
|
||||
public static void run() {
|
||||
System.out.println("[Demo] Injection succeeded! Hello from JuiceAgent.");
|
||||
System.out.println("[Demo] Current thread: " + Thread.currentThread().getName());
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Build it into `app/payload.jar`. Each artifact gets its own output directory, so
|
||||
packaging the payload never picks up the demo target's classes:
|
||||
|
||||
```
|
||||
javac -encoding UTF-8 --release 8 -d app/build/payload app/src/Main.java
|
||||
jar --create --file app/payload.jar -C app/build/payload .
|
||||
```
|
||||
|
||||
The class name `Main` and method name `run` are needed in Step 4.
|
||||
|
||||
**Own code.** Ask the user for the payload JAR and record its fully qualified
|
||||
entry class and method. The entry method must be `public`, `static` and take no
|
||||
arguments (the project documents this as `public static void`; the return value
|
||||
is ignored). It is resolved by reflection, so a non-public, non-static or
|
||||
parameterized method is only reported as a failure at invocation time — the JAR
|
||||
itself still loads.
|
||||
|
||||
**Modify bytecode.** Point the user at `examples/retransform-class`. Payloads
|
||||
that redefine or retransform classes use JuiceAgent-API, so Q4 must resolve to
|
||||
`BuiltIn`.
|
||||
|
||||
### Q4 — JuiceAgent-API
|
||||
|
||||
| Answer | `JarLoader.Mode` |
|
||||
| --- | --- |
|
||||
| Yes | `BuiltIn` |
|
||||
| No | `CustomJar` |
|
||||
| I don't know | `BuiltIn` |
|
||||
|
||||
`BuiltIn` (recommended) runs in two stages, and **both stages read
|
||||
`config.toml` from the runtime directory**:
|
||||
|
||||
1. `libloader` extracts the embedded JuiceAgent-API JAR into `%TEMP%`, adds it
|
||||
to the system class loader and calls `JuiceAgentBootstrap.start`, which loads
|
||||
`libagent.dll` (from `JuiceAgentNativeLibraryPath`) and initializes the JVMTI
|
||||
agent.
|
||||
2. The agent's `JarLoaderService` reads the `JarLoader.*` keys again, then the
|
||||
`JarLoader` module adds every `*.jar` in `InjectionDir` to the system class
|
||||
loader, loads `JarPath` and invokes `EntryClass.EntryMethod`.
|
||||
|
||||
`Enabled` and `InjectionDir` are used in `BuiltIn` mode only. Omitting a key
|
||||
silently falls back to a default, which is a common source of confusion:
|
||||
`InjectionDir` defaults to `./injection`, `JarPath` to `./Entry.jar`,
|
||||
`EntryClass` to `Example.Main` and `EntryMethod` to `start`.
|
||||
|
||||
`CustomJar` skips JuiceAgent-API and `libagent.dll` entirely: `libloader` adds
|
||||
`JarPath` itself to the system class loader and invokes the entry method. In this
|
||||
mode `Enabled` and `InjectionDir` are ignored, so any library the payload needs
|
||||
must be bundled inside the payload JAR (or already on the target's classpath).
|
||||
|
||||
### Q5 — Other libraries
|
||||
|
||||
- **Yes:** create `app/injection/` and copy the dependency JARs into it. Every
|
||||
`*.jar` there is loaded before the payload (`BuiltIn` mode only).
|
||||
- **No:** still create the empty directory if the config references it, or drop
|
||||
`InjectionDir` from the config.
|
||||
|
||||
### Q6 — Injection way
|
||||
|
||||
- **`injector.exe`:** nothing to prepare, continue to Step 4.
|
||||
- **JNI JavaInjector:** copy the whole `examples/inject-via-java-api/injector`
|
||||
directory to `app/injector/`, then build it:
|
||||
|
||||
```
|
||||
app\injector\build.bat
|
||||
```
|
||||
|
||||
That directory ships a prebuilt `JuiceAgent-JavaInjector-1.0-SNAPSHOT.jar`;
|
||||
`build.bat` merges the example's `JavaInjector.class` into it and sets the main
|
||||
class, so keep the JAR in place.
|
||||
|
||||
## Step 4 — Write config.toml
|
||||
|
||||
The file must be named exactly `config.toml` and placed in the directory that
|
||||
`libloader` treats as the **runtime directory** (see the table below). Do not
|
||||
rename it and do not scatter it across directories.
|
||||
|
||||
```toml
|
||||
# See docs/config.md for more information:
|
||||
# https://github.com/xiaozhou233/JuiceAgent/blob/main/docs/config.md
|
||||
|
||||
[JuiceAgent]
|
||||
Version = 2
|
||||
JuiceAgentNativeLibraryPath = ""
|
||||
|
||||
[JarLoader]
|
||||
# BuiltIn: use the built-in jar loader (recommended; supports JuiceAgent-API)
|
||||
# CustomJar: load the JAR directly, without JuiceAgent-API
|
||||
# https://github.com/xiaozhou233/JuiceAgent/blob/main/docs/advanced.md#load-custom-api--directly-load-jar
|
||||
Enabled = true
|
||||
|
||||
# Q4
|
||||
Mode = "BuiltIn"
|
||||
|
||||
# BuiltIn mode only; Q5
|
||||
InjectionDir = "./injection"
|
||||
|
||||
# Q3
|
||||
JarPath = "./payload.jar"
|
||||
EntryClass = "Main"
|
||||
EntryMethod = "run"
|
||||
```
|
||||
|
||||
- `Version` must stay `2`. A mismatch makes the loader refuse to start.
|
||||
- `JuiceAgentNativeLibraryPath = ""` means "`libagent.dll` in the runtime
|
||||
directory". Change it to an absolute path only if `libagent.dll` lives
|
||||
elsewhere.
|
||||
- `Mode = "CustomJar"` requires `JarPath`, `EntryClass` and `EntryMethod`
|
||||
(there are no defaults in that mode); `Enabled` and `InjectionDir` are unused.
|
||||
- Paths starting with `./` are resolved against the runtime directory; absolute
|
||||
paths are used as-is.
|
||||
|
||||
### Which directory is the runtime directory?
|
||||
|
||||
This is where most failed setups go wrong: `libloader` does not take the config
|
||||
directory from the `injector.exe` command line.
|
||||
|
||||
| How you inject | Directory `config.toml` is read from |
|
||||
| --- | --- |
|
||||
| Interactive `injector.exe` (type the PID) | the **injector process's** current directory — so `cd app` first |
|
||||
| `injector.exe <pid> <libloader.dll> [libinject.dll]` | the **target JVM's** current directory (no directory is passed) |
|
||||
| JavaInjector (JNI) | the `config_path` you enter; an empty value falls back to the target JVM's working directory |
|
||||
|
||||
Consequences:
|
||||
|
||||
- With the argument form, `config.toml` **and** every `./` path inside it
|
||||
(`JarPath`, `InjectionDir`, `libagent.dll`) resolve against the target JVM's
|
||||
working directory.
|
||||
- If the user cannot control the target's working directory, use absolute paths
|
||||
in `config.toml` — including `JuiceAgentNativeLibraryPath`.
|
||||
- JNI injection is the most predictable option, because the config directory is
|
||||
passed explicitly.
|
||||
|
||||
## Step 5 — Run the injection
|
||||
|
||||
### 5.1 Use `injector.exe`
|
||||
|
||||
```
|
||||
cd app
|
||||
```
|
||||
|
||||
`cd app` matters: `injector.exe` loads `libinject.dll` **by name from the
|
||||
current directory**, and in interactive mode the current directory is also the
|
||||
runtime directory.
|
||||
|
||||
**Interactive:**
|
||||
|
||||
```
|
||||
.\injector.exe
|
||||
```
|
||||
|
||||
It prints the `jps -l` output, then `Input PID:`. Type the PID of the target JVM
|
||||
and press Enter.
|
||||
|
||||
> The program always ends with `Press any key to exit...` and waits for stdin.
|
||||
> If you drive it from a script, feed it a newline after the PID and do not wait
|
||||
> for the process to exit on its own.
|
||||
|
||||
**With arguments:**
|
||||
|
||||
```
|
||||
.\injector.exe <PID> "<path-to-app>\libloader.dll" "<path-to-app>\libinject.dll"
|
||||
```
|
||||
|
||||
The third argument is the path to **`libinject.dll`**, not a config directory.
|
||||
Omit it to let `injector.exe` load `libinject.dll` from the current directory.
|
||||
Remember that this form reads `config.toml` from the *target's* working
|
||||
directory (Step 4).
|
||||
|
||||
### 5.2 Use JNI JavaInjector
|
||||
|
||||
Run it from `app`, because the example loads `./libinject.dll`:
|
||||
|
||||
```
|
||||
java -cp injector\JuiceAgent-JavaInjector-1.0-SNAPSHOT.jar JavaInjector
|
||||
```
|
||||
|
||||
```
|
||||
PID: 1234
|
||||
Dll: <path-to-app>\libloader.dll
|
||||
config_path: <path-to-app>
|
||||
```
|
||||
|
||||
Enter the target PID, the path to `libloader.dll`, and the directory containing
|
||||
`config.toml`. Leaving `config_path` empty behaves like the argument form above:
|
||||
the runtime directory falls back to the **target JVM's** working directory, so
|
||||
always pass the directory explicitly.
|
||||
|
||||
## Step 6 — Verify
|
||||
|
||||
Verification has two independent sources. Do not confuse them: the
|
||||
`[JuiceAgent JarLoader]` progress lines are printed to the **target's stdout**,
|
||||
while the diagnostic logs are written to **files**.
|
||||
|
||||
**1. Target stdout** — this is the user-visible proof:
|
||||
|
||||
```
|
||||
[JuiceAgent API] RuntimeDir : <the directory actually used>
|
||||
[JuiceAgent JarLoader] Loading entry jar: ...
|
||||
[JuiceAgent JarLoader] Resolving class: Main
|
||||
[JuiceAgent JarLoader] Invoking method: Main.run
|
||||
[JuiceAgent JarLoader] Entry method invoked successfully.
|
||||
[Demo] Injection succeeded! Hello from JuiceAgent.
|
||||
```
|
||||
|
||||
The `[JuiceAgent API]` banner prints the effective runtime directory and the
|
||||
native library path, which is the fastest way to confirm the Step 4 rules.
|
||||
|
||||
**2. Log files** — two files are written **relative to the target JVM's working
|
||||
directory** and truncated on every injection:
|
||||
|
||||
| File | Look for |
|
||||
| --- | --- |
|
||||
| `libloader.log` | `DllMain: DLL_PROCESS_ATTACH, runtime_dir:` and `[PreLoad] Runtime directory:` |
|
||||
| `libagent.log` | `[JuiceAgent] Added JVMTI capabilities`, `[JarLoaderService] Loaded jar:`, and `JNI Exception occurred at:` when the payload itself throws |
|
||||
|
||||
If the target has no console (a service or a detached window), the stdout
|
||||
markers are invisible — verify through the log files instead.
|
||||
|
||||
Report the outcome to the user, including the exact `app` path, the injection
|
||||
command used, and the observed output.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
| Symptom | Likely cause |
|
||||
| --- | --- |
|
||||
| Injection reports success but nothing happens | `config.toml` is not in the directory `libloader` actually used — see Step 4 |
|
||||
| `RuntimeDir :` in the banner is not `app` | The runtime directory fell back to the target JVM's working directory — see Step 4 |
|
||||
| `[JuiceAgent API] JuiceAgent library not found at: <path>` | `libagent.dll` could not be resolved — set an absolute `JuiceAgentNativeLibraryPath`, or fix the runtime directory |
|
||||
| `Failed to load injector library` / error 2 | `injector.exe` was not started from `app`, and no `libinject.dll` path was passed |
|
||||
| `Failed to open DLL file` | The `libloader.dll` path is wrong |
|
||||
| `libloader.log` / `libagent.log` seem missing | They are written in the target JVM's working directory, not your shell's |
|
||||
| Loader refuses to start | `[JuiceAgent] Version` is not `2` |
|
||||
| `Missing required config key: JarLoader.Mode` | `JarLoader.Mode` was omitted |
|
||||
| Errors about missing `JarPath` / `EntryClass` / `EntryMethod` | `Mode = "CustomJar"` requires all three |
|
||||
| `Failed to load jar: ...\Entry.jar` | `JarPath` was omitted and the default was used |
|
||||
| The JAR loads but the entry call fails | The method is not `public static` with no parameters, or `EntryClass` is not fully qualified |
|
||||
| `JNI Exception occurred at: CallStaticVoidMethod failed` | The payload threw — read the stack trace printed next to it |
|
||||
| The injected process hangs for ~30 s, then `Failed to attach to JVM!` | The target process is not a JVM (the loader retries 30 × 1 s before giving up) |
|
||||
| `jps` does not list the target | The target is 32-bit (JuiceAgent ships x64 only) or runs with different privileges |
|
||||
| Injection fails on an elevated target | Run `injector.exe` elevated too |
|
||||
| Antivirus flags the binaries | Expected false positive — see `docs/Antivirus-False-Positive.md` |
|
||||
| Native-access warning on JDK 22+ | The payload loads a native library; the target JVM needs `--enable-native-access=ALL-UNNAMED` |
|
||||
|
||||
## Done checklist
|
||||
|
||||
- [ ] A JDK 1.8+ with `javac`, `jar` and `jps` is available
|
||||
- [ ] `app/` contains all four JuiceAgent binaries
|
||||
- [ ] The payload JAR exists and its entry method is `public static` and takes no arguments
|
||||
- [ ] `config.toml` is in the directory `libloader` actually uses (Step 4), `Version = 2`, and every key matches the Q3–Q5 answers
|
||||
- [ ] The injection command reported success
|
||||
- [ ] The `[JuiceAgent API]` banner shows the expected `RuntimeDir`, and the payload output appears with no errors in the logs
|
||||
@@ -4,6 +4,11 @@
|
||||
|
||||
JuiceAgent is an advanced JVMTI-based injection framework for runtime JAR loading, bytecode transformation, and runtime JVM instrumentation. It injects into a running JVM process even when `DisableAttachMechanism=true`, without requiring `-javaagent` startup arguments or the attach mechanism.
|
||||
|
||||
Two platforms are supported:
|
||||
|
||||
- **Windows x64** — reflective DLL injection (`injector.exe` + `libinject.dll`).
|
||||
- **Linux x64** — `ptrace` attach plus a remote `dlopen` call that makes the target JVM load `libloader.so` itself.
|
||||
|
||||
**Warning**: This project is still experimental and is not recommended for production use. Use it at your own risk.
|
||||
|
||||
> **Tips**: Some antivirus software may flag JuiceAgent as malware. See [Antivirus False Positive Notice](docs/Antivirus-False-Positive.md) for details.
|
||||
@@ -14,6 +19,13 @@ Welcome to join our QQ/Discord group for more information and support:
|
||||
- Discord: [JuiceDev](https://discord.gg/AQTnUyWNNJ)
|
||||
- QQ Group: 1103504356
|
||||
|
||||
> **New to JuiceAgent?** You do not have to wire up the injection by hand. A
|
||||
> coding agent such as OpenCode can do it for you: open this repository in the
|
||||
> agent and ask it to read [`QuickStartForAgents.md`](QuickStartForAgents.md) and
|
||||
> follow it. That guide covers the whole process — environment check, requirement
|
||||
> gathering, `config.toml`, injection and verification — and is written to be
|
||||
> executed by an agent. Simply tell the agent:
|
||||
> "Read `QuickStartForAgents.md` and follow it to inject my JAR."
|
||||
|
||||

|
||||

|
||||
@@ -25,7 +37,7 @@ Welcome to join our QQ/Discord group for more information and support:
|
||||

|
||||

|
||||

|
||||

|
||||

|
||||
|
||||

|
||||

|
||||
@@ -40,6 +52,7 @@ Welcome to join our QQ/Discord group for more information and support:
|
||||
- [Features](#features)
|
||||
- [Project Structure](#project-structure)
|
||||
- [Quick Start](#quick-start)
|
||||
- [Linux Support](#linux-support)
|
||||
- [JuiceAgent API](#juiceagent-api)
|
||||
- [Examples](#examples)
|
||||
- [How To Build](#how-to-build)
|
||||
@@ -69,6 +82,14 @@ With JuiceAgent, developers can:
|
||||
|
||||
The `JuiceAgent-API` jar is embedded in the native binaries, so no separate download is required.
|
||||
|
||||
On Linux the pipeline is the same, only the injection step changes. The injector
|
||||
attaches to the target process with `ptrace`, saves its registers, and performs a
|
||||
remote `dlopen` so the JVM loads `libloader.so` in-process (no `LD_PRELOAD`, no
|
||||
`-javaagent`). `libloader.so` then starts from an ELF constructor, resolves its
|
||||
runtime directory (`JuiceAgent_ConfigPath`, or `$HOME/.juiceagent` by default),
|
||||
and drives the agent exactly like the Windows loader. See
|
||||
[Linux Support](#linux-support).
|
||||
|
||||
## Features
|
||||
|
||||
- Load external JARs into the Bootstrap or System ClassLoader
|
||||
@@ -83,10 +104,10 @@ The `JuiceAgent-API` jar is embedded in the native binaries, so no separate down
|
||||
|
||||
## Project Structure
|
||||
|
||||
- `src/libloader` — `libloader.dll`. Injected into the target JVM. Attaches to the JVM, parses `config.toml`, injects the embedded `JuiceAgent-API`, and bootstraps the agent.
|
||||
- `src/libagent` — `libagent.dll`. The JVMTI agent. Registers callbacks (e.g. `ClassFileLoadHook`) and implements the native side of `JuiceAgent-API`.
|
||||
- `src/injector` — `injector.exe`. Command-line driver that loads `libinject.dll` and injects `libloader.dll` into the target process.
|
||||
- `src/libinject` — `libinject.dll`. Reflective DLL injector. Exposes a native `inject` function and JNI bindings (`cn.xiaozhou233.juiceagent.injector.InjectorNative`).
|
||||
- `src/libloader` — `libloader.dll` (Windows) / `libloader.so` (Linux). Injected into the target JVM. Attaches to the JVM, parses `config.toml`, injects the embedded `JuiceAgent-API`, and bootstraps the agent.
|
||||
- `src/libagent` — `libagent.dll` (Windows) / `libagent.so` (Linux). The JVMTI agent. Registers callbacks (e.g. `ClassFileLoadHook`) and implements the native side of `JuiceAgent-API`.
|
||||
- `src/injector` — `injector.exe` (Windows) / `injector` (Linux). Command-line driver that loads the loader into the target process.
|
||||
- `src/libinject` — `libinject.dll` (Windows only). Reflective DLL injector. Exposes a native `inject` function and JNI bindings (`cn.xiaozhou233.juiceagent.injector.InjectorNative`).
|
||||
|
||||
## Quick Start
|
||||
|
||||
@@ -96,6 +117,10 @@ The `JuiceAgent-API` jar is embedded in the native binaries, so no separate down
|
||||
|
||||
Download `JuiceAgent_vx.x.x_x64.zip` from the [releases](https://github.com/xiaozhou233/JuiceAgent/releases) page.
|
||||
|
||||
> **Linux users**: Linux builds are **not** attached to GitHub Releases. Download
|
||||
> them from the [Jenkins job](https://jenkins.xiaozhou233.cn/job/JuiceAgent/)
|
||||
> instead — see [Linux Support](#linux-support).
|
||||
|
||||
Extract the ZIP file to a directory:
|
||||
|
||||
- YourDir
|
||||
@@ -120,17 +145,15 @@ Extract the ZIP file to a directory:
|
||||
|
||||
```toml
|
||||
[JuiceAgent]
|
||||
Version = 1
|
||||
|
||||
[JuiceAgent.Loader]
|
||||
# Path to libagent.dll, default is "./libagent.dll"
|
||||
Version = 2
|
||||
# Path to libagent.dll, default is "./libagent.dll" (relative to the runtime directory)
|
||||
JuiceAgentNativeLibraryPath = ""
|
||||
|
||||
[JuiceAgent.Modules]
|
||||
|
||||
[JuiceAgent.Modules.JarLoader]
|
||||
[JarLoader]
|
||||
Enabled = true
|
||||
# Directory containing dependency JARs to load first
|
||||
# Mode: BuiltIn | CustomJar
|
||||
Mode = "BuiltIn"
|
||||
# Directory containing dependency JARs to load first (BuiltIn mode)
|
||||
InjectionDir = "./injection"
|
||||
# Path to the JAR file to be loaded
|
||||
JarPath = "./MyCustomJar.jar"
|
||||
@@ -140,7 +163,7 @@ EntryClass = "Example.Main"
|
||||
EntryMethod = "run"
|
||||
```
|
||||
|
||||
Save the file as `config.toml` in the same directory (the runtime directory). Relative paths are resolved against the runtime directory.
|
||||
Save the file as `config.toml` in the same directory (the runtime directory). Relative paths are resolved against the runtime directory. See [Configuration](docs/config.md) for the complete reference.
|
||||
|
||||
- YourDir
|
||||
- **config.toml**
|
||||
@@ -170,30 +193,79 @@ You can also pass arguments directly: `injector.exe <pid> <libloader.dll path> [
|
||||
|
||||
#### Method B: Use JNI to call `inject`
|
||||
|
||||
Create `cn/xiaozhou233/juiceagent/injector/InjectorNative.java` in your project:
|
||||
|
||||
```java
|
||||
package cn.xiaozhou233.juiceagent.injector;
|
||||
|
||||
public class InjectorNative {
|
||||
public native boolean inject(int pid, String path);
|
||||
public native boolean inject(int pid, String path, String configDir);
|
||||
}
|
||||
```
|
||||
|
||||
Example:
|
||||
|
||||
```java
|
||||
System.load("<path-to-libinject.dll>");
|
||||
InjectorNative injectorNative = new InjectorNative();
|
||||
|
||||
injectorNative.inject(<pid>, "<path-to-libloader.dll>", "<path-to-config-directory>");
|
||||
```
|
||||
See [Inject](docs/Inject.md)
|
||||
|
||||
### 5. Done
|
||||
|
||||
The target JVM will load the specified JAR and execute the specified entry class and method.
|
||||
|
||||
## Linux Support
|
||||
|
||||
JuiceAgent also works on Linux x64. Instead of reflective DLL injection, the
|
||||
Linux injector uses `ptrace` to attach to the target process and then performs a
|
||||
**remote `dlopen`**: it saves the thread state, makes the target call
|
||||
`dlopen("libloader.so", RTLD_NOW)`, restores the state and detaches. The JVM
|
||||
therefore loads the loader itself — no `LD_PRELOAD` and no `-javaagent` — and the
|
||||
rest of the pipeline is identical to Windows.
|
||||
|
||||
### Download
|
||||
|
||||
Linux builds are **not** published on GitHub Releases. Download the latest
|
||||
successful build from the Jenkins job:
|
||||
|
||||
```text
|
||||
https://jenkins.xiaozhou233.cn/job/JuiceAgent/
|
||||
```
|
||||
|
||||
Grab the build artifact (`JuiceAgent_vX.Y.Z_x64_linux.tar.gz`) from the most
|
||||
recent successful build, then extract `injector`, `libloader.so` and
|
||||
`libagent.so` from it.
|
||||
|
||||
### Components
|
||||
|
||||
- `libloader.so` — loaded into the target JVM, starts from an ELF constructor.
|
||||
- `libagent.so` — the JVMTI agent. This is the default
|
||||
`JuiceAgentNativeLibraryPath` on Linux (instead of `libagent.dll`).
|
||||
- `injector` — attaches to the target PID and performs the remote `dlopen`.
|
||||
|
||||
### Configuration location
|
||||
|
||||
On Linux the loader does **not** look in the current working directory. It
|
||||
resolves the runtime directory in this order:
|
||||
|
||||
1. `JuiceAgent_ConfigPath` — if the environment variable is set and non-empty, it
|
||||
is used as-is.
|
||||
2. `$HOME/.juiceagent` — the default; created automatically if it does not exist.
|
||||
|
||||
`config.toml` is read from that directory. The schema is identical to Windows
|
||||
and relative paths (`JarPath`, `InjectionDir`, ...) are resolved against it, so a
|
||||
typical layout is:
|
||||
|
||||
```text
|
||||
~/.juiceagent/
|
||||
├── config.toml
|
||||
├── MyCustomJar.jar
|
||||
└── injection/
|
||||
└── Dependencies.jar
|
||||
```
|
||||
|
||||
To point the loader at another directory:
|
||||
|
||||
```bash
|
||||
export JuiceAgent_ConfigPath=/opt/juiceagent
|
||||
```
|
||||
|
||||
### Requirements
|
||||
|
||||
- Run the injector as the same user as the target JVM (or as `root`), and make
|
||||
sure `ptrace` is permitted. If injection fails with `EPERM`, check
|
||||
`/proc/sys/kernel/yama/ptrace_scope`.
|
||||
- The target JVM and the loader must both be x64.
|
||||
|
||||
> **Note**: The Linux injector binary is not open source yet. The `injector`
|
||||
> target in this repository is a placeholder that only prints a notice; the
|
||||
> loader and the agent are fully open source and build from this tree.
|
||||
|
||||
## JuiceAgent API
|
||||
|
||||
The following native functions are exposed to Java through the `cn.xiaozhou233.juiceagent.api.JuiceAgent` class (see the [JuiceAgent-API](https://github.com/xiaozhou233/JuiceAgent-API) project for the Java API definition):
|
||||
@@ -214,6 +286,7 @@ The following native functions are exposed to Java through the `cn.xiaozhou233.j
|
||||
|
||||
## Examples
|
||||
|
||||
- `examples/inject-via-java-api` — injects JuiceAgent into a running JVM through the Java API (JNI), without needing `injector.exe`.
|
||||
- `examples/load-via-injector-exe` — loads a JAR into a target JVM via `injector.exe` and runs an entry point.
|
||||
- `examples/retransform-class` — demonstrates class retransformation with a target JVM and a modified copy of the class.
|
||||
|
||||
@@ -222,7 +295,7 @@ The following native functions are exposed to Java through the `cn.xiaozhou233.j
|
||||
### Requirements
|
||||
|
||||
- Java 8+
|
||||
- MinGW
|
||||
- MinGW-w64 (Windows) or GCC/Clang (Linux)
|
||||
- CMake 3.15+
|
||||
- Ninja
|
||||
|
||||
@@ -246,7 +319,9 @@ cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=Release
|
||||
cmake --build build
|
||||
```
|
||||
|
||||
The generated binaries will be placed in `build/bin`.
|
||||
The generated binaries will be placed in `build/bin`. On Linux this produces
|
||||
`libloader.so`, `libagent.so` and `injector`; on Windows the `.dll` / `.exe`
|
||||
equivalents.
|
||||
|
||||
## Full Disclaimer
|
||||
|
||||
|
||||
+82
-35
@@ -6,6 +6,11 @@
|
||||
|
||||
JuiceAgent 是一个基于 JVMTI 的高级注入框架,用于运行时 JAR 加载、字节码变换和运行时 JVM 插桩。它可以在 `DisableAttachMechanism=true` 的情况下注入到正在运行的 JVM 进程中,无需 `-javaagent` 启动参数,也无需使用 attach 机制。
|
||||
|
||||
目前支持两个平台:
|
||||
|
||||
- **Windows x64**——反射式 DLL 注入(`injector.exe` + `libinject.dll`)。
|
||||
- **Linux x64**——通过 `ptrace` 附加目标进程,再用一次远程 `dlopen` 让目标 JVM 自己加载 `libloader.so`。
|
||||
|
||||
**警告**:本项目仍处于实验阶段,不建议用于生产环境。使用风险自负。
|
||||
|
||||
> **提示**:部分杀毒软件可能将 JuiceAgent 误报为恶意软件。详情见[杀毒软件误报说明](docs/Antivirus-False-Positive.md)。
|
||||
@@ -16,6 +21,9 @@ JuiceAgent 是一个基于 JVMTI 的高级注入框架,用于运行时 JAR 加
|
||||
- Discord:[JuiceDev](https://discord.gg/AQTnUyWNNJ)
|
||||
- QQ 群:1103504356
|
||||
|
||||
> **不知道该怎么用?** 不必手动折腾注入流程:用支持读写文件和执行命令的 AI Agent(例如 OpenCode)即可。在本仓库中打开 Agent,让它先阅读 [`QuickStartForAgents.md`](QuickStartForAgents.md) 并照着执行——该文档覆盖了完整流程(环境检查、需求确认、`config.toml`、注入与验证),并且是专门写给 Agent 执行的。你只需要告诉它:
|
||||
> "请阅读 `QuickStartForAgents.md`,并照着里面的步骤把我的 JAR 注入到目标 JVM。"
|
||||
|
||||

|
||||

|
||||

|
||||
@@ -26,7 +34,7 @@ JuiceAgent 是一个基于 JVMTI 的高级注入框架,用于运行时 JAR 加
|
||||

|
||||

|
||||

|
||||

|
||||

|
||||
|
||||

|
||||

|
||||
@@ -41,6 +49,7 @@ JuiceAgent 是一个基于 JVMTI 的高级注入框架,用于运行时 JAR 加
|
||||
- [特性](#特性)
|
||||
- [项目结构](#项目结构)
|
||||
- [快速开始](#快速开始)
|
||||
- [Linux 支持](#linux-支持)
|
||||
- [JuiceAgent API](#juiceagent-api)
|
||||
- [示例](#示例)
|
||||
- [如何构建](#如何构建)
|
||||
@@ -70,6 +79,8 @@ JuiceAgent 是 [JuiceAgent-API](https://github.com/xiaozhou233/JuiceAgent-API)
|
||||
|
||||
`JuiceAgent-API` jar 内嵌于原生二进制中,无需单独下载。
|
||||
|
||||
Linux 上的流程与此相同,只有注入这一步不同。注入器通过 `ptrace` 附加到目标进程,保存线程状态,发起一次远程 `dlopen` 让 JVM 在自身进程内加载 `libloader.so`(无需 `LD_PRELOAD`,也无需 `-javaagent`)。随后 `libloader.so` 从 ELF constructor 启动,解析运行时目录(`JuiceAgent_ConfigPath`,默认 `$HOME/.juiceagent`),之后与 Windows 加载器完全一致地驱动 agent。详见 [Linux 支持](#linux-支持)。
|
||||
|
||||
## 特性
|
||||
|
||||
- 将外部 JAR 加载到 Bootstrap 或 System ClassLoader
|
||||
@@ -84,10 +95,10 @@ JuiceAgent 是 [JuiceAgent-API](https://github.com/xiaozhou233/JuiceAgent-API)
|
||||
|
||||
## 项目结构
|
||||
|
||||
- `src/libloader` — `libloader.dll`。注入到目标 JVM,附加 JVM、解析 `config.toml`、注入内嵌的 `JuiceAgent-API` 并引导 agent。
|
||||
- `src/libagent` — `libagent.dll`。JVMTI agent。注册回调(例如 `ClassFileLoadHook`)并实现 `JuiceAgent-API` 的原生侧。
|
||||
- `src/injector` — `injector.exe`。命令行驱动,加载 `libinject.dll` 并将 `libloader.dll` 注入到目标进程。
|
||||
- `src/libinject` — `libinject.dll`。反射式 DLL 注入器,导出原生 `inject` 函数并提供 JNI 绑定(`cn.xiaozhou233.juiceagent.injector.InjectorNative`)。
|
||||
- `src/libloader` — `libloader.dll`(Windows)/ `libloader.so`(Linux)。注入到目标 JVM,附加 JVM、解析 `config.toml`、注入内嵌的 `JuiceAgent-API` 并引导 agent。
|
||||
- `src/libagent` — `libagent.dll`(Windows)/ `libagent.so`(Linux)。JVMTI agent。注册回调(例如 `ClassFileLoadHook`)并实现 `JuiceAgent-API` 的原生侧。
|
||||
- `src/injector` — `injector.exe`(Windows)/ `injector`(Linux)。命令行驱动,将加载器注入到目标进程。
|
||||
- `src/libinject` — `libinject.dll`(仅 Windows)。反射式 DLL 注入器,导出原生 `inject` 函数并提供 JNI 绑定(`cn.xiaozhou233.juiceagent.injector.InjectorNative`)。
|
||||
|
||||
## 快速开始
|
||||
|
||||
@@ -97,6 +108,10 @@ JuiceAgent 是 [JuiceAgent-API](https://github.com/xiaozhou233/JuiceAgent-API)
|
||||
|
||||
从 [releases](https://github.com/xiaozhou233/JuiceAgent/releases) 页面下载 `JuiceAgent_vx.x.x_x64.zip`。
|
||||
|
||||
> **Linux 用户注意**:Linux 构建**不会**发布在 GitHub Release 上,请从
|
||||
> [Jenkins](https://jenkins.xiaozhou233.cn/job/JuiceAgent/) 下载,详见
|
||||
> [Linux 支持](#linux-支持)。
|
||||
|
||||
解压 ZIP 到一个目录:
|
||||
|
||||
- YourDir
|
||||
@@ -121,17 +136,15 @@ JuiceAgent 是 [JuiceAgent-API](https://github.com/xiaozhou233/JuiceAgent-API)
|
||||
|
||||
```toml
|
||||
[JuiceAgent]
|
||||
Version = 1
|
||||
|
||||
[JuiceAgent.Loader]
|
||||
# libagent.dll 的路径,默认是 "./libagent.dll"
|
||||
Version = 2
|
||||
# libagent.dll 的路径,默认是 "./libagent.dll"(相对于运行时目录)
|
||||
JuiceAgentNativeLibraryPath = ""
|
||||
|
||||
[JuiceAgent.Modules]
|
||||
|
||||
[JuiceAgent.Modules.JarLoader]
|
||||
[JarLoader]
|
||||
Enabled = true
|
||||
# 需要优先加载的依赖 JAR 所在目录
|
||||
# Mode:BuiltIn | CustomJar
|
||||
Mode = "BuiltIn"
|
||||
# 需要优先加载的依赖 JAR 所在目录(BuiltIn 模式)
|
||||
InjectionDir = "./injection"
|
||||
# 要加载的 JAR 文件路径
|
||||
JarPath = "./MyCustomJar.jar"
|
||||
@@ -141,7 +154,7 @@ EntryClass = "Example.Main"
|
||||
EntryMethod = "run"
|
||||
```
|
||||
|
||||
将文件保存为 `config.toml` 并放在同一目录(运行时目录)中。相对路径以运行时目录为基准解析。
|
||||
将文件保存为 `config.toml` 并放在同一目录(运行时目录)中。相对路径以运行时目录为基准解析。完整配置说明见 [Configuration](docs/config.md)。
|
||||
|
||||
- YourDir
|
||||
- **config.toml**
|
||||
@@ -171,30 +184,63 @@ Input PID:
|
||||
|
||||
#### 方法 B:通过 JNI 调用 `inject`
|
||||
|
||||
在你的项目中创建 `cn/xiaozhou233/juiceagent/injector/InjectorNative.java`:
|
||||
|
||||
```java
|
||||
package cn.xiaozhou233.juiceagent.injector;
|
||||
|
||||
public class InjectorNative {
|
||||
public native boolean inject(int pid, String path);
|
||||
public native boolean inject(int pid, String path, String configDir);
|
||||
}
|
||||
```
|
||||
|
||||
示例:
|
||||
|
||||
```java
|
||||
System.load("<libinject.dll 的路径>");
|
||||
InjectorNative injectorNative = new InjectorNative();
|
||||
|
||||
injectorNative.inject(<pid>, "<libloader.dll 的路径>", "<配置文件所在目录>");
|
||||
```
|
||||
看 [Inject](docs/Inject.md)
|
||||
|
||||
### 5. 完成
|
||||
|
||||
目标 JVM 将加载指定的 JAR 并执行指定的入口类和入口方法。
|
||||
|
||||
## Linux 支持
|
||||
|
||||
JuiceAgent 同样支持 Linux x64。与反射式 DLL 注入不同,Linux 注入器使用 `ptrace` 附加目标进程,然后执行一次**远程 `dlopen`**:保存线程状态,让目标进程调用 `dlopen("libloader.so", RTLD_NOW)`,恢复状态并 detach。这样由 JVM 自己加载加载器——无需 `LD_PRELOAD`,也无需 `-javaagent`——其后的流程与 Windows 完全一致。
|
||||
|
||||
### 下载
|
||||
|
||||
Linux 构建**不会**发布在 GitHub Release 上,请从 Jenkins 任务下载最新一次成功的构建:
|
||||
|
||||
```text
|
||||
https://jenkins.xiaozhou233.cn/job/JuiceAgent/
|
||||
```
|
||||
|
||||
选择最近一次成功的构建,下载其产物(`JuiceAgent_vX.Y.Z_x64_linux.tar.gz`),从中解出
|
||||
`injector`、`libloader.so` 和 `libagent.so`。
|
||||
|
||||
### 组件
|
||||
|
||||
- `libloader.so` —— 加载进目标 JVM,从 ELF constructor 启动。
|
||||
- `libagent.so` —— JVMTI agent。在 Linux 上它是 `JuiceAgentNativeLibraryPath` 的默认值(而不是 `libagent.dll`)。
|
||||
- `injector` —— 附加到目标 PID 并执行远程 `dlopen`。
|
||||
|
||||
### 配置位置
|
||||
|
||||
Linux 上加载器**不会**在当前工作目录中查找配置,而是按以下顺序确定运行时目录:
|
||||
|
||||
1. `JuiceAgent_ConfigPath` —— 环境变量存在且非空时直接使用。
|
||||
2. `$HOME/.juiceagent` —— 默认值,目录不存在时会自动创建。
|
||||
|
||||
`config.toml` 从该目录读取,配置结构(schema)与 Windows 完全一致,相对路径(`JarPath`、`InjectionDir` 等)也以该目录为基准解析。典型目录结构:
|
||||
|
||||
```text
|
||||
~/.juiceagent/
|
||||
├── config.toml
|
||||
├── MyCustomJar.jar
|
||||
└── injection/
|
||||
└── Dependencies.jar
|
||||
```
|
||||
|
||||
如需指定其他目录:
|
||||
|
||||
```bash
|
||||
export JuiceAgent_ConfigPath=/opt/juiceagent
|
||||
```
|
||||
|
||||
### 环境要求
|
||||
|
||||
- 以与目标 JVM 相同的用户(或 `root`)运行注入器,并确保允许 `ptrace`。如果注入失败并返回 `EPERM`,请检查 `/proc/sys/kernel/yama/ptrace_scope`。
|
||||
- 目标 JVM 与加载器都必须是 x64。
|
||||
|
||||
> **注意**:Linux 注入器二进制目前尚未开源。本仓库中的 `injector` 目标只是一个占位程序,仅打印提示信息;加载器与 agent 完全开源,可直接从本仓库构建。
|
||||
|
||||
## JuiceAgent API
|
||||
|
||||
以下原生函数通过 `cn.xiaozhou233.juiceagent.api.JuiceAgent` 类暴露给 Java(Java API 定义见 [JuiceAgent-API](https://github.com/xiaozhou233/JuiceAgent-API) 项目):
|
||||
@@ -215,6 +261,7 @@ injectorNative.inject(<pid>, "<libloader.dll 的路径>", "<配置文件所在
|
||||
|
||||
## 示例
|
||||
|
||||
- `examples/inject-via-java-api` — 通过 Java API(JNI)将 JuiceAgent 注入到正在运行的 JVM,无需 `injector.exe`。
|
||||
- `examples/load-via-injector-exe` — 通过 `injector.exe` 将 JAR 加载到目标 JVM 并运行入口点。
|
||||
- `examples/retransform-class` — 演示使用目标 JVM 和修改后的类副本进行类重变换。
|
||||
|
||||
@@ -223,7 +270,7 @@ injectorNative.inject(<pid>, "<libloader.dll 的路径>", "<配置文件所在
|
||||
### 环境要求
|
||||
|
||||
- Java 8+
|
||||
- MinGW
|
||||
- MinGW-w64(Windows)或 GCC/Clang(Linux)
|
||||
- CMake 3.15+
|
||||
- Ninja
|
||||
|
||||
@@ -247,7 +294,7 @@ cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=Release
|
||||
cmake --build build
|
||||
```
|
||||
|
||||
生成的二进制文件将放在 `build/bin` 中。
|
||||
生成的二进制文件将放在 `build/bin` 中。Linux 下会生成 `libloader.so`、`libagent.so` 和 `injector`;Windows 下为对应的 `.dll` / `.exe`。
|
||||
|
||||
## 完整免责声明
|
||||
|
||||
|
||||
+3
-1
@@ -1 +1,3 @@
|
||||
Version 4.1.1
|
||||
Major=5
|
||||
Minor=0
|
||||
Patch=1
|
||||
@@ -0,0 +1,26 @@
|
||||
# Inject Method
|
||||
|
||||
## Method A: Use `injector.exe`
|
||||
Run `injector.exe` from `YourDir`.
|
||||
|
||||
```text
|
||||
<jps output>
|
||||
Input PID:
|
||||
```
|
||||
|
||||
Enter the PID of the target JVM process and press Enter.
|
||||
|
||||
## Method B: Use JNI to call `inject`
|
||||
Download the JuiceAgent-JavaInjector-x.x-xxxx.jar from [here](https://github.com/xiaozhou233/JuiceAgent-JavaInjector/releases).
|
||||
|
||||
Add JuiceAgent-JavaInjector-x.x-xxxx.jar to your classpath.
|
||||
|
||||
Example:
|
||||
|
||||
```java
|
||||
import cn.xiaozhou233.juiceagent.injector.Injector;
|
||||
|
||||
System.load("<path-to-libinject>");
|
||||
|
||||
Injector.inject(<pid>, "<path-to-libloader>", "<path-to-config-directory>");
|
||||
```
|
||||
+25
-15
@@ -1,24 +1,34 @@
|
||||
# Advanced
|
||||
|
||||
## Load Custom API / Directly Load Jar
|
||||
WARN: This feature didn't implement yet.
|
||||
|
||||
### Describe
|
||||
JuiceAgent loads custom JARs through the following workflow:
|
||||
JuiceAgent runs in **BuiltIn** mode by default: `libloader` registers the embedded
|
||||
JuiceAgent-API jar, the agent bootstraps it, and the JarLoader module loads your JAR
|
||||
and invokes its entry method.
|
||||
|
||||
1. Inject `libloader` into the target process.
|
||||
2. Load **JuiceAgent-API** and execute its initialization entry point.
|
||||
3. Invoke the `JarLoader` from **JuiceAgent-API** to load the specified JAR into the JVM.
|
||||
If you don't need JuiceAgent-API — for example you want to provide your own bootstrap
|
||||
and call an arbitrary class/method — set `JarLoader.Mode` to **`CustomJar`**:
|
||||
|
||||
The second step is fully customizable. You can replace **JuiceAgent-API** with your own JAR and call any class method you specify.
|
||||
```toml
|
||||
[JuiceAgent]
|
||||
Version = 2
|
||||
|
||||
### Configuration
|
||||
[JarLoader]
|
||||
Mode = "CustomJar"
|
||||
JarPath = "./my-agent.jar"
|
||||
EntryClass = "com.example.MyBootstrap"
|
||||
EntryMethod = "start"
|
||||
```
|
||||
|
||||
Set the following environment variables before launching `libloader`:
|
||||
Workflow in `CustomJar` mode:
|
||||
|
||||
```bat
|
||||
set JUICEAGENT_API_ENABLED=true
|
||||
set JUICEAGENT_API_JAR=<path-to-your-jar>
|
||||
set JUICEAGENT_API_CLASS=<target-class-name>
|
||||
set JUICEAGENT_API_METHOD=<target-method-name>
|
||||
```
|
||||
1. `libloader` attaches to the target JVM and reads `config.toml`.
|
||||
2. It adds `JarPath` to the system class loader search path. JuiceAgent-API is **not** loaded.
|
||||
3. It invokes `EntryClass.EntryMethod`.
|
||||
|
||||
`EntryMethod` must be a `public static void` method that takes no arguments.
|
||||
|
||||
> `JarLoader.Enabled` and `JarLoader.InjectionDir` only apply to `BuiltIn` mode; they are
|
||||
> ignored in `CustomJar` mode.
|
||||
|
||||
See [Configuration](config.md) for the complete list of keys.
|
||||
@@ -0,0 +1,65 @@
|
||||
# Configuration (`config.toml`)
|
||||
|
||||
JuiceAgent reads a single `config.toml` from the **runtime directory** (the directory
|
||||
passed to the injector / loader; the current working directory is used when none is
|
||||
given). Paths that start with `./` are resolved against the runtime directory;
|
||||
absolute paths are used as-is.
|
||||
|
||||
The current schema version is **2**. `JuiceAgent.Version` must match the version
|
||||
expected by the binaries, otherwise the loader stops with a version mismatch error.
|
||||
|
||||
## Example
|
||||
|
||||
```toml
|
||||
[JuiceAgent]
|
||||
Version = 2
|
||||
JuiceAgentNativeLibraryPath = ""
|
||||
|
||||
[JarLoader]
|
||||
Enabled = true
|
||||
Mode = "BuiltIn"
|
||||
InjectionDir = "./injection"
|
||||
JarPath = "./MyCustomJar.jar"
|
||||
EntryClass = "Example.Main"
|
||||
EntryMethod = "run"
|
||||
```
|
||||
|
||||
## `[JuiceAgent]`
|
||||
|
||||
| Key | Type | Required | Default | Description |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| `Version` | integer | yes | — | Configuration schema version. Must be `2`. |
|
||||
| `JuiceAgentNativeLibraryPath` | string (path) | no | `./libagent.dll` | Path to `libagent.dll`, loaded by the bootstrap after injection. |
|
||||
|
||||
## `[JarLoader]`
|
||||
|
||||
| Key | Type | Required | Default | Description |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| `Mode` | string | yes | — | How the target JAR is registered: `BuiltIn` or `CustomJar`. |
|
||||
| `Enabled` | boolean | no | `false` | Run the JarLoader module after the agent is initialized (`BuiltIn` mode only). When `false`, no JAR is loaded and no entry method is invoked. |
|
||||
| `InjectionDir` | string (path) | no | `./injection` | Directory of dependency JARs loaded before the main JAR (`BuiltIn` mode). |
|
||||
| `JarPath` | string (path) | see below | `./Entry.jar` (`BuiltIn`) | The JAR to load. |
|
||||
| `EntryClass` | string | see below | `Example.Main` (`BuiltIn`) | Entry class to invoke after loading the JAR. |
|
||||
| `EntryMethod` | string | see below | `start` (`BuiltIn`) | Entry method, must be a `public static void` method with no parameters. |
|
||||
|
||||
> In `CustomJar` mode, `JarPath`, `EntryClass` and `EntryMethod` are required (there are
|
||||
> no defaults); `Enabled` and `InjectionDir` are not used.
|
||||
|
||||
## Modes
|
||||
|
||||
### `BuiltIn` (recommended)
|
||||
|
||||
1. `libloader` extracts the embedded **JuiceAgent-API** jar and adds it to the system class loader.
|
||||
2. The agent bootstraps JuiceAgent-API (`JuiceAgentBootstrap.start`).
|
||||
3. If `Enabled = true`, the JarLoader module loads every `*.jar` from `InjectionDir`, then loads `JarPath`, and invokes `EntryClass.EntryMethod`.
|
||||
|
||||
This is the mode used by most users: keep JuiceAgent-API and just supply the JAR and
|
||||
entry point to run.
|
||||
|
||||
### `CustomJar`
|
||||
|
||||
1. `libloader` adds `JarPath` itself to the system class loader. **JuiceAgent-API is not used.**
|
||||
2. It invokes `EntryClass.EntryMethod` directly.
|
||||
|
||||
Use this when you want to bring your own bootstrap and call an arbitrary class/method.
|
||||
See [Advanced](advanced.md#load-custom-api--directly-load-jar) for details.
|
||||
@@ -0,0 +1,143 @@
|
||||
# Changelog / 更新日志
|
||||
|
||||
本文件记录 JuiceAgent 的版本变更。更早的版本请见 [GitHub Releases](https://github.com/xiaozhou233/JuiceAgent/releases)。
|
||||
|
||||
This file records notable changes to JuiceAgent. For older releases, see [GitHub Releases](https://github.com/xiaozhou233/JuiceAgent/releases).
|
||||
|
||||
## 中文
|
||||
|
||||
### [5.0.1] - 2026-10-16
|
||||
|
||||
#### 🐛 修复
|
||||
|
||||
- 修复配置错误导致目标 JVM 崩溃:`libloader.dll` 是反射加载的,其展开表未被登记,C++ 异常在其中既无法 unwind 也无法捕获。现改为配置读取非抛出 + 解析走无异常模式,并以 `-fno-exceptions` 编译 libloader,任何会抛异常的代码在编译期即失败。
|
||||
|
||||
#### ✨ 新功能
|
||||
|
||||
- 事件总线新增 `subscribeFront` / `listenFront`(监听者顺序能力)。
|
||||
|
||||
#### 🔧 内部改动
|
||||
|
||||
- 用约 60 行类型安全事件总线替换 `eventpp`(移除 23 个 in-tree 头文件,约 144 KB)。
|
||||
- 移除无引用的 `MethodEntry` / `MethodExit` 事件定义。
|
||||
|
||||
#### 📝 文档
|
||||
|
||||
- 新增 `docs/config.md` 与 `docs/update/`;重写 `docs/advanced.md`;README 配置示例升级到 v2。
|
||||
|
||||
#### 🔁 CI
|
||||
|
||||
- 新增 GitHub Actions 工作流(构建 + 集成测试 + 打包 + 上传 artifact)与 `tests/run-tests.ps1`。
|
||||
- 构建改为静态链接 C/C++ 运行时。
|
||||
|
||||
### [5.0.0] - 2026-10-15
|
||||
|
||||
#### ⚠️ 破坏性变更
|
||||
|
||||
- 配置 schema 由 v1 升级到 v2(`CONFIG_VERSION = 2`):旧配置会被版本校验拒绝,需按 [v5.0.0 发布说明](v5.0.0.md) 迁移。
|
||||
|
||||
#### ✨ 新功能
|
||||
|
||||
- 新增 `JarLoader.Mode`:`BuiltIn`(内置 JuiceAgent-API)与 `CustomJar`(直接加载自定义 JAR)两种加载模式。
|
||||
- 新增 `JarLoader.Enabled` 开关,可在 `BuiltIn` 模式下关闭 JarLoader 模块。
|
||||
- 新增配置解析与访问的错误日志。
|
||||
|
||||
#### 🐛 修复
|
||||
|
||||
- 自定义 JAR 入口类名规范化(`.` → `/`),修复 `NoClassDefFoundError`。
|
||||
- `tests/copy-bin.bat` 在被占用时会静默失败的问题。
|
||||
- `GetClassBytesByName` 集成测试未先加载目标类的问题。
|
||||
|
||||
#### 🔧 内部改动
|
||||
|
||||
- TOML 解析器由 `toml11` 迁移到 `toml++`。
|
||||
- 移除未使用的 `LoaderConfig` 相关辅助函数。
|
||||
|
||||
#### 📝 文档
|
||||
|
||||
- 新增 `docs/config.md`(v2 配置参考)。
|
||||
- 重写 `docs/advanced.md`;README 与示例文档升级到 v2。
|
||||
|
||||
### [4.1.2] - 2026-10-11
|
||||
|
||||
#### ✨ 新功能
|
||||
|
||||
- 新增基于版本的打包脚本(`script/package.bat` + `script/package.cmake`)。
|
||||
- `Version.txt` 改为 `Major` / `Minor` / `Patch` 结构化格式。
|
||||
|
||||
#### 🐛 修复
|
||||
|
||||
- 修复 `getClassBytesByName` 在部分环境下无法获取类的问题(改用 JVMTI 的 `findLoadedClass`)。
|
||||
|
||||
#### 📝 文档
|
||||
|
||||
- 新增 `docs/Inject.md`;修正文档路径。
|
||||
|
||||
## English
|
||||
|
||||
### [5.0.1] - 2026-10-16
|
||||
|
||||
#### 🐛 Fixes
|
||||
|
||||
- Fix a config error crashing the target JVM: `libloader.dll` is reflectively loaded, so its unwind tables are never registered and a C++ exception cannot be unwound or caught there. Config reads are now non-throwing, parsing runs in non-throwing mode, and libloader is compiled with `-fno-exceptions` so exception-capable code fails the build.
|
||||
|
||||
#### ✨ Features
|
||||
|
||||
- New `subscribeFront` / `listenFront` listener-ordering support on the event bus.
|
||||
|
||||
#### 🔧 Internal
|
||||
|
||||
- Replace `eventpp` with a ~60-line type-safe event bus (removes 23 in-tree headers, ~144 KB).
|
||||
- Remove the unreferenced `MethodEntry` / `MethodExit` event definitions.
|
||||
|
||||
#### 📝 Docs
|
||||
|
||||
- Add `docs/config.md` and `docs/update/`; rewrite `docs/advanced.md`; update the README config examples to v2.
|
||||
|
||||
#### 🔁 CI
|
||||
|
||||
- Add a GitHub Actions workflow (build + integration tests + package + artifact upload) and `tests/run-tests.ps1`.
|
||||
- Link the C/C++ runtime statically.
|
||||
|
||||
### [5.0.0] - 2026-10-15
|
||||
|
||||
#### ⚠️ Breaking Changes
|
||||
|
||||
- Configuration schema upgraded from v1 to v2 (`CONFIG_VERSION = 2`): older configs are rejected by the version check and must be migrated (see the [v5.0.0 release notes](v5.0.0.md)).
|
||||
|
||||
#### ✨ Features
|
||||
|
||||
- New `JarLoader.Mode`: `BuiltIn` (embedded JuiceAgent-API) and `CustomJar` (load your own JAR directly).
|
||||
- New `JarLoader.Enabled` switch to turn the JarLoader module off in `BuiltIn` mode.
|
||||
- Added logging for config parse and access errors.
|
||||
|
||||
#### 🐛 Fixes
|
||||
|
||||
- Normalize custom-jar entry class names (`.` → `/`), fixing `NoClassDefFoundError`.
|
||||
- `tests/copy-bin.bat` no longer fails silently when a target file is locked.
|
||||
- `GetClassBytesByName` integration test now loads the target class first.
|
||||
|
||||
#### 🔧 Internal
|
||||
|
||||
- Migrate the TOML parser from `toml11` to `toml++`.
|
||||
- Remove the unused `LoaderConfig` helpers.
|
||||
|
||||
#### 📝 Docs
|
||||
|
||||
- Add `docs/config.md` (v2 configuration reference).
|
||||
- Rewrite `docs/advanced.md`; update the READMEs and example guides to v2.
|
||||
|
||||
### [4.1.2] - 2026-10-11
|
||||
|
||||
#### ✨ Features
|
||||
|
||||
- Add a version-based packaging script (`script/package.bat` + `script/package.cmake`).
|
||||
- `Version.txt` now uses a structured `Major` / `Minor` / `Patch` format.
|
||||
|
||||
#### 🐛 Fixes
|
||||
|
||||
- Fix `getClassBytesByName` failing in some environments (use JVMTI `findLoadedClass`).
|
||||
|
||||
#### 📝 Docs
|
||||
|
||||
- Add `docs/Inject.md`; fix documentation paths.
|
||||
@@ -0,0 +1,163 @@
|
||||
# JuiceAgent 5.0.0 Release Notes
|
||||
|
||||
## 中文
|
||||
|
||||
### ⚠️ 破坏性变更
|
||||
|
||||
- **配置文件升级到 v2**:`CONFIG_VERSION` 提升为 `2`。加载器启动时会校验 `JuiceAgent.Version`,版本不匹配将直接拒绝加载,因此旧版 v1 配置必须先迁移。
|
||||
|
||||
v1(不再支持):
|
||||
|
||||
```toml
|
||||
[JuiceAgent]
|
||||
Version = 1
|
||||
|
||||
[JuiceAgent.Loader]
|
||||
JuiceAgentNativeLibraryPath = ""
|
||||
|
||||
[JuiceAgent.Modules]
|
||||
|
||||
[JuiceAgent.Modules.JarLoader]
|
||||
Enabled = true
|
||||
InjectionDir = "./injection"
|
||||
JarPath = "./MyCustomJar.jar"
|
||||
EntryClass = "Example.Main"
|
||||
EntryMethod = "run"
|
||||
```
|
||||
|
||||
v2(当前):
|
||||
|
||||
```toml
|
||||
[JuiceAgent]
|
||||
Version = 2
|
||||
JuiceAgentNativeLibraryPath = ""
|
||||
|
||||
[JarLoader]
|
||||
Enabled = true
|
||||
Mode = "BuiltIn"
|
||||
InjectionDir = "./injection"
|
||||
JarPath = "./MyCustomJar.jar"
|
||||
EntryClass = "Example.Main"
|
||||
EntryMethod = "run"
|
||||
```
|
||||
|
||||
迁移要点:
|
||||
|
||||
- `Version` 由 `1` 改为 `2`。
|
||||
- `JuiceAgentNativeLibraryPath` 由 `[JuiceAgent.Loader]` 移到 `[JuiceAgent]`。
|
||||
- 原 `[JuiceAgent.Modules.JarLoader]` 展平为顶层 `[JarLoader]`。
|
||||
- 新增必填项 `Mode`(`BuiltIn` 或 `CustomJar`)。
|
||||
- 完整说明见 [docs/config.md](../config.md)。
|
||||
|
||||
### ✨ 新功能
|
||||
|
||||
- 新增两种 JAR 加载模式(`JarLoader.Mode`):
|
||||
- `BuiltIn`(推荐):加载器解出内嵌的 JuiceAgent-API jar 并注入系统类加载器,agent 通过 API 引导,再由 JarLoader 模块加载目标 JAR 并调用入口方法。
|
||||
- `CustomJar`:不再使用 JuiceAgent-API,加载器直接把 `JarPath` 加入系统类加载器并调用 `EntryClass.EntryMethod`,便于接入自定义引导。
|
||||
- 新增 `JarLoader.Enabled` 开关(默认 `false`),可在 `BuiltIn` 模式下关闭 JarLoader 模块。
|
||||
- 新增配置解析与访问的错误日志:配置缺失或类型不匹配时会给出明确提示。
|
||||
|
||||
### 🐛 修复
|
||||
|
||||
- 修复自定义 JAR 入口类查找失败:将类名规范化为 JNI 内部形式(`.` → `/`),`FindClass` 现在能正确解析 `Example.Main` 这类 Java 二进制名(修复 `NoClassDefFoundError`)。
|
||||
- 修复集成测试的二进制拷贝脚本 `tests/copy-bin.bat`:改用原生 `COPY /Y`,在目标文件被占用时明确报错,不再静默失败导致测试使用旧二进制。
|
||||
- 修复 `GetClassBytesByName` 集成测试:先加载目标类再按名获取字节码(该 API 只解析已加载的类)。
|
||||
|
||||
### 🔧 内部改动
|
||||
|
||||
- TOML 解析器由 `toml11` 迁移到 `toml++`。
|
||||
- 移除未使用的 `LoaderConfig` / `get_loader_config` / `print_loader_config`(其中仍引用着 v1 的配置键)。
|
||||
|
||||
### 📝 文档
|
||||
|
||||
- 新增 [docs/config.md](../config.md):完整的 v2 配置参考(含两种模式流程与各键默认值)。
|
||||
- 重写 [docs/advanced.md](../advanced.md):改为描述 `JarLoader.Mode = "CustomJar"`,移除已废弃的 `JUICEAGENT_API_*` 环境变量说明。
|
||||
- README(中/英)的 Quick Start 配置示例升级到 v2 并链接 `docs/config.md`;示例列表补充 `inject-via-java-api`。
|
||||
- 同步更新 `examples/inject-via-java-api` 的说明文档(中/英,md/txt)。
|
||||
|
||||
---
|
||||
|
||||
## English
|
||||
|
||||
### ⚠️ Breaking Changes
|
||||
|
||||
- **Configuration upgraded to v2**: `CONFIG_VERSION` is now `2`. The loader validates `JuiceAgent.Version` at startup and refuses to load on a mismatch, so existing v1 configs must be migrated first.
|
||||
|
||||
v1 (no longer supported):
|
||||
|
||||
```toml
|
||||
[JuiceAgent]
|
||||
Version = 1
|
||||
|
||||
[JuiceAgent.Loader]
|
||||
JuiceAgentNativeLibraryPath = ""
|
||||
|
||||
[JuiceAgent.Modules]
|
||||
|
||||
[JuiceAgent.Modules.JarLoader]
|
||||
Enabled = true
|
||||
InjectionDir = "./injection"
|
||||
JarPath = "./MyCustomJar.jar"
|
||||
EntryClass = "Example.Main"
|
||||
EntryMethod = "run"
|
||||
```
|
||||
|
||||
v2 (current):
|
||||
|
||||
```toml
|
||||
[JuiceAgent]
|
||||
Version = 2
|
||||
JuiceAgentNativeLibraryPath = ""
|
||||
|
||||
[JarLoader]
|
||||
Enabled = true
|
||||
Mode = "BuiltIn"
|
||||
InjectionDir = "./injection"
|
||||
JarPath = "./MyCustomJar.jar"
|
||||
EntryClass = "Example.Main"
|
||||
EntryMethod = "run"
|
||||
```
|
||||
|
||||
Migration:
|
||||
|
||||
- `Version`: `1` → `2`.
|
||||
- `JuiceAgentNativeLibraryPath` moved from `[JuiceAgent.Loader]` to `[JuiceAgent]`.
|
||||
- `[JuiceAgent.Modules.JarLoader]` flattened to a top-level `[JarLoader]`.
|
||||
- New required key `Mode` (`BuiltIn` or `CustomJar`).
|
||||
- Full reference: [docs/config.md](../config.md).
|
||||
|
||||
### ✨ Features
|
||||
|
||||
- Two JAR loading modes (`JarLoader.Mode`):
|
||||
- `BuiltIn` (recommended): the loader extracts the embedded JuiceAgent-API jar and adds it to the system class loader, the agent bootstraps it, and the JarLoader module loads the target JAR and invokes its entry method.
|
||||
- `CustomJar`: JuiceAgent-API is not used; the loader adds `JarPath` to the system class loader and invokes `EntryClass.EntryMethod`, so you can plug in your own bootstrap.
|
||||
- New `JarLoader.Enabled` switch (default `false`) to turn the JarLoader module off in `BuiltIn` mode.
|
||||
- New logging for config parse and access errors, with clear messages when a key is missing or has the wrong type.
|
||||
|
||||
### 🐛 Fixes
|
||||
|
||||
- Fix entry class lookup for custom jars: class names are normalized to the JNI internal form (`.` → `/`) so `FindClass` resolves Java binary names like `Example.Main` (fixes `NoClassDefFoundError`).
|
||||
- Fix the integration test helper `tests/copy-bin.bat`: it now uses native `COPY /Y` and reports a clear error when a target file is locked, instead of failing silently and testing against stale binaries.
|
||||
- Fix the `GetClassBytesByName` integration test: load the target class before looking it up by name (the API only resolves already-loaded classes).
|
||||
|
||||
### 🔧 Internal
|
||||
|
||||
- Migrate the TOML parser from `toml11` to `toml++`.
|
||||
- Remove the unused `LoaderConfig` / `get_loader_config` / `print_loader_config` (which still referenced a v1 config key).
|
||||
|
||||
### 📝 Docs
|
||||
|
||||
- Add [docs/config.md](../config.md): the complete v2 configuration reference (mode workflows and key defaults).
|
||||
- Rewrite [docs/advanced.md](../advanced.md) around `JarLoader.Mode = "CustomJar"`, dropping the removed `JUICEAGENT_API_*` environment variables.
|
||||
- Update the Quick Start config example in both READMEs to v2 and link `docs/config.md`; add `inject-via-java-api` to the examples list.
|
||||
- Update the `examples/inject-via-java-api` guides (EN/ZH, md/txt).
|
||||
|
||||
---
|
||||
|
||||
如果您在使用过程中遇到问题,可以加入我们的QQ/Discord群组
|
||||
If you encounter any issues during use, you can join our QQ/Discord group
|
||||
|
||||
Discord: [JuiceDev](https://discord.gg/AQTnUyWNNJ)
|
||||
QQ群: 1103504356
|
||||
|
||||
**Full Changelog**: https://github.com/xiaozhou233/JuiceAgent/compare/v4.1.2...v5.0.0
|
||||
@@ -0,0 +1,77 @@
|
||||
# JuiceAgent 5.0.1 Release Notes
|
||||
|
||||
## 中文
|
||||
|
||||
### 🐛 修复
|
||||
|
||||
- **修复配置错误导致目标 JVM 崩溃**:当 `config.toml` 缺少必填项(例如 `JarLoader.Mode`)或语法不合法时,被注入的目标 JVM 会以 `EXCEPTION_ILLEGAL_INSTRUCTION` 崩溃。
|
||||
|
||||
根因是 `libloader.dll` 采用**反射加载(手动映射)**,其展开表(unwind tables)不会被系统登记,因此在其中抛出的 C++ 异常**既无法 unwind 也无法被 catch**——`try/catch` 在这里是无效的。修复方式:
|
||||
|
||||
- 配置读取全部改为**非抛出**:缺 key / 类型不符只记日志并**提前返回**,报错精确到具体 key;
|
||||
- 配置解析在**无异常模式**下进行(`toml::parse_result`),畸形 TOML 也只报错、不崩;
|
||||
- `libloader` 目标以 **`-fno-exceptions`** 编译,以后任何会抛异常的代码都会在**编译期**失败。
|
||||
|
||||
### ✨ 新功能
|
||||
|
||||
- 事件总线新增 `subscribeFront` / `listenFront`:可将监听者插入队首优先执行(为后续 transformer 管线预留的顺序能力)。
|
||||
|
||||
### 🔧 内部改动
|
||||
|
||||
- 用约 60 行的**类型安全**事件总线替换第三方库 `eventpp`:监听者按事件类型注册与调用,不再有 `const void*` 强转;同时移除 in-tree 的 eventpp 头文件(23 个文件,约 144 KB)及其 license。
|
||||
- 移除无引用的 `MethodEntry` / `MethodExit` 事件定义。
|
||||
|
||||
### 📝 文档
|
||||
|
||||
- 新增 [docs/config.md](../config.md)(v2 配置完整参考)与 [docs/update/](../update/)(发布说明 + CHANGELOG)。
|
||||
- 重写 [docs/advanced.md](../advanced.md);README(中/英)配置示例升级到 v2。
|
||||
|
||||
### 🔁 CI
|
||||
|
||||
- 新增 GitHub Actions 工作流 `.github/workflows/ci.yml`:在 `windows-latest` 上用 MinGW-w64 + Ninja 构建、运行集成测试、打包,并把 `JuiceAgent_v*.zip` 作为 artifact 上传(保留 14 天)。
|
||||
- 新增可复用的测试脚本 `tests/run-tests.ps1`:编译 → 刷新 `tests/resources` → 逐条运行并按**输出断言**(测试程序即使失败也返回 0,所以只看退出码不够)。
|
||||
- 构建改为**静态链接** C/C++ 运行时(与本地 w64devkit 一致),避免运行时 DLL 版本不匹配导致 `UnsatisfiedLinkError`。
|
||||
|
||||
---
|
||||
|
||||
## English
|
||||
|
||||
### 🐛 Fixes
|
||||
|
||||
- **Fix a config error crashing the target JVM**: when `config.toml` was missing a required key (e.g. `JarLoader.Mode`) or was malformed, the injected target JVM crashed with `EXCEPTION_ILLEGAL_INSTRUCTION`.
|
||||
|
||||
The root cause is that `libloader.dll` is **reflectively loaded (manually mapped)**, so its unwind tables are never registered with the OS and a C++ exception thrown inside it can be neither unwound nor caught - `try/catch` simply cannot work there. The fix:
|
||||
|
||||
- configuration reads are now **non-throwing**: a missing key or type mismatch is logged and the loader **returns early**, with the error naming the exact key;
|
||||
- config parsing happens in **non-throwing mode** (`toml::parse_result`), so malformed TOML is reported instead of crashing;
|
||||
- the `libloader` target is compiled with **`-fno-exceptions`**, so any exception-capable code added later fails the **build** instead of crashing at runtime.
|
||||
|
||||
### ✨ Features
|
||||
|
||||
- New `subscribeFront` / `listenFront` on the event bus, to register a listener ahead of the existing ones (ordering support for a future transformer pipeline).
|
||||
|
||||
### 🔧 Internal
|
||||
|
||||
- Replace the `eventpp` dependency with a ~60-line, **type-safe** event bus: listeners are registered and invoked by concrete event type, with no `const void*` casting; the in-tree eventpp headers (23 files, ~144 KB) and their license are removed.
|
||||
- Remove the unreferenced `MethodEntry` / `MethodExit` event definitions.
|
||||
|
||||
### 📝 Docs
|
||||
|
||||
- Add [docs/config.md](../config.md) (full v2 configuration reference) and [docs/update/](../update/) (release notes + changelog).
|
||||
- Rewrite [docs/advanced.md](../advanced.md); update the config examples in both READMEs to v2.
|
||||
|
||||
### 🔁 CI
|
||||
|
||||
- Add a GitHub Actions workflow (`.github/workflows/ci.yml`) that builds with MinGW-w64 + Ninja on `windows-latest`, runs the integration tests, packages the release, and uploads `JuiceAgent_v*.zip` as a build artifact (14-day retention).
|
||||
- Add a reusable test runner, `tests/run-tests.ps1`, which compiles the modules, refreshes `tests/resources`, then runs every test and asserts on its **output** (the test programs exit 0 even on failure, so exit codes are not enough).
|
||||
- Link the C/C++ runtime **statically** (matching the local w64devkit build) so the DLLs do not fail to load because of a mismatched runtime DLL on the machine.
|
||||
|
||||
---
|
||||
|
||||
如果您在使用过程中遇到问题,可以加入我们的QQ/Discord群组
|
||||
If you encounter any issues during use, you can join our QQ/Discord group
|
||||
|
||||
Discord: [JuiceDev](https://discord.gg/AQTnUyWNNJ)
|
||||
QQ群: 1103504356
|
||||
|
||||
**Full Changelog**: https://github.com/xiaozhou233/JuiceAgent/compare/v5.0.0...v5.0.1
|
||||
@@ -64,15 +64,12 @@ in `config.toml` and execute its entry method.
|
||||
|
||||
```toml
|
||||
[JuiceAgent]
|
||||
Version = 1
|
||||
|
||||
[JuiceAgent.Loader]
|
||||
Version = 2
|
||||
JuiceAgentNativeLibraryPath = ""
|
||||
|
||||
[JuiceAgent.Modules]
|
||||
|
||||
[JuiceAgent.Modules.JarLoader]
|
||||
[JarLoader]
|
||||
Enabled = true
|
||||
Mode = "BuiltIn"
|
||||
InjectionDir = "./injection"
|
||||
JarPath = "./demo.jar"
|
||||
EntryClass = "Example.Main"
|
||||
|
||||
@@ -47,15 +47,12 @@ Configuration (config.toml)
|
||||
============================
|
||||
|
||||
[JuiceAgent]
|
||||
Version = 1
|
||||
|
||||
[JuiceAgent.Loader]
|
||||
Version = 2
|
||||
JuiceAgentNativeLibraryPath = ""
|
||||
|
||||
[JuiceAgent.Modules]
|
||||
|
||||
[JuiceAgent.Modules.JarLoader]
|
||||
[JarLoader]
|
||||
Enabled = true
|
||||
Mode = "BuiltIn"
|
||||
InjectionDir = "./injection"
|
||||
JarPath = "./demo.jar"
|
||||
EntryClass = "Example.Main"
|
||||
|
||||
@@ -1,14 +1,19 @@
|
||||
[JuiceAgent]
|
||||
Version = 1
|
||||
# See config.md for more information https://github.com/xiaozhou233/JuiceAgent/blob/main/docs/config.md
|
||||
|
||||
[JuiceAgent.Loader]
|
||||
[JuiceAgent]
|
||||
Version = 2
|
||||
JuiceAgentNativeLibraryPath = ""
|
||||
|
||||
[JuiceAgent.Modules]
|
||||
|
||||
[JuiceAgent.Modules.JarLoader]
|
||||
[JarLoader]
|
||||
# Mode: BuiltIn, CustomJar
|
||||
# BuiltIn: Use the built-in jar loader (recommended, support JuiceAgent-API ( https://github.com/xiaozhou233/JuiceAgent#juiceagent-api ))
|
||||
# CustomJar: Load the Jar directly, without using JuiceAgent-API
|
||||
# For more information, please refer to the documentation: https://github.com/xiaozhou233/JuiceAgent/blob/main/docs/advanced.md#load-custom-api--directly-load-jar
|
||||
Enabled = true
|
||||
Mode = "BuiltIn"
|
||||
|
||||
# InjectionDir only works when Mode is BuiltIn
|
||||
InjectionDir = "./injection"
|
||||
JarPath = "./demo.jar"
|
||||
EntryClass = "Example.Main"
|
||||
EntryMethod = "run"
|
||||
EntryMethod = "run"
|
||||
@@ -63,15 +63,12 @@
|
||||
|
||||
```toml
|
||||
[JuiceAgent]
|
||||
Version = 1
|
||||
|
||||
[JuiceAgent.Loader]
|
||||
Version = 2
|
||||
JuiceAgentNativeLibraryPath = ""
|
||||
|
||||
[JuiceAgent.Modules]
|
||||
|
||||
[JuiceAgent.Modules.JarLoader]
|
||||
[JarLoader]
|
||||
Enabled = true
|
||||
Mode = "BuiltIn"
|
||||
InjectionDir = "./injection"
|
||||
JarPath = "./demo.jar"
|
||||
EntryClass = "Example.Main"
|
||||
|
||||
@@ -46,15 +46,12 @@
|
||||
=======================
|
||||
|
||||
[JuiceAgent]
|
||||
Version = 1
|
||||
|
||||
[JuiceAgent.Loader]
|
||||
Version = 2
|
||||
JuiceAgentNativeLibraryPath = ""
|
||||
|
||||
[JuiceAgent.Modules]
|
||||
|
||||
[JuiceAgent.Modules.JarLoader]
|
||||
[JarLoader]
|
||||
Enabled = true
|
||||
Mode = "BuiltIn"
|
||||
InjectionDir = "./injection"
|
||||
JarPath = "./demo.jar"
|
||||
EntryClass = "Example.Main"
|
||||
|
||||
@@ -1,21 +1,19 @@
|
||||
[JuiceAgent]
|
||||
Version = 1
|
||||
# See config.md for more information https://github.com/xiaozhou233/JuiceAgent/blob/main/docs/config.md
|
||||
|
||||
[JuiceAgent.Loader]
|
||||
# Path to JuiceAgent-API jar, leave empty to use the built-in API
|
||||
JuiceAgentAPIJarPath = ""
|
||||
# Path to libagent.dll, default is "./libagent.dll"
|
||||
[JuiceAgent]
|
||||
Version = 2
|
||||
JuiceAgentNativeLibraryPath = ""
|
||||
|
||||
[JuiceAgent.Modules]
|
||||
|
||||
[JuiceAgent.Modules.JarLoader]
|
||||
[JarLoader]
|
||||
# Mode: BuiltIn, CustomJar
|
||||
# BuiltIn: Use the built-in jar loader (recommended, support JuiceAgent-API ( https://github.com/xiaozhou233/JuiceAgent#juiceagent-api ))
|
||||
# CustomJar: Load the Jar directly, without using JuiceAgent-API
|
||||
# For more information, please refer to the documentation: https://github.com/xiaozhou233/JuiceAgent/blob/main/docs/advanced.md#load-custom-api--directly-load-jar
|
||||
Enabled = true
|
||||
# Directory containing dependency JARs to load into the JVM (put your deps here)
|
||||
Mode = "BuiltIn"
|
||||
|
||||
# InjectionDir only works when Mode is BuiltIn
|
||||
InjectionDir = "./injection"
|
||||
# Path to the injection JAR to be loaded
|
||||
JarPath = "./demo.jar"
|
||||
# Entry class to be executed after loading the JAR
|
||||
EntryClass = "Example.Main"
|
||||
# Entry method, must be: public static void run()
|
||||
EntryMethod = "run"
|
||||
@@ -3,5 +3,5 @@ out/
|
||||
|
||||
# Do not ignore root build artifacts:
|
||||
!new_target.class
|
||||
!playload.jar
|
||||
!payload.jar
|
||||
!target.jar
|
||||
@@ -10,10 +10,10 @@
|
||||
| `config.toml` | Injection config |
|
||||
| `build.bat` | Build script |
|
||||
| `run.bat` | Run target JVM |
|
||||
| `playload.jar` | JAR to inject (built by `build.bat`) |
|
||||
| `payload.jar` | JAR to inject (built by `build.bat`) |
|
||||
| `target.jar` | Target JVM program (built by `build.bat`) |
|
||||
| `new_target.class` | Retransformed bytecode (built by `build.bat`) |
|
||||
| `playload/` | Payload source |
|
||||
| `payload/` | Payload source |
|
||||
| `target/` | Target source |
|
||||
| `new_target/` | Modified copy of target source |
|
||||
|
||||
@@ -31,7 +31,7 @@ Hello!
|
||||
Retransformed!
|
||||
```
|
||||
|
||||
This example injects `playload.jar` into a running JVM. The payload reads
|
||||
This example injects `payload.jar` into a running JVM. The payload reads
|
||||
`new_target.class` from its own JAR and calls
|
||||
`JuiceAgent.retransformClassByName("target", ...)` to swap the already-loaded
|
||||
`target` class on the fly. After that, `say()` starts printing the new message
|
||||
@@ -41,14 +41,14 @@ without restarting the JVM.
|
||||
|
||||
### 1. Build (optional)
|
||||
|
||||
`playload.jar` and `target.jar` are already included by default.
|
||||
If you modified `playload/`, `target/` or `new_target/`, run:
|
||||
`payload.jar` and `target.jar` are already included by default.
|
||||
If you modified `payload/`, `target/` or `new_target/`, run:
|
||||
|
||||
```
|
||||
build.bat
|
||||
```
|
||||
|
||||
to regenerate `playload.jar`, `target.jar` and `new_target.class`.
|
||||
to regenerate `payload.jar`, `target.jar` and `new_target.class`.
|
||||
|
||||
### 2. Run the target JVM
|
||||
|
||||
@@ -77,8 +77,8 @@ Input PID: 6644
|
||||
Go back to the target window. Injection succeeded if you see:
|
||||
|
||||
```
|
||||
Playload loaded!
|
||||
Playload executed!
|
||||
Payload loaded!
|
||||
Payload executed!
|
||||
```
|
||||
|
||||
and the output of `say()` changes from `Hello!` to:
|
||||
@@ -92,8 +92,8 @@ Retransformed!
|
||||
|
||||
| Key | Description |
|
||||
| --- | --- |
|
||||
| `JarPath` | JAR path to inject (default: `./playload.jar`) |
|
||||
| `EntryClass` | Entry class (default: `playload`) |
|
||||
| `JarPath` | JAR path to inject (default: `./payload.jar`) |
|
||||
| `EntryClass` | Entry class (default: `payload`) |
|
||||
| `EntryMethod` | Entry method, must be `public static void entry()` |
|
||||
|
||||
## Troubleshooting
|
||||
@@ -102,8 +102,8 @@ Retransformed!
|
||||
Install a JDK and add its `bin` directory to `PATH`.
|
||||
- `injector.exe` reports injection failure:
|
||||
Make sure the target JVM is running and the PID is correct.
|
||||
- No `Playload loaded!` output appears:
|
||||
- No `Payload loaded!` output appears:
|
||||
Check `libagent.log` and `libloader.log` in this directory for the cause.
|
||||
- `say()` output does not change:
|
||||
Make sure `build.bat` was run after editing `new_target/`, and that
|
||||
`new_target.class` inside `playload.jar` is up to date.
|
||||
`new_target.class` inside `payload.jar` is up to date.
|
||||
@@ -9,10 +9,10 @@ Directory Files:
|
||||
config.toml - injection config
|
||||
build.bat - build script
|
||||
run.bat - run target JVM
|
||||
playload.jar - JAR to inject (built by build.bat)
|
||||
payload.jar - JAR to inject (built by build.bat)
|
||||
target.jar - target JVM program (built by build.bat)
|
||||
new_target.class - retransformed bytecode (built by build.bat)
|
||||
playload/ - payload source
|
||||
payload/ - payload source
|
||||
target/ - target source
|
||||
new_target/ - modified copy of target source
|
||||
|
||||
@@ -26,7 +26,7 @@ The target class "target" has a method say() that prints:
|
||||
new_target/target.java is a modified copy that also prints:
|
||||
Retransformed!
|
||||
|
||||
This example injects playload.jar into a running JVM. The payload reads
|
||||
This example injects payload.jar into a running JVM. The payload reads
|
||||
new_target.class from its own JAR and calls
|
||||
JuiceAgent.retransformClassByName("target", ...) to swap the already-loaded
|
||||
"target" class on the fly. After that, say() starts printing the new message
|
||||
@@ -37,10 +37,10 @@ without restarting the JVM.
|
||||
============================================
|
||||
|
||||
1. Build (optional)
|
||||
playload.jar and target.jar are already included by default.
|
||||
If you modified playload/, target/ or new_target/, run:
|
||||
payload.jar and target.jar are already included by default.
|
||||
If you modified payload/, target/ or new_target/, run:
|
||||
build.bat
|
||||
to regenerate playload.jar, target.jar and new_target.class.
|
||||
to regenerate payload.jar, target.jar and new_target.class.
|
||||
|
||||
2. Run the target JVM
|
||||
Double-click run.bat (or run: java -jar target.jar). A black window
|
||||
@@ -57,8 +57,8 @@ without restarting the JVM.
|
||||
|
||||
4. Verify
|
||||
Go back to the target window. Injection succeeded if you see:
|
||||
Playload loaded!
|
||||
Playload executed!
|
||||
Payload loaded!
|
||||
Payload executed!
|
||||
and the output of say() changes from "Hello!" to:
|
||||
Hello!
|
||||
Retransformed!
|
||||
@@ -67,8 +67,8 @@ without restarting the JVM.
|
||||
Config / config.toml
|
||||
============================================
|
||||
|
||||
JarPath - JAR path to inject (default: ./playload.jar)
|
||||
EntryClass - Entry class (default: playload)
|
||||
JarPath - JAR path to inject (default: ./payload.jar)
|
||||
EntryClass - Entry class (default: payload)
|
||||
EntryMethod - Entry method, must be public static void entry()
|
||||
|
||||
============================================
|
||||
@@ -79,8 +79,8 @@ without restarting the JVM.
|
||||
Install a JDK and add its bin directory to PATH.
|
||||
- injector.exe reports injection failure:
|
||||
Make sure the target JVM is running and the PID is correct.
|
||||
- No "Playload loaded!" output appears:
|
||||
- No "Payload loaded!" output appears:
|
||||
Check libagent.log and libloader.log in this directory for the cause.
|
||||
- say() output does not change:
|
||||
Make sure build.bat was run after editing new_target/, and that
|
||||
new_target.class inside playload.jar is up to date.
|
||||
new_target.class inside payload.jar is up to date.
|
||||
@@ -1,13 +1,13 @@
|
||||
@echo off
|
||||
setlocal
|
||||
|
||||
set "API_JAR=playload\JuiceAgent-API-1.4.1+build.1.jar"
|
||||
set "PAYLOAD_JAR=playload.jar"
|
||||
set "API_JAR=payload\JuiceAgent-API-1.4.1+build.1.jar"
|
||||
set "PAYLOAD_JAR=payload.jar"
|
||||
set "TARGET_JAR=target.jar"
|
||||
|
||||
set "OUT=out"
|
||||
set "OUT_NT=%OUT%\new_target"
|
||||
set "OUT_PL=%OUT%\playload"
|
||||
set "OUT_PL=%OUT%\payload"
|
||||
set "OUT_TG=%OUT%\target"
|
||||
|
||||
set "NEW_TARGET_CLASS=new_target.class"
|
||||
@@ -29,8 +29,8 @@ if errorlevel 1 goto :error
|
||||
copy /y "%OUT_NT%\new_target.class" "%NEW_TARGET_CLASS%"
|
||||
if errorlevel 1 goto :error
|
||||
|
||||
echo === Compiling playload ===
|
||||
javac -encoding UTF-8 --release 8 -cp "%API_JAR%" -d "%OUT_PL%" playload\playload.java
|
||||
echo === Compiling payload ===
|
||||
javac -encoding UTF-8 --release 8 -cp "%API_JAR%" -d "%OUT_PL%" payload\payload.java
|
||||
if errorlevel 1 goto :error
|
||||
|
||||
echo === Compiling target ===
|
||||
@@ -38,7 +38,7 @@ javac -encoding UTF-8 --release 8 -d "%OUT_TG%" target\target.java
|
||||
if errorlevel 1 goto :error
|
||||
|
||||
echo === Packaging payload jar ===
|
||||
jar --create --file "%PAYLOAD_JAR%" -C "%OUT_PL%" playload.class
|
||||
jar --create --file "%PAYLOAD_JAR%" -C "%OUT_PL%" payload.class
|
||||
if errorlevel 1 goto :error
|
||||
|
||||
echo === Packaging target jar ===
|
||||
|
||||
@@ -1,21 +1,19 @@
|
||||
[JuiceAgent]
|
||||
Version = 1
|
||||
# See config.md for more information https://github.com/xiaozhou233/JuiceAgent/blob/main/docs/config.md
|
||||
|
||||
[JuiceAgent.Loader]
|
||||
# Path to JuiceAgent-API jar, leave empty to use the built-in API
|
||||
JuiceAgentAPIJarPath = ""
|
||||
# Path to libagent.dll, default is "./libagent.dll"
|
||||
[JuiceAgent]
|
||||
Version = 2
|
||||
JuiceAgentNativeLibraryPath = ""
|
||||
|
||||
[JuiceAgent.Modules]
|
||||
|
||||
[JuiceAgent.Modules.JarLoader]
|
||||
[JarLoader]
|
||||
# Mode: BuiltIn, CustomJar
|
||||
# BuiltIn: Use the built-in jar loader (recommended, support JuiceAgent-API ( https://github.com/xiaozhou233/JuiceAgent#juiceagent-api ))
|
||||
# CustomJar: Load the Jar directly, without using JuiceAgent-API
|
||||
# For more information, please refer to the documentation: https://github.com/xiaozhou233/JuiceAgent/blob/main/docs/advanced.md#load-custom-api--directly-load-jar
|
||||
Enabled = true
|
||||
# Directory containing dependency JARs to load into the JVM (put your deps here)
|
||||
Mode = "BuiltIn"
|
||||
|
||||
# InjectionDir only works when Mode is BuiltIn
|
||||
InjectionDir = "./injection"
|
||||
# Path to the injection JAR to be loaded
|
||||
JarPath = "./playload.jar"
|
||||
# Entry class to be executed after loading the JAR
|
||||
EntryClass = "playload"
|
||||
# Entry method, must be: public static void run()
|
||||
JarPath = "./payload.jar"
|
||||
EntryClass = "payload"
|
||||
EntryMethod = "entry"
|
||||
Binary file not shown.
File renamed without changes.
+3
-3
@@ -1,8 +1,8 @@
|
||||
import cn.xiaozhou233.juiceagent.api.JuiceAgent;
|
||||
|
||||
public class playload {
|
||||
public class payload {
|
||||
public static void entry() throws java.io.IOException {
|
||||
System.out.println("Playload loaded!");
|
||||
System.out.println("Payload loaded!");
|
||||
|
||||
java.io.InputStream in = new java.io.FileInputStream("new_target.class");
|
||||
java.io.ByteArrayOutputStream out = new java.io.ByteArrayOutputStream();
|
||||
@@ -20,6 +20,6 @@ public class playload {
|
||||
bytes.length
|
||||
);
|
||||
|
||||
System.out.println("Playload executed!");
|
||||
System.out.println("Payload executed!");
|
||||
}
|
||||
}
|
||||
Binary file not shown.
@@ -10,10 +10,10 @@
|
||||
| `config.toml` | 注入配置 |
|
||||
| `build.bat` | 构建脚本 |
|
||||
| `run.bat` | 运行目标 JVM |
|
||||
| `playload.jar` | 注入用的 JAR(由 `build.bat` 生成) |
|
||||
| `payload.jar` | 注入用的 JAR(由 `build.bat` 生成) |
|
||||
| `target.jar` | 目标 JVM 程序(由 `build.bat` 生成) |
|
||||
| `new_target.class` | 重变换后的字节码(由 `build.bat` 生成) |
|
||||
| `playload/` | payload 源码 |
|
||||
| `payload/` | payload 源码 |
|
||||
| `target/` | 目标类源码 |
|
||||
| `new_target/` | target 的修改版源码 |
|
||||
|
||||
@@ -31,7 +31,7 @@ Hello!
|
||||
Retransformed!
|
||||
```
|
||||
|
||||
本示例把 `playload.jar` 注入到运行中的 JVM。payload 从自己的 JAR 中读取
|
||||
本示例把 `payload.jar` 注入到运行中的 JVM。payload 从自己的 JAR 中读取
|
||||
`new_target.class`,调用 `JuiceAgent.retransformClassByName("target", ...)`
|
||||
在运行时动态替换已加载的 `target` 类。之后 `say()` 无需重启 JVM 就会输出新内容。
|
||||
|
||||
@@ -39,14 +39,14 @@ Retransformed!
|
||||
|
||||
### 1. 构建(可选)
|
||||
|
||||
`playload.jar` 和 `target.jar` 默认已包含。
|
||||
如果修改了 `playload/`、`target/` 或 `new_target/`,运行:
|
||||
`payload.jar` 和 `target.jar` 默认已包含。
|
||||
如果修改了 `payload/`、`target/` 或 `new_target/`,运行:
|
||||
|
||||
```
|
||||
build.bat
|
||||
```
|
||||
|
||||
重新生成 `playload.jar`、`target.jar` 和 `new_target.class`。
|
||||
重新生成 `payload.jar`、`target.jar` 和 `new_target.class`。
|
||||
|
||||
### 2. 运行目标 JVM
|
||||
|
||||
@@ -72,8 +72,8 @@ Input PID: 6644
|
||||
回到目标窗口,注入成功应看到:
|
||||
|
||||
```
|
||||
Playload loaded!
|
||||
Playload executed!
|
||||
Payload loaded!
|
||||
Payload executed!
|
||||
```
|
||||
|
||||
并且 `say()` 的输出从 `Hello!` 变为:
|
||||
@@ -87,8 +87,8 @@ Retransformed!
|
||||
|
||||
| 配置项 | 说明 |
|
||||
| --- | --- |
|
||||
| `JarPath` | 注入的 JAR 路径(默认 `./playload.jar`) |
|
||||
| `EntryClass` | 入口类(默认 `playload`) |
|
||||
| `JarPath` | 注入的 JAR 路径(默认 `./payload.jar`) |
|
||||
| `EntryClass` | 入口类(默认 `payload`) |
|
||||
| `EntryMethod` | 入口方法,必须为 `public static void entry()` |
|
||||
|
||||
## 常见问题
|
||||
@@ -97,8 +97,8 @@ Retransformed!
|
||||
安装 JDK 并将 `bin` 目录加入 `PATH`。
|
||||
- `injector.exe` 提示注入失败:
|
||||
确认目标 JVM 正在运行且 PID 正确。
|
||||
- 没有出现 `Playload loaded!` 输出:
|
||||
- 没有出现 `Payload loaded!` 输出:
|
||||
查看本目录下的 `libagent.log` 和 `libloader.log` 定位原因。
|
||||
- `say()` 输出没有变化:
|
||||
确认修改 `new_target/` 后重新运行过 `build.bat`,且 `playload.jar` 内的
|
||||
确认修改 `new_target/` 后重新运行过 `build.bat`,且 `payload.jar` 内的
|
||||
`new_target.class` 是最新的。
|
||||
@@ -9,10 +9,10 @@
|
||||
config.toml - 注入配置
|
||||
build.bat - 构建脚本
|
||||
run.bat - 运行目标 JVM
|
||||
playload.jar - 注入用的 JAR (由 build.bat 生成)
|
||||
payload.jar - 注入用的 JAR (由 build.bat 生成)
|
||||
target.jar - 目标 JVM 程序 (由 build.bat 生成)
|
||||
new_target.class - 重变换后的字节码 (由 build.bat 生成)
|
||||
playload/ - payload 源码
|
||||
payload/ - payload 源码
|
||||
target/ - 目标类源码
|
||||
new_target/ - target 的修改版源码
|
||||
|
||||
@@ -26,7 +26,7 @@
|
||||
new_target/target.java 是它的修改版, 额外打印:
|
||||
Retransformed!
|
||||
|
||||
本示例把 playload.jar 注入到运行中的 JVM。payload 从自己的 JAR 中读取
|
||||
本示例把 payload.jar 注入到运行中的 JVM。payload 从自己的 JAR 中读取
|
||||
new_target.class, 调用 JuiceAgent.retransformClassByName("target", ...)
|
||||
在运行时动态替换已加载的 "target" 类。之后 say() 无需重启 JVM 就会输出新内容。
|
||||
|
||||
@@ -35,10 +35,10 @@ new_target.class, 调用 JuiceAgent.retransformClassByName("target", ...)
|
||||
============================================
|
||||
|
||||
1. 构建 (可选)
|
||||
playload.jar 和 target.jar 默认已包含。
|
||||
如果修改了 playload/、target/ 或 new_target/, 运行:
|
||||
payload.jar 和 target.jar 默认已包含。
|
||||
如果修改了 payload/、target/ 或 new_target/, 运行:
|
||||
build.bat
|
||||
重新生成 playload.jar、target.jar 和 new_target.class。
|
||||
重新生成 payload.jar、target.jar 和 new_target.class。
|
||||
|
||||
2. 运行目标 JVM
|
||||
双击 run.bat (或执行: java -jar target.jar)。黑窗口出现并每秒打印:
|
||||
@@ -53,8 +53,8 @@ new_target.class, 调用 JuiceAgent.retransformClassByName("target", ...)
|
||||
|
||||
4. 验证
|
||||
回到目标窗口, 注入成功应看到:
|
||||
Playload loaded!
|
||||
Playload executed!
|
||||
Payload loaded!
|
||||
Payload executed!
|
||||
并且 say() 的输出从 "Hello!" 变为:
|
||||
Hello!
|
||||
Retransformed!
|
||||
@@ -63,8 +63,8 @@ new_target.class, 调用 JuiceAgent.retransformClassByName("target", ...)
|
||||
配置 / config.toml
|
||||
============================================
|
||||
|
||||
JarPath - 注入的 JAR 路径 (默认: ./playload.jar)
|
||||
EntryClass - 入口类 (默认: playload)
|
||||
JarPath - 注入的 JAR 路径 (默认: ./payload.jar)
|
||||
EntryClass - 入口类 (默认: payload)
|
||||
EntryMethod - 入口方法, 必须为 public static void entry()
|
||||
|
||||
============================================
|
||||
@@ -75,8 +75,8 @@ new_target.class, 调用 JuiceAgent.retransformClassByName("target", ...)
|
||||
安装 JDK 并将 bin 目录加入 PATH。
|
||||
- injector.exe 提示注入失败:
|
||||
确认目标 JVM 正在运行且 PID 正确。
|
||||
- 没有出现 "Playload loaded!" 输出:
|
||||
- 没有出现 "Payload loaded!" 输出:
|
||||
查看本目录下的 libagent.log 和 libloader.log 定位原因。
|
||||
- say() 输出没有变化:
|
||||
确认修改 new_target/ 后重新运行过 build.bat, 且 playload.jar 内的
|
||||
确认修改 new_target/ 后重新运行过 build.bat, 且 payload.jar 内的
|
||||
new_target.class 是最新的。
|
||||
+108
-126
@@ -1,160 +1,142 @@
|
||||
#pragma once
|
||||
|
||||
#include <filesystem>
|
||||
#include <optional>
|
||||
#include <toml++/toml.h>
|
||||
#include <string>
|
||||
#include <type_traits>
|
||||
|
||||
#include <JuiceAgent/ConfigStruct.hpp>
|
||||
#include <vector>
|
||||
#include <cstddef>
|
||||
#include <JuiceAgent/Logger.hpp>
|
||||
#include <JuiceAgent/Utils.hpp>
|
||||
#include <toml.hpp>
|
||||
|
||||
namespace JuiceAgent::Config {
|
||||
|
||||
class Config {
|
||||
private:
|
||||
toml::table _config;
|
||||
std::optional<toml::parse_error> _last_error;
|
||||
|
||||
std::filesystem::path _runtime_dir;
|
||||
std::filesystem::path _config_path;
|
||||
|
||||
bool _valid = false;
|
||||
|
||||
public:
|
||||
explicit Config(const std::filesystem::path& runtime_dir = {})
|
||||
{
|
||||
_runtime_dir = runtime_dir;
|
||||
|
||||
// No runtime directory specified: do not auto-read a config file
|
||||
// from the current working directory.
|
||||
explicit Config(const std::filesystem::path& runtime_dir = {}) {
|
||||
// Check if the runtime directory is empty
|
||||
if (runtime_dir.empty()) {
|
||||
return;
|
||||
// Use the default runtime directory
|
||||
_runtime_dir = std::filesystem::current_path();
|
||||
} else {
|
||||
_runtime_dir = runtime_dir;
|
||||
}
|
||||
|
||||
const auto result = toml::try_parse(_runtime_dir / "config.toml");
|
||||
_config_path = _runtime_dir / "config.toml";
|
||||
|
||||
if (result.is_ok()) {
|
||||
_config = result.unwrap();
|
||||
// Load the config file.
|
||||
//
|
||||
// This must never throw: when libloader runs from the reflectively
|
||||
// loaded DLL its unwind tables are not registered, so a C++ exception
|
||||
// raised here could not be caught and would crash the target process.
|
||||
// toml++ switches to non-throwing mode (parse_result) automatically
|
||||
// when exceptions are disabled.
|
||||
#if TOML_EXCEPTIONS
|
||||
try {
|
||||
_config = toml::parse_file(_config_path.string());
|
||||
_valid = true;
|
||||
} catch (const toml::parse_error& e) {
|
||||
spdlog::error("Failed to parse config file: {}", e.description());
|
||||
_last_error = e;
|
||||
}
|
||||
else {
|
||||
spdlog::error("Failed to parse config.toml");
|
||||
|
||||
for (const auto& err : result.unwrap_err()) {
|
||||
spdlog::error("{}", toml::format_error(err));
|
||||
}
|
||||
#else
|
||||
toml::parse_result result = toml::parse_file(_config_path.string());
|
||||
if (result.succeeded()) {
|
||||
_config = std::move(result).table();
|
||||
_valid = true;
|
||||
} else {
|
||||
spdlog::error("Failed to parse config file: {}", result.error().description());
|
||||
_last_error = result.error();
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
bool is_valid() const noexcept
|
||||
{
|
||||
return _valid;
|
||||
// Non-throwing lookup: returns defaultValue when the key is missing or has
|
||||
// the wrong type. There is deliberately no throwing overload - callers that
|
||||
// require a key must check contains() first.
|
||||
template<typename T>
|
||||
T get(const std::string& path, T defaultValue) const {
|
||||
const auto* node = _config.at_path(path).node();
|
||||
|
||||
if (!node) {
|
||||
// Configuration key is missing; use the default value.
|
||||
spdlog::warn("Configuration key not found: {}, using default value", path);
|
||||
return defaultValue;
|
||||
}
|
||||
|
||||
auto value = node->value<T>();
|
||||
|
||||
if (!value) {
|
||||
// Configuration type mismatch; use the default value.
|
||||
spdlog::warn("Configuration type mismatch: {}, using default value", path);
|
||||
return defaultValue;
|
||||
}
|
||||
|
||||
return *value;
|
||||
}
|
||||
|
||||
const toml::value& get_config() const noexcept
|
||||
{
|
||||
std::string getPath(
|
||||
const std::string& key,
|
||||
const std::string& defaultValue
|
||||
) const {
|
||||
std::string rawValue = get<std::string>(key, defaultValue);
|
||||
|
||||
// Use the default value when the configuration value is empty.
|
||||
if (rawValue.empty()) {
|
||||
rawValue = defaultValue;
|
||||
}
|
||||
|
||||
if (rawValue.empty()) {
|
||||
return {};
|
||||
}
|
||||
|
||||
const std::filesystem::path value(rawValue);
|
||||
|
||||
if (value.is_absolute()) {
|
||||
return value.lexically_normal().string();
|
||||
}
|
||||
|
||||
const std::string normalized = value.generic_string();
|
||||
|
||||
if (normalized == "." || normalized.starts_with("./")) {
|
||||
return (_runtime_dir / value).lexically_normal().string();
|
||||
}
|
||||
|
||||
return value.lexically_normal().string();
|
||||
}
|
||||
|
||||
bool contains(const std::string& path) const {
|
||||
return _config.at_path(path).node() != nullptr;
|
||||
}
|
||||
|
||||
// Getters
|
||||
const toml::table& getConfig() const {
|
||||
return _config;
|
||||
}
|
||||
|
||||
const std::filesystem::path& runtime_dir() const noexcept
|
||||
{
|
||||
const std::filesystem::path& getRuntimeDir() const {
|
||||
return _runtime_dir;
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
T get(const std::string& path, const T& default_value, bool is_path = false) const
|
||||
{
|
||||
if (!_valid) {
|
||||
return default_value;
|
||||
}
|
||||
|
||||
try {
|
||||
const toml::value* current = &_config;
|
||||
std::size_t start = 0;
|
||||
|
||||
while (start < path.size()) {
|
||||
const std::size_t end = path.find('.', start);
|
||||
const std::string key = path.substr(
|
||||
start,
|
||||
end == std::string::npos ? std::string::npos : end - start
|
||||
);
|
||||
|
||||
current = ¤t->at(key);
|
||||
|
||||
if (end == std::string::npos) {
|
||||
break;
|
||||
}
|
||||
|
||||
start = end + 1;
|
||||
}
|
||||
|
||||
T value = read_value<T>(*current);
|
||||
|
||||
if constexpr (std::is_same_v<T, std::string>) {
|
||||
if (value.empty()) {
|
||||
value = default_value;
|
||||
}
|
||||
|
||||
if (is_path && value.starts_with(".")) {
|
||||
value = (_runtime_dir / value).lexically_normal().string();
|
||||
}
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
catch (...) {
|
||||
spdlog::warn("Config get failed: {}, using default value", path);
|
||||
return default_value;
|
||||
}
|
||||
const std::filesystem::path& getConfigPath() const {
|
||||
return _config_path;
|
||||
}
|
||||
|
||||
private:
|
||||
template<typename T>
|
||||
static T read_value(const toml::value& v)
|
||||
{
|
||||
if constexpr (std::is_same_v<T, std::string>) {
|
||||
return v.as_string();
|
||||
}
|
||||
else if constexpr (std::is_same_v<T, bool>) {
|
||||
return v.as_boolean();
|
||||
}
|
||||
else if constexpr (std::is_integral_v<T> && !std::is_same_v<T, bool>) {
|
||||
return static_cast<T>(v.as_integer());
|
||||
}
|
||||
else if constexpr (std::is_floating_point_v<T>) {
|
||||
return static_cast<T>(v.as_floating());
|
||||
}
|
||||
else {
|
||||
static_assert(sizeof(T) == 0, "Unsupported config type");
|
||||
}
|
||||
const std::optional<toml::parse_error>& getLastError() const {
|
||||
return _last_error;
|
||||
}
|
||||
|
||||
std::filesystem::path _runtime_dir;
|
||||
toml::value _config;
|
||||
bool _valid = false;
|
||||
bool isValid() const {
|
||||
return _valid;
|
||||
}
|
||||
};
|
||||
|
||||
namespace Utils {
|
||||
inline LoaderConfig get_loader_config(const Config& config)
|
||||
{
|
||||
LoaderConfig loader_config;
|
||||
loader_config.JuiceAgentNativeLibraryPath = config.get<std::string>(
|
||||
"JuiceAgent.Loader.JuiceAgentNativeLibraryPath",
|
||||
(config.runtime_dir() / "libagent.dll").string(),
|
||||
true
|
||||
);
|
||||
loader_config.RuntimeDir = config.runtime_dir().string();
|
||||
|
||||
return loader_config;
|
||||
}
|
||||
|
||||
inline void print_loader_config(const LoaderConfig& config)
|
||||
{
|
||||
spdlog::info("JuiceAgentNativeLibraryPath: {}", config.JuiceAgentNativeLibraryPath);
|
||||
spdlog::info("RuntimeDir: {}", config.RuntimeDir);
|
||||
}
|
||||
|
||||
inline std::string serialize_loader_config(const Config& config, const LoaderConfig& loader_config)
|
||||
{
|
||||
JuiceAgent::Utils::Serializer ser;
|
||||
ser.add_kv("Version", config.get<int>("JuiceAgent.Version", 1));
|
||||
ser.add_kv("JuiceAgentNativeLibraryPath", loader_config.JuiceAgentNativeLibraryPath);
|
||||
ser.add_kv("RuntimeDir", loader_config.RuntimeDir);
|
||||
|
||||
return ser.serialize();
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace JuiceAgent::Config
|
||||
@@ -1,9 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <string>
|
||||
|
||||
struct LoaderConfig {
|
||||
std::string JuiceAgentNativeLibraryPath;
|
||||
|
||||
std::string RuntimeDir;
|
||||
};
|
||||
@@ -0,0 +1,3 @@
|
||||
#pragma once
|
||||
|
||||
const int CONFIG_VERSION = 2;
|
||||
+140
-191
@@ -10,51 +10,28 @@
|
||||
#include <string>
|
||||
#include <type_traits>
|
||||
#include <unordered_map>
|
||||
#include <charconv>
|
||||
#include <string_view>
|
||||
#include <system_error>
|
||||
|
||||
namespace JuiceAgent::Utils
|
||||
{
|
||||
template<typename T>
|
||||
class LocalRef {
|
||||
public:
|
||||
LocalRef(JNIEnv* env, T ref = nullptr)
|
||||
: _env(env), _ref(ref) {}
|
||||
// JNIEnv::FindClass expects the internal form of a class name where the
|
||||
// package separator is '/' (e.g. "Example/Main"). Configs and docs use the
|
||||
// Java binary name with '.' (e.g. "Example.Main"), so normalize it here to
|
||||
// keep both forms working.
|
||||
inline std::string to_jni_class_name(const char* name)
|
||||
{
|
||||
std::string result(name ? name : "");
|
||||
|
||||
~LocalRef()
|
||||
{
|
||||
reset();
|
||||
}
|
||||
|
||||
LocalRef(const LocalRef&) = delete;
|
||||
LocalRef& operator=(const LocalRef&) = delete;
|
||||
|
||||
LocalRef(LocalRef&& other) noexcept
|
||||
: _env(other._env), _ref(other._ref)
|
||||
{
|
||||
other._ref = nullptr;
|
||||
}
|
||||
|
||||
T get() const
|
||||
{
|
||||
return _ref;
|
||||
}
|
||||
|
||||
operator T() const
|
||||
{
|
||||
return _ref;
|
||||
}
|
||||
|
||||
void reset(T ref = nullptr)
|
||||
{
|
||||
if (_ref) {
|
||||
_env->DeleteLocalRef(_ref);
|
||||
for (char& c : result) {
|
||||
if (c == '.') {
|
||||
c = '/';
|
||||
}
|
||||
_ref = ref;
|
||||
}
|
||||
|
||||
private:
|
||||
JNIEnv* _env;
|
||||
T _ref;
|
||||
};
|
||||
return result;
|
||||
}
|
||||
|
||||
inline bool check_and_clear_exception(JNIEnv* env, const char* context)
|
||||
{
|
||||
@@ -68,7 +45,8 @@ namespace JuiceAgent::Utils
|
||||
return true;
|
||||
}
|
||||
|
||||
inline bool call_java_impl(JNIEnv* env, const char* clazz, const char* method, const char* params)
|
||||
// Call a static Java method with a single string parameter
|
||||
inline bool call_static_java_method(JNIEnv* env, const char* clazz, const char* method, const char* params)
|
||||
{
|
||||
if (!env || !clazz || !method) {
|
||||
spdlog::error("Invalid JNI arguments");
|
||||
@@ -79,7 +57,8 @@ namespace JuiceAgent::Utils
|
||||
|
||||
spdlog::debug("Calling Java method: {}.{} {}", clazz, method, signature);
|
||||
|
||||
jclass cls = env->FindClass(clazz);
|
||||
std::string jni_class = to_jni_class_name(clazz);
|
||||
jclass cls = env->FindClass(jni_class.c_str());
|
||||
if (!cls) {
|
||||
check_and_clear_exception(env, "FindClass failed");
|
||||
spdlog::error("Class not found: {}", clazz);
|
||||
@@ -118,210 +97,180 @@ namespace JuiceAgent::Utils
|
||||
|
||||
return success;
|
||||
}
|
||||
|
||||
inline bool call_static_java_method(JNIEnv* env, const char* clazz, const char* method)
|
||||
{
|
||||
if (!env || !clazz || !method) {
|
||||
spdlog::error("Invalid JNI arguments");
|
||||
return false;
|
||||
}
|
||||
|
||||
constexpr const char* signature = "()V";
|
||||
|
||||
spdlog::debug("Calling Java method: {}.{} {}", clazz, method, signature);
|
||||
|
||||
std::string jni_class = to_jni_class_name(clazz);
|
||||
jclass cls = env->FindClass(jni_class.c_str());
|
||||
if (!cls) {
|
||||
check_and_clear_exception(env, "FindClass failed");
|
||||
spdlog::error("Class not found: {}", clazz);
|
||||
return false;
|
||||
}
|
||||
|
||||
jmethodID mid = env->GetStaticMethodID(cls, method, signature);
|
||||
if (!mid) {
|
||||
check_and_clear_exception(env, "GetStaticMethodID failed");
|
||||
spdlog::error("Method not found: {}", method);
|
||||
env->DeleteLocalRef(cls);
|
||||
return false;
|
||||
}
|
||||
|
||||
env->CallStaticVoidMethod(cls, mid);
|
||||
|
||||
bool success = !env->ExceptionCheck();
|
||||
check_and_clear_exception(env, "CallStaticVoidMethod failed");
|
||||
|
||||
env->DeleteLocalRef(cls);
|
||||
|
||||
return success;
|
||||
}
|
||||
|
||||
class Serializer {
|
||||
public:
|
||||
template<typename T>
|
||||
Serializer& add_kv(const std::string& key, const T& value)
|
||||
Serializer& add_kv(std::string_view key, const T& value)
|
||||
{
|
||||
s += escape(key);
|
||||
append_escaped(key);
|
||||
s += '=';
|
||||
|
||||
if constexpr (std::is_same_v<T, bool>) {
|
||||
using ValueType = std::decay_t<T>;
|
||||
|
||||
if constexpr (std::is_same_v<ValueType, bool>) {
|
||||
s += value ? "true" : "false";
|
||||
}
|
||||
else if constexpr (std::is_arithmetic_v<T>) {
|
||||
s += escape(std::to_string(value));
|
||||
else if constexpr (std::is_integral_v<ValueType>) {
|
||||
append_number(value);
|
||||
}
|
||||
else if constexpr (std::is_floating_point_v<ValueType>) {
|
||||
append_number(value);
|
||||
}
|
||||
else {
|
||||
s += escape(value);
|
||||
append_escaped(std::string_view(value));
|
||||
}
|
||||
|
||||
s += ';';
|
||||
return *this;
|
||||
}
|
||||
|
||||
void clear()
|
||||
void clear() noexcept
|
||||
{
|
||||
s.clear();
|
||||
}
|
||||
|
||||
bool empty() const
|
||||
bool empty() const noexcept
|
||||
{
|
||||
return s.empty();
|
||||
}
|
||||
|
||||
const std::string& serialize() const
|
||||
const std::string& serialize() const noexcept
|
||||
{
|
||||
return s;
|
||||
}
|
||||
|
||||
private:
|
||||
static std::string escape(const std::string& input)
|
||||
void append_escaped(std::string_view input)
|
||||
{
|
||||
std::string out;
|
||||
out.reserve(input.size());
|
||||
|
||||
for (char c : input) {
|
||||
if (c == '=' || c == ';' || c == '\\') {
|
||||
out += '\\';
|
||||
s += '\\';
|
||||
}
|
||||
out += c;
|
||||
}
|
||||
|
||||
return out;
|
||||
s += c;
|
||||
}
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
void append_number(T value)
|
||||
{
|
||||
char buffer[64];
|
||||
|
||||
auto [end, ec] = std::to_chars(
|
||||
buffer,
|
||||
buffer + sizeof(buffer),
|
||||
value
|
||||
);
|
||||
|
||||
if (ec == std::errc{}) {
|
||||
s.append(buffer, end);
|
||||
}
|
||||
}
|
||||
|
||||
std::string s;
|
||||
};
|
||||
|
||||
class Deserializer {
|
||||
public:
|
||||
Deserializer() = default;
|
||||
inline jobjectArray to_java_string_array(
|
||||
JNIEnv* env,
|
||||
const std::vector<std::string>& values)
|
||||
{
|
||||
|
||||
explicit Deserializer(const std::string& input)
|
||||
{
|
||||
parse(input);
|
||||
if (!env) {
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
void parse(const std::string& input)
|
||||
{
|
||||
data.clear();
|
||||
|
||||
std::string key;
|
||||
std::string value;
|
||||
bool reading_key = true;
|
||||
bool escaped = false;
|
||||
|
||||
auto commit = [&]() {
|
||||
if (!key.empty()) {
|
||||
data[unescape(key)] = unescape(value);
|
||||
}
|
||||
key.clear();
|
||||
value.clear();
|
||||
reading_key = true;
|
||||
};
|
||||
|
||||
for (char c : input) {
|
||||
if (escaped) {
|
||||
(reading_key ? key : value) += c;
|
||||
escaped = false;
|
||||
}
|
||||
else if (c == '\\') {
|
||||
escaped = true;
|
||||
}
|
||||
else if (reading_key && c == '=') {
|
||||
reading_key = false;
|
||||
}
|
||||
else if (c == ';') {
|
||||
commit();
|
||||
}
|
||||
else {
|
||||
(reading_key ? key : value) += c;
|
||||
}
|
||||
}
|
||||
|
||||
commit();
|
||||
jclass string_class = env->FindClass("java/lang/String");
|
||||
if (!string_class) {
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
bool has(const std::string& key) const
|
||||
{
|
||||
return data.find(key) != data.end();
|
||||
jobjectArray result = env->NewObjectArray(
|
||||
static_cast<jsize>(values.size()),
|
||||
string_class,
|
||||
nullptr
|
||||
);
|
||||
|
||||
if (!result) {
|
||||
env->DeleteLocalRef(string_class);
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
T get(const std::string& key, T def) const
|
||||
{
|
||||
auto it = data.find(key);
|
||||
if (it == data.end()) {
|
||||
return def;
|
||||
for (jsize i = 0; i < static_cast<jsize>(values.size()); ++i) {
|
||||
jstring value = env->NewStringUTF(values[i].c_str());
|
||||
|
||||
if (!value) {
|
||||
env->DeleteLocalRef(result);
|
||||
env->DeleteLocalRef(string_class);
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
return convert<T>(it->second, def);
|
||||
}
|
||||
env->SetObjectArrayElement(result, i, value);
|
||||
env->DeleteLocalRef(value);
|
||||
|
||||
void clear()
|
||||
{
|
||||
data.clear();
|
||||
}
|
||||
|
||||
bool empty() const
|
||||
{
|
||||
return data.empty();
|
||||
}
|
||||
|
||||
std::size_t size() const
|
||||
{
|
||||
return data.size();
|
||||
}
|
||||
|
||||
private:
|
||||
static std::string unescape(const std::string& input)
|
||||
{
|
||||
std::string out;
|
||||
out.reserve(input.size());
|
||||
|
||||
bool escaped = false;
|
||||
|
||||
for (char c : input) {
|
||||
if (escaped) {
|
||||
out += c;
|
||||
escaped = false;
|
||||
}
|
||||
else if (c == '\\') {
|
||||
escaped = true;
|
||||
}
|
||||
else {
|
||||
out += c;
|
||||
}
|
||||
}
|
||||
|
||||
return out;
|
||||
}
|
||||
|
||||
static bool to_bool(const std::string& v, bool def)
|
||||
{
|
||||
if (v == "true" || v == "1") {
|
||||
return true;
|
||||
}
|
||||
if (v == "false" || v == "0") {
|
||||
return false;
|
||||
}
|
||||
return def;
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
static T convert(const std::string& v, T def)
|
||||
{
|
||||
if constexpr (std::is_same_v<T, std::string>) {
|
||||
return v;
|
||||
}
|
||||
else if constexpr (std::is_same_v<T, bool>) {
|
||||
return to_bool(v, def);
|
||||
}
|
||||
else if constexpr (std::is_integral_v<T>) {
|
||||
try {
|
||||
return static_cast<T>(std::stoll(v));
|
||||
}
|
||||
catch (...) {
|
||||
return def;
|
||||
}
|
||||
}
|
||||
else if constexpr (std::is_floating_point_v<T>) {
|
||||
try {
|
||||
return static_cast<T>(std::stold(v));
|
||||
}
|
||||
catch (...) {
|
||||
return def;
|
||||
}
|
||||
}
|
||||
else {
|
||||
return def;
|
||||
if (env->ExceptionCheck()) {
|
||||
env->DeleteLocalRef(result);
|
||||
env->DeleteLocalRef(string_class);
|
||||
return nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
std::unordered_map<std::string, std::string> data;
|
||||
};
|
||||
env->DeleteLocalRef(string_class);
|
||||
return result;
|
||||
}
|
||||
|
||||
inline std::string toDelimitedString(const std::vector<std::string>& values,
|
||||
const std::string& delimiter = ",")
|
||||
{
|
||||
std::string result;
|
||||
|
||||
for (const auto& value : values) {
|
||||
if (!result.empty()) {
|
||||
result += delimiter;
|
||||
}
|
||||
result += value;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
class File {
|
||||
public:
|
||||
|
||||
@@ -1,498 +0,0 @@
|
||||
// eventpp library
|
||||
// Copyright (C) 2018 Wang Qi (wqking)
|
||||
// Github: https://github.com/wqking/eventpp
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#ifndef CALLBACKLIST_H_588722158669
|
||||
#define CALLBACKLIST_H_588722158669
|
||||
|
||||
#include "eventpolicies.h"
|
||||
|
||||
#include <functional>
|
||||
#include <mutex>
|
||||
#include <cassert>
|
||||
|
||||
namespace eventpp {
|
||||
|
||||
namespace internal_ {
|
||||
|
||||
template <
|
||||
typename Prototype,
|
||||
typename PoliciesType
|
||||
>
|
||||
class CallbackListBase;
|
||||
|
||||
template <
|
||||
typename PoliciesType,
|
||||
typename ReturnType, typename ...Args
|
||||
>
|
||||
class CallbackListBase<
|
||||
ReturnType (Args...),
|
||||
PoliciesType
|
||||
>
|
||||
{
|
||||
private:
|
||||
using Policies = PoliciesType;
|
||||
|
||||
using Threading = typename SelectThreading<Policies, HasTypeThreading<Policies>::value>::Type;
|
||||
|
||||
using Callback_ = typename SelectCallback<
|
||||
Policies,
|
||||
HasTypeCallback<Policies>::value,
|
||||
std::function<ReturnType (Args...)>
|
||||
>::Type;
|
||||
|
||||
using CanContinueInvoking = typename SelectCanContinueInvoking<
|
||||
Policies, HasFunctionCanContinueInvoking<Policies, Args...>::value
|
||||
>::Type;
|
||||
|
||||
struct Node;
|
||||
using NodePtr = std::shared_ptr<Node>;
|
||||
|
||||
struct Node
|
||||
{
|
||||
using Counter = unsigned int;
|
||||
|
||||
Node(const Callback_ & callback, const Counter counter)
|
||||
: callback(callback), counter(counter)
|
||||
{
|
||||
}
|
||||
|
||||
NodePtr previous;
|
||||
NodePtr next;
|
||||
Callback_ callback;
|
||||
Counter counter;
|
||||
};
|
||||
|
||||
class Handle_ : public std::weak_ptr<Node>
|
||||
{
|
||||
private:
|
||||
using super = std::weak_ptr<Node>;
|
||||
|
||||
public:
|
||||
using super::super;
|
||||
|
||||
operator bool () const noexcept {
|
||||
return ! this->expired();
|
||||
}
|
||||
};
|
||||
|
||||
using Counter = typename Node::Counter;
|
||||
enum : Counter {
|
||||
removedCounter = 0
|
||||
};
|
||||
|
||||
public:
|
||||
using Callback = Callback_;
|
||||
using Handle = Handle_;
|
||||
using Mutex = typename Threading::Mutex;
|
||||
|
||||
public:
|
||||
CallbackListBase() noexcept
|
||||
:
|
||||
head(),
|
||||
tail(),
|
||||
mutex(),
|
||||
currentCounter(0)
|
||||
{
|
||||
}
|
||||
|
||||
CallbackListBase(const CallbackListBase & other)
|
||||
: CallbackListBase()
|
||||
{
|
||||
cloneFrom(other.head);
|
||||
}
|
||||
|
||||
CallbackListBase(CallbackListBase && other) noexcept
|
||||
: CallbackListBase()
|
||||
{
|
||||
swap(other);
|
||||
}
|
||||
|
||||
// If we use pass by value idiom and omit the 'this' check,
|
||||
// when assigning to self there is a deep copy which is inefficient.
|
||||
CallbackListBase & operator = (const CallbackListBase & other) {
|
||||
if(this != &other) {
|
||||
CallbackListBase copied(other);
|
||||
swap(copied);
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
CallbackListBase & operator = (CallbackListBase && other) noexcept {
|
||||
if(this != &other) {
|
||||
doFreeAllNodes();
|
||||
|
||||
head = std::move(other.head);
|
||||
tail = std::move(other.tail);
|
||||
currentCounter = other.currentCounter.load();
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
~CallbackListBase() {
|
||||
// Don't lock mutex here since it may throw exception
|
||||
|
||||
doFreeAllNodes();
|
||||
}
|
||||
|
||||
void swap(CallbackListBase & other) noexcept {
|
||||
using std::swap;
|
||||
|
||||
swap(head, other.head);
|
||||
swap(tail, other.tail);
|
||||
|
||||
const auto value = currentCounter.load();
|
||||
currentCounter.exchange(other.currentCounter.load());
|
||||
other.currentCounter.exchange(value);
|
||||
}
|
||||
|
||||
bool empty() const {
|
||||
// Don't lock the mutex for performance reason.
|
||||
// !head still works even when the underlying raw pointer is garbled (for other thread is writting to head)
|
||||
// And empty() doesn't guarantee the list is still empty after the function returned.
|
||||
//std::lock_guard<Mutex> lockGuard(mutex);
|
||||
|
||||
return ! head;
|
||||
}
|
||||
|
||||
operator bool() const {
|
||||
return ! empty();
|
||||
}
|
||||
|
||||
Handle append(const Callback & callback)
|
||||
{
|
||||
NodePtr node(doAllocateNode(callback));
|
||||
|
||||
std::lock_guard<Mutex> lockGuard(mutex);
|
||||
|
||||
if(head) {
|
||||
node->previous = tail;
|
||||
tail->next = node;
|
||||
tail = node;
|
||||
}
|
||||
else {
|
||||
head = node;
|
||||
tail = node;
|
||||
}
|
||||
|
||||
return Handle(node);
|
||||
}
|
||||
|
||||
Handle prepend(const Callback & callback)
|
||||
{
|
||||
NodePtr node(doAllocateNode(callback));
|
||||
|
||||
std::lock_guard<Mutex> lockGuard(mutex);
|
||||
|
||||
if(head) {
|
||||
node->next = head;
|
||||
head->previous = node;
|
||||
head = node;
|
||||
}
|
||||
else {
|
||||
head = node;
|
||||
tail = node;
|
||||
}
|
||||
|
||||
return Handle(node);
|
||||
}
|
||||
|
||||
Handle insert(const Callback & callback, const Handle & before)
|
||||
{
|
||||
// Disable this assertion because it's too slow in debug mode.
|
||||
//assert(before.expired() || ownsHandle(before));
|
||||
|
||||
NodePtr beforeNode = before.lock();
|
||||
if(beforeNode) {
|
||||
NodePtr node(doAllocateNode(callback));
|
||||
|
||||
std::lock_guard<Mutex> lockGuard(mutex);
|
||||
|
||||
doInsert(node, beforeNode);
|
||||
|
||||
return Handle(node);
|
||||
}
|
||||
|
||||
return append(callback);
|
||||
}
|
||||
|
||||
bool remove(const Handle & handle)
|
||||
{
|
||||
// Disable this assertion because it's too slow in debug mode.
|
||||
//assert(handle.expired() || ownsHandle(handle));
|
||||
|
||||
// It looks like the lock can be put inside the `if` below,
|
||||
// but that doesn't work in multi-threading and cause related unit tests fail.
|
||||
std::lock_guard<Mutex> lockGuard(mutex);
|
||||
|
||||
auto node = handle.lock();
|
||||
if(node) {
|
||||
doFreeNode(node);
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
bool ownsHandle(const Handle & handle) const
|
||||
{
|
||||
std::lock_guard<Mutex> lockGuard(mutex);
|
||||
|
||||
auto node = handle.lock();
|
||||
if(node) {
|
||||
while(node->previous) {
|
||||
node = node->previous;
|
||||
}
|
||||
return node == head;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
template <typename Func>
|
||||
void forEach(Func && func) const
|
||||
{
|
||||
doForEachIf([&func, this](NodePtr & node) -> bool {
|
||||
doForEachInvoke<void>(func, node);
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
template <typename Func>
|
||||
bool forEachIf(Func && func) const
|
||||
{
|
||||
return doForEachIf([&func, this](NodePtr & node) -> bool {
|
||||
return doForEachInvoke<bool>(func, node);
|
||||
});
|
||||
}
|
||||
|
||||
#if !defined(__GNUC__) || __GNUC__ >= 5
|
||||
void operator() (Args ...args) const
|
||||
{
|
||||
forEachIf([&args...](Callback & callback) -> bool {
|
||||
// We can't use std::forward here, because if we use std::forward,
|
||||
// for arg that is passed by value, and the callback prototype accepts it by value,
|
||||
// std::forward will move it and may cause the original value invalid.
|
||||
// That happens on any value-to-value passing, no matter the callback moves it or not.
|
||||
|
||||
callback(args...);
|
||||
return CanContinueInvoking::canContinueInvoking(args...);
|
||||
});
|
||||
}
|
||||
#else
|
||||
// This is a patch version for GCC 4. It inlines the unrolled doForEachIf.
|
||||
// GCC 4.8.3 doesn't supporting parameter pack catpure in lambda, see,
|
||||
// https://github.com/wqking/eventpp/issues/19
|
||||
// This is a compromised patch for GCC 4, it may be not maintained or updated unless there are bugs.
|
||||
// We don't use the patch as main code because the patch generates longer code, and duplicated with doForEachIf.
|
||||
void operator() (Args ...args) const
|
||||
{
|
||||
NodePtr node;
|
||||
|
||||
{
|
||||
std::lock_guard<Mutex> lockGuard(mutex);
|
||||
node = head;
|
||||
}
|
||||
|
||||
const Counter counter = currentCounter.load(std::memory_order_acquire);
|
||||
|
||||
while(node) {
|
||||
if(node->counter != removedCounter && counter >= node->counter) {
|
||||
node->callback(args...);
|
||||
if(! CanContinueInvoking::canContinueInvoking(args...)) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
{
|
||||
std::lock_guard<Mutex> lockGuard(mutex);
|
||||
node = node->next;
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
private:
|
||||
template <typename F>
|
||||
bool doForEachIf(F && f) const
|
||||
{
|
||||
NodePtr node;
|
||||
|
||||
{
|
||||
std::lock_guard<Mutex> lockGuard(mutex);
|
||||
node = head;
|
||||
}
|
||||
|
||||
const Counter counter = currentCounter.load(std::memory_order_acquire);
|
||||
|
||||
while(node) {
|
||||
if(node->counter != removedCounter && counter >= node->counter) {
|
||||
if(! f(node)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
{
|
||||
std::lock_guard<Mutex> lockGuard(mutex);
|
||||
node = node->next;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
template <typename RT, typename Func>
|
||||
auto doForEachInvoke(Func && func, NodePtr & node) const
|
||||
-> typename std::enable_if<CanInvoke<Func, Handle, Callback &>::value, RT>::type
|
||||
{
|
||||
return func(Handle(node), node->callback);
|
||||
}
|
||||
|
||||
template <typename RT, typename Func>
|
||||
auto doForEachInvoke(Func && func, NodePtr & node) const
|
||||
-> typename std::enable_if<CanInvoke<Func, Callback &>::value, RT>::type
|
||||
{
|
||||
return func(node->callback);
|
||||
}
|
||||
|
||||
void doInsert(NodePtr & node, NodePtr & beforeNode)
|
||||
{
|
||||
node->previous = beforeNode->previous;
|
||||
node->next = beforeNode;
|
||||
if(beforeNode->previous) {
|
||||
beforeNode->previous->next = node;
|
||||
}
|
||||
beforeNode->previous = node;
|
||||
|
||||
if(beforeNode == head) {
|
||||
head = node;
|
||||
}
|
||||
}
|
||||
|
||||
NodePtr doAllocateNode(const Callback & callback)
|
||||
{
|
||||
return std::make_shared<Node>(callback, getNextCounter());
|
||||
}
|
||||
|
||||
void doFreeNode(NodePtr & node)
|
||||
{
|
||||
if(node->next) {
|
||||
node->next->previous = node->previous;
|
||||
}
|
||||
if(node->previous) {
|
||||
node->previous->next = node->next;
|
||||
}
|
||||
|
||||
// Mark it as deleted, this must be before the assignment of head and tail below,
|
||||
// because node can be a reference to head or tail, and after the assignment, node
|
||||
// can be null pointer.
|
||||
node->counter = removedCounter;
|
||||
|
||||
if(head == node) {
|
||||
head = node->next;
|
||||
}
|
||||
if(tail == node) {
|
||||
tail = node->previous;
|
||||
}
|
||||
|
||||
// don't modify node->previous or node->next
|
||||
// because node may be still used in a loop.
|
||||
}
|
||||
|
||||
void doFreeAllNodes() {
|
||||
NodePtr node = head;
|
||||
head.reset();
|
||||
while(node) {
|
||||
NodePtr next = node->next;
|
||||
node->previous.reset();
|
||||
node->next.reset();
|
||||
node = next;
|
||||
}
|
||||
node.reset();
|
||||
}
|
||||
|
||||
Counter getNextCounter()
|
||||
{
|
||||
Counter result = ++currentCounter;;
|
||||
if(result == 0) { // overflow, let's reset all nodes' counters.
|
||||
{
|
||||
std::lock_guard<Mutex> lockGuard(mutex);
|
||||
NodePtr node = head;
|
||||
while(node) {
|
||||
node->counter = 1;
|
||||
node = node->next;
|
||||
}
|
||||
}
|
||||
result = ++currentCounter;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
void cloneFrom(const NodePtr & fromHead) {
|
||||
NodePtr fromNode(fromHead);
|
||||
NodePtr node;
|
||||
const Counter counter = getNextCounter();
|
||||
while(fromNode) {
|
||||
const NodePtr nextNode(std::make_shared<Node>(fromNode->callback, counter));
|
||||
|
||||
nextNode->previous = node;
|
||||
|
||||
if(node) {
|
||||
node->next = nextNode;
|
||||
}
|
||||
else {
|
||||
node = nextNode;
|
||||
head = node;
|
||||
}
|
||||
|
||||
node = nextNode;
|
||||
fromNode = fromNode->next;
|
||||
}
|
||||
|
||||
tail = node;
|
||||
}
|
||||
|
||||
private:
|
||||
NodePtr head;
|
||||
NodePtr tail;
|
||||
mutable Mutex mutex;
|
||||
typename Threading::template Atomic<Counter> currentCounter;
|
||||
|
||||
};
|
||||
|
||||
|
||||
} //namespace internal_
|
||||
|
||||
|
||||
template <
|
||||
typename Prototype_,
|
||||
typename Policies_ = DefaultPolicies
|
||||
>
|
||||
class CallbackList : public internal_::CallbackListBase<Prototype_, Policies_>, public TagCallbackList
|
||||
{
|
||||
private:
|
||||
using super = internal_::CallbackListBase<Prototype_, Policies_>;
|
||||
|
||||
public:
|
||||
using super::super;
|
||||
|
||||
friend void swap(CallbackList & first, CallbackList & second) noexcept {
|
||||
first.swap(second);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
} //namespace eventpp
|
||||
|
||||
|
||||
#endif
|
||||
@@ -1,328 +0,0 @@
|
||||
// eventpp library
|
||||
// Copyright (C) 2018 Wang Qi (wqking)
|
||||
// Github: https://github.com/wqking/eventpp
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#ifndef EVENTDISPATCHER_H_319010983013
|
||||
#define EVENTDISPATCHER_H_319010983013
|
||||
|
||||
#include "callbacklist.h"
|
||||
|
||||
namespace eventpp {
|
||||
|
||||
namespace internal_ {
|
||||
|
||||
template <
|
||||
typename EventType_,
|
||||
typename Prototype_,
|
||||
typename Policies_,
|
||||
typename MixinRoot_
|
||||
>
|
||||
class EventDispatcherBase;
|
||||
|
||||
template <
|
||||
typename EventType_,
|
||||
typename Policies_,
|
||||
typename MixinRoot_,
|
||||
typename ReturnType, typename ...Args
|
||||
>
|
||||
class EventDispatcherBase <
|
||||
EventType_,
|
||||
ReturnType (Args...),
|
||||
Policies_,
|
||||
MixinRoot_
|
||||
>
|
||||
{
|
||||
protected:
|
||||
using ThisType = EventDispatcherBase<
|
||||
EventType_,
|
||||
ReturnType (Args...),
|
||||
Policies_,
|
||||
MixinRoot_
|
||||
>;
|
||||
using MixinRoot = typename std::conditional<
|
||||
std::is_same<MixinRoot_, void>::value,
|
||||
ThisType,
|
||||
MixinRoot_
|
||||
>::type;
|
||||
using Policies = Policies_;
|
||||
|
||||
using Threading = typename SelectThreading<Policies_, HasTypeThreading<Policies_>::value>::Type;
|
||||
|
||||
using ArgumentPassingMode = typename SelectArgumentPassingMode<
|
||||
Policies_,
|
||||
HasTypeArgumentPassingMode<Policies_>::value,
|
||||
ArgumentPassingAutoDetect
|
||||
>::Type;
|
||||
|
||||
using Callback_ = typename SelectCallback<
|
||||
Policies_,
|
||||
HasTypeCallback<Policies_>::value,
|
||||
std::function<ReturnType (Args...)>
|
||||
>::Type;
|
||||
using CallbackList_ = CallbackList<ReturnType (Args...), Policies_>;
|
||||
|
||||
using Prototype = ReturnType (Args...);
|
||||
|
||||
using Map = typename SelectMap<
|
||||
EventType_,
|
||||
CallbackList_,
|
||||
Policies_,
|
||||
HasTemplateMap<Policies_>::value
|
||||
>::Type;
|
||||
|
||||
using Mixins = typename internal_::SelectMixins<
|
||||
Policies_,
|
||||
internal_::HasTypeMixins<Policies_>::value
|
||||
>::Type;
|
||||
|
||||
public:
|
||||
using Handle = typename CallbackList_::Handle;
|
||||
using Callback = Callback_;
|
||||
using Event = EventType_;
|
||||
using Mutex = typename Threading::Mutex;
|
||||
|
||||
public:
|
||||
EventDispatcherBase()
|
||||
:
|
||||
eventCallbackListMap(),
|
||||
listenerMutex()
|
||||
{
|
||||
}
|
||||
|
||||
EventDispatcherBase(const EventDispatcherBase & other)
|
||||
:
|
||||
eventCallbackListMap(other.eventCallbackListMap),
|
||||
listenerMutex()
|
||||
{
|
||||
}
|
||||
|
||||
EventDispatcherBase(EventDispatcherBase && other) noexcept
|
||||
:
|
||||
eventCallbackListMap(std::move(other.eventCallbackListMap)),
|
||||
listenerMutex()
|
||||
{
|
||||
}
|
||||
|
||||
EventDispatcherBase & operator = (const EventDispatcherBase & other)
|
||||
{
|
||||
eventCallbackListMap = other.eventCallbackListMap;
|
||||
return *this;
|
||||
}
|
||||
|
||||
EventDispatcherBase & operator = (EventDispatcherBase && other) noexcept
|
||||
{
|
||||
eventCallbackListMap = std::move(other.eventCallbackListMap);
|
||||
return *this;
|
||||
}
|
||||
|
||||
void swap(EventDispatcherBase & other) noexcept {
|
||||
using std::swap;
|
||||
|
||||
swap(eventCallbackListMap, other.eventCallbackListMap);
|
||||
}
|
||||
|
||||
Handle appendListener(const Event & event, const Callback & callback)
|
||||
{
|
||||
std::lock_guard<Mutex> lockGuard(listenerMutex);
|
||||
|
||||
return eventCallbackListMap[event].append(callback);
|
||||
}
|
||||
|
||||
Handle prependListener(const Event & event, const Callback & callback)
|
||||
{
|
||||
std::lock_guard<Mutex> lockGuard(listenerMutex);
|
||||
|
||||
return eventCallbackListMap[event].prepend(callback);
|
||||
}
|
||||
|
||||
Handle insertListener(const Event & event, const Callback & callback, const Handle & before)
|
||||
{
|
||||
std::lock_guard<Mutex> lockGuard(listenerMutex);
|
||||
|
||||
return eventCallbackListMap[event].insert(callback, before);
|
||||
}
|
||||
|
||||
bool removeListener(const Event & event, const Handle handle)
|
||||
{
|
||||
CallbackList_ * callableList = doFindCallableList(event);
|
||||
if(callableList) {
|
||||
return callableList->remove(handle);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
bool hasAnyListener(const Event & event) const
|
||||
{
|
||||
const CallbackList_ * callableList = doFindCallableList(event);
|
||||
if(callableList) {
|
||||
return ! callableList->empty();
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
bool ownsHandle(const Event & event, const Handle & handle) const
|
||||
{
|
||||
const CallbackList_ * callableList = doFindCallableList(event);
|
||||
if(callableList) {
|
||||
return callableList->ownsHandle(handle);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
template <typename Func>
|
||||
void forEach(const Event & event, Func && func) const
|
||||
{
|
||||
const CallbackList_ * callableList = doFindCallableList(event);
|
||||
if(callableList) {
|
||||
callableList->forEach(std::forward<Func>(func));
|
||||
}
|
||||
}
|
||||
|
||||
template <typename Func>
|
||||
bool forEachIf(const Event & event, Func && func) const
|
||||
{
|
||||
const CallbackList_ * callableList = doFindCallableList(event);
|
||||
if (callableList) {
|
||||
return callableList->forEachIf(std::forward<Func>(func));
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
void dispatch(Args ...args) const
|
||||
{
|
||||
static_assert(ArgumentPassingMode::canIncludeEventType, "Dispatching arguments count doesn't match required (Event type should be included).");
|
||||
|
||||
using GetEvent = typename SelectGetEvent<Policies_, EventType_, HasFunctionGetEvent<Policies_, Args...>::value>::Type;
|
||||
|
||||
// can't std::forward<Args>(args) in GetEvent::getEvent because the pass by value arguments will be moved to getEvent
|
||||
// then the other std::forward<Args>(args) to directDispatch will get empty values.
|
||||
directDispatch(
|
||||
GetEvent::getEvent(args...),
|
||||
std::forward<Args>(args)...
|
||||
);
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
void dispatch(T && first, Args ...args) const
|
||||
{
|
||||
static_assert(ArgumentPassingMode::canExcludeEventType, "Dispatching arguments count doesn't match required (Event type should NOT be included).");
|
||||
|
||||
using GetEvent = typename SelectGetEvent<Policies_, EventType_, HasFunctionGetEvent<Policies_, T &&, Args...>::value>::Type;
|
||||
|
||||
directDispatch(
|
||||
GetEvent::getEvent(std::forward<T>(first), args...),
|
||||
std::forward<Args>(args)...
|
||||
);
|
||||
}
|
||||
|
||||
// Bypass any getEvent policy. The first argument is the event type.
|
||||
// Most used for internal purpose.
|
||||
void directDispatch(const Event & e, Args ...args) const
|
||||
{
|
||||
if(! internal_::ForEachMixins<MixinRoot, Mixins, DoMixinBeforeDispatch>::forEach(
|
||||
this, typename std::add_lvalue_reference<Args>::type(args)...)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const CallbackList_ * callableList = doFindCallableList(e);
|
||||
if(callableList) {
|
||||
(*callableList)(std::forward<Args>(args)...);
|
||||
}
|
||||
}
|
||||
|
||||
protected:
|
||||
const CallbackList_ * doFindCallableList(const Event & e) const
|
||||
{
|
||||
return doFindCallableListHelper(this, e);
|
||||
}
|
||||
|
||||
CallbackList_ * doFindCallableList(const Event & e)
|
||||
{
|
||||
return doFindCallableListHelper(this, e);
|
||||
}
|
||||
|
||||
private:
|
||||
// template helper to avoid code duplication in doFindCallableList
|
||||
template <typename T>
|
||||
static auto doFindCallableListHelper(T * self, const Event & e)
|
||||
-> typename std::conditional<std::is_const<T>::value, const CallbackList_ *, CallbackList_ *>::type
|
||||
{
|
||||
std::lock_guard<Mutex> lockGuard(self->listenerMutex);
|
||||
|
||||
auto it = self->eventCallbackListMap.find(e);
|
||||
if(it != self->eventCallbackListMap.end()) {
|
||||
return &it->second;
|
||||
}
|
||||
else {
|
||||
return nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
// Mixin related
|
||||
struct DoMixinBeforeDispatch
|
||||
{
|
||||
template <typename T, typename Self, typename ...A>
|
||||
static auto forEach(const Self * self, A && ...args)
|
||||
-> typename std::enable_if<HasFunctionMixinBeforeDispatch<T, A...>::value, bool>::type {
|
||||
return static_cast<const T *>(self)->mixinBeforeDispatch(std::forward<A>(args)...);
|
||||
}
|
||||
|
||||
template <typename T, typename Self, typename ...A>
|
||||
static auto forEach(const Self * /*self*/, A && ... /*args*/)
|
||||
-> typename std::enable_if<! HasFunctionMixinBeforeDispatch<T, A...>::value, bool>::type {
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
private:
|
||||
Map eventCallbackListMap;
|
||||
mutable Mutex listenerMutex;
|
||||
};
|
||||
|
||||
|
||||
} //namespace internal_
|
||||
|
||||
template <
|
||||
typename Event_,
|
||||
typename Prototype_,
|
||||
typename Policies_ = DefaultPolicies
|
||||
>
|
||||
class EventDispatcher : public internal_::InheritMixins<
|
||||
internal_::EventDispatcherBase<Event_, Prototype_, Policies_, void>,
|
||||
typename internal_::SelectMixins<Policies_, internal_::HasTypeMixins<Policies_>::value >::Type
|
||||
>::Type, public TagEventDispatcher
|
||||
{
|
||||
private:
|
||||
using super = typename internal_::InheritMixins<
|
||||
internal_::EventDispatcherBase<Event_, Prototype_, Policies_, void>,
|
||||
typename internal_::SelectMixins<Policies_, internal_::HasTypeMixins<Policies_>::value >::Type
|
||||
>::Type;
|
||||
|
||||
public:
|
||||
using super::super;
|
||||
|
||||
friend void swap(EventDispatcher & first, EventDispatcher & second) noexcept {
|
||||
first.swap(second);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
} //namespace eventpp
|
||||
|
||||
|
||||
#endif
|
||||
|
||||
@@ -1,186 +0,0 @@
|
||||
// eventpp library
|
||||
// Copyright (C) 2018 Wang Qi (wqking)
|
||||
// Github: https://github.com/wqking/eventpp
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#ifndef EVENTOPTIONS_H_730367862613
|
||||
#define EVENTOPTIONS_H_730367862613
|
||||
|
||||
#include "internal/typeutil_i.h"
|
||||
|
||||
#include <atomic>
|
||||
#include <condition_variable>
|
||||
#include <map>
|
||||
#include <unordered_map>
|
||||
#include <list>
|
||||
|
||||
namespace eventpp {
|
||||
|
||||
struct TagHomo {};
|
||||
struct TagCallbackList : public TagHomo {};
|
||||
struct TagEventDispatcher : public TagHomo {};
|
||||
struct TagEventQueue : public TagHomo {};
|
||||
|
||||
struct TagHeter {};
|
||||
struct TagHeterCallbackList : public TagHeter {};
|
||||
struct TagHeterEventDispatcher : public TagHeter {};
|
||||
struct TagHeterEventQueue : public TagHeter {};
|
||||
|
||||
struct SpinLock
|
||||
{
|
||||
public:
|
||||
void lock() {
|
||||
while(locked.test_and_set(std::memory_order_acquire)) {
|
||||
}
|
||||
}
|
||||
|
||||
void unlock() {
|
||||
locked.clear(std::memory_order_release);
|
||||
}
|
||||
|
||||
private:
|
||||
std::atomic_flag locked = ATOMIC_FLAG_INIT;
|
||||
};
|
||||
|
||||
template <
|
||||
typename Mutex_,
|
||||
template <typename > class Atomic_ = std::atomic,
|
||||
typename ConditionVariable_ = std::condition_variable
|
||||
>
|
||||
struct GeneralThreading
|
||||
{
|
||||
using Mutex = Mutex_;
|
||||
|
||||
template <typename T>
|
||||
using Atomic = Atomic_<T>;
|
||||
|
||||
using ConditionVariable = ConditionVariable_;
|
||||
};
|
||||
|
||||
struct MultipleThreading
|
||||
{
|
||||
using Mutex = std::mutex;
|
||||
|
||||
template <typename T>
|
||||
using Atomic = std::atomic<T>;
|
||||
|
||||
using ConditionVariable = std::condition_variable;
|
||||
};
|
||||
|
||||
struct SingleThreading
|
||||
{
|
||||
struct Mutex
|
||||
{
|
||||
void lock() {}
|
||||
void unlock() {}
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
struct Atomic
|
||||
{
|
||||
Atomic() noexcept = default;
|
||||
constexpr Atomic(T desired) noexcept
|
||||
: value(desired)
|
||||
{
|
||||
}
|
||||
|
||||
void store(T desired, std::memory_order /*order*/ = std::memory_order_seq_cst) noexcept
|
||||
{
|
||||
value = desired;
|
||||
}
|
||||
|
||||
T load(std::memory_order /*order*/ = std::memory_order_seq_cst) const noexcept
|
||||
{
|
||||
return value;
|
||||
}
|
||||
|
||||
T exchange(T desired, std::memory_order /*order*/ = std::memory_order_seq_cst) noexcept
|
||||
{
|
||||
const T previous = value;
|
||||
value = desired;
|
||||
return previous;
|
||||
}
|
||||
|
||||
T operator ++ () noexcept
|
||||
{
|
||||
return ++value;
|
||||
}
|
||||
|
||||
T operator -- () noexcept
|
||||
{
|
||||
return --value;
|
||||
}
|
||||
|
||||
T value;
|
||||
};
|
||||
|
||||
struct ConditionVariable
|
||||
{
|
||||
void notify_one() noexcept
|
||||
{
|
||||
}
|
||||
|
||||
template <class Predicate>
|
||||
void wait(std::unique_lock<std::mutex> & /*lock*/, Predicate /*pred*/)
|
||||
{
|
||||
}
|
||||
|
||||
template <class Rep, class Period, class Predicate>
|
||||
bool wait_for(std::unique_lock<std::mutex> & /*lock*/,
|
||||
const std::chrono::duration<Rep, Period> & /*rel_time*/,
|
||||
Predicate /*pred*/
|
||||
)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
struct ArgumentPassingAutoDetect
|
||||
{
|
||||
enum {
|
||||
canIncludeEventType = true,
|
||||
canExcludeEventType = true
|
||||
};
|
||||
};
|
||||
|
||||
struct ArgumentPassingIncludeEvent
|
||||
{
|
||||
enum {
|
||||
canIncludeEventType = true,
|
||||
canExcludeEventType = false
|
||||
};
|
||||
};
|
||||
|
||||
struct ArgumentPassingExcludeEvent
|
||||
{
|
||||
enum {
|
||||
canIncludeEventType = false,
|
||||
canExcludeEventType = true
|
||||
};
|
||||
};
|
||||
|
||||
struct DefaultPolicies
|
||||
{
|
||||
};
|
||||
|
||||
template <template <typename> class ...Mixins>
|
||||
struct MixinList
|
||||
{
|
||||
};
|
||||
|
||||
#include "internal/eventpolicies_i.h"
|
||||
|
||||
|
||||
} //namespace eventpp
|
||||
|
||||
|
||||
#endif
|
||||
@@ -1,561 +0,0 @@
|
||||
// eventpp library
|
||||
// Copyright (C) 2018 Wang Qi (wqking)
|
||||
// Github: https://github.com/wqking/eventpp
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#ifndef EVENTQUEUE_H_705786053037
|
||||
#define EVENTQUEUE_H_705786053037
|
||||
|
||||
#include "eventdispatcher.h"
|
||||
#include "internal/eventqueue_i.h"
|
||||
|
||||
#include <tuple>
|
||||
#include <chrono>
|
||||
|
||||
namespace eventpp {
|
||||
|
||||
namespace internal_ {
|
||||
|
||||
template <
|
||||
typename EventType_,
|
||||
typename Prototype_,
|
||||
typename Policies_
|
||||
>
|
||||
class EventQueueBase;
|
||||
|
||||
template <
|
||||
typename EventType_,
|
||||
typename Policies_,
|
||||
typename ReturnType, typename ...Args
|
||||
>
|
||||
class EventQueueBase <
|
||||
EventType_,
|
||||
ReturnType (Args...),
|
||||
Policies_
|
||||
> : public EventDispatcherBase<
|
||||
EventType_,
|
||||
ReturnType (Args...),
|
||||
Policies_,
|
||||
EventQueueBase <
|
||||
EventType_,
|
||||
ReturnType (Args...),
|
||||
Policies_
|
||||
>
|
||||
>
|
||||
{
|
||||
private:
|
||||
using super = EventDispatcherBase<
|
||||
EventType_,
|
||||
ReturnType (Args...),
|
||||
Policies_,
|
||||
EventQueueBase <
|
||||
EventType_,
|
||||
ReturnType (Args...),
|
||||
Policies_
|
||||
>
|
||||
>;
|
||||
|
||||
using Policies = typename super::Policies;
|
||||
using Threading = typename super::Threading;
|
||||
using ConditionVariable = typename Threading::ConditionVariable;
|
||||
|
||||
using QueuedEventArgumentsType = std::tuple<typename std::decay<Args>::type...>;
|
||||
|
||||
struct QueuedEvent_
|
||||
{
|
||||
typename std::decay<typename super::Event>::type event;
|
||||
QueuedEventArgumentsType arguments;
|
||||
|
||||
typename super::Event getEvent() const {
|
||||
return event;
|
||||
}
|
||||
|
||||
template <std::size_t N>
|
||||
auto getArgument() const
|
||||
-> typename std::tuple_element<N, std::tuple<Args...> >::type {
|
||||
return std::get<N>(arguments);
|
||||
}
|
||||
};
|
||||
|
||||
using BufferedItemList = typename SelectQueueList<
|
||||
BufferedItem<QueuedEvent_>,
|
||||
Policies_,
|
||||
HasTemplateQueueList<Policies_>::value
|
||||
>::Type;
|
||||
|
||||
public:
|
||||
using QueuedEvent = QueuedEvent_;
|
||||
using Event = typename super::Event;
|
||||
using Handle = typename super::Handle;
|
||||
using Callback = typename super::Callback;
|
||||
using Mutex = typename super::Mutex;
|
||||
|
||||
struct DisableQueueNotify
|
||||
{
|
||||
DisableQueueNotify(EventQueueBase * queue)
|
||||
: queue(queue)
|
||||
{
|
||||
++queue->queueNotifyCounter;
|
||||
}
|
||||
|
||||
~DisableQueueNotify()
|
||||
{
|
||||
--queue->queueNotifyCounter;
|
||||
|
||||
if(queue->doCanNotifyQueueAvailable() && ! queue->emptyQueue()) {
|
||||
queue->queueListConditionVariable.notify_one();
|
||||
}
|
||||
}
|
||||
|
||||
EventQueueBase * queue;
|
||||
};
|
||||
|
||||
public:
|
||||
EventQueueBase()
|
||||
:
|
||||
super(),
|
||||
queueListConditionVariable(),
|
||||
queueEmptyCounter(0),
|
||||
queueNotifyCounter(0),
|
||||
queueListMutex(),
|
||||
queueList(),
|
||||
freeListMutex(),
|
||||
freeList()
|
||||
{
|
||||
}
|
||||
|
||||
EventQueueBase(const EventQueueBase & other)
|
||||
: super(other)
|
||||
{
|
||||
}
|
||||
|
||||
EventQueueBase(EventQueueBase && other) noexcept
|
||||
: super(std::move(other))
|
||||
{
|
||||
}
|
||||
|
||||
EventQueueBase & operator = (const EventQueueBase & other)
|
||||
{
|
||||
super::operator = (other);
|
||||
return *this;
|
||||
}
|
||||
|
||||
EventQueueBase & operator = (EventQueueBase && other) noexcept
|
||||
{
|
||||
super::operator = (std::move(other));
|
||||
return *this;
|
||||
}
|
||||
|
||||
template <typename ...A>
|
||||
auto enqueue(A && ...args) -> typename std::enable_if<sizeof...(A) == sizeof...(Args), void>::type
|
||||
{
|
||||
static_assert(super::ArgumentPassingMode::canIncludeEventType, "Enqueuing arguments count doesn't match required (Event type should be included).");
|
||||
|
||||
using GetEvent = typename SelectGetEvent<Policies_, EventType_, HasFunctionGetEvent<Policies_, A...>::value>::Type;
|
||||
|
||||
doEnqueue(QueuedEvent{
|
||||
GetEvent::getEvent(args...),
|
||||
QueuedEventArgumentsType(std::forward<A>(args)...)
|
||||
});
|
||||
|
||||
if(doCanProcess()) {
|
||||
queueListConditionVariable.notify_one();
|
||||
}
|
||||
}
|
||||
|
||||
template <typename T, typename ...A>
|
||||
auto enqueue(T && first, A && ...args) -> typename std::enable_if<sizeof...(A) == sizeof...(Args), void>::type
|
||||
{
|
||||
static_assert(super::ArgumentPassingMode::canExcludeEventType, "Enqueuing arguments count doesn't match required (Event type should NOT be included).");
|
||||
|
||||
using GetEvent = typename SelectGetEvent<Policies_, EventType_, HasFunctionGetEvent<Policies_, T &&, A...>::value>::Type;
|
||||
|
||||
doEnqueue(QueuedEvent{
|
||||
GetEvent::getEvent(std::forward<T>(first), args...),
|
||||
QueuedEventArgumentsType(std::forward<A>(args)...)
|
||||
});
|
||||
|
||||
if(doCanProcess()) {
|
||||
queueListConditionVariable.notify_one();
|
||||
}
|
||||
}
|
||||
|
||||
bool emptyQueue() const
|
||||
{
|
||||
return queueList.empty() && (queueEmptyCounter.load(std::memory_order_acquire) == 0);
|
||||
}
|
||||
|
||||
void clearEvents()
|
||||
{
|
||||
if(! queueList.empty()) {
|
||||
BufferedItemList tempList;
|
||||
|
||||
{
|
||||
std::lock_guard<Mutex> queueListLock(queueListMutex);
|
||||
std::swap(queueList, tempList);
|
||||
}
|
||||
|
||||
if(! tempList.empty()) {
|
||||
for(auto & item : tempList) {
|
||||
item.clear();
|
||||
}
|
||||
|
||||
std::lock_guard<Mutex> queueListLock(freeListMutex);
|
||||
freeList.splice(freeList.end(), tempList);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bool process()
|
||||
{
|
||||
if(! queueList.empty()) {
|
||||
BufferedItemList tempList;
|
||||
|
||||
// Use a counter to tell the queue list is not empty during processing
|
||||
// even though queueList is swapped to empty.
|
||||
CounterGuard<decltype(queueEmptyCounter)> counterGuard(queueEmptyCounter);
|
||||
|
||||
{
|
||||
std::lock_guard<Mutex> queueListLock(queueListMutex);
|
||||
std::swap(queueList, tempList);
|
||||
}
|
||||
|
||||
if(! tempList.empty()) {
|
||||
for(auto & item : tempList) {
|
||||
doDispatchQueuedEvent(
|
||||
item.get(),
|
||||
typename MakeIndexSequence<sizeof...(Args)>::Type()
|
||||
);
|
||||
item.clear();
|
||||
}
|
||||
|
||||
std::lock_guard<Mutex> queueListLock(freeListMutex);
|
||||
freeList.splice(freeList.end(), tempList);
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
bool processOne()
|
||||
{
|
||||
if(! queueList.empty()) {
|
||||
BufferedItemList tempList;
|
||||
|
||||
// Use a counter to tell the queue list is not empty during processing
|
||||
// even though queueList is swapped to empty.
|
||||
CounterGuard<decltype(queueEmptyCounter)> counterGuard(queueEmptyCounter);
|
||||
|
||||
{
|
||||
std::lock_guard<Mutex> queueListLock(queueListMutex);
|
||||
if(! queueList.empty()) {
|
||||
tempList.splice(tempList.end(), queueList, queueList.begin());
|
||||
}
|
||||
}
|
||||
|
||||
if(! tempList.empty()) {
|
||||
auto & item = tempList.front();
|
||||
doDispatchQueuedEvent(
|
||||
item.get(),
|
||||
typename MakeIndexSequence<sizeof...(Args)>::Type()
|
||||
);
|
||||
item.clear();
|
||||
|
||||
std::lock_guard<Mutex> queueListLock(freeListMutex);
|
||||
freeList.splice(freeList.end(), tempList);
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
template <typename Predictor>
|
||||
bool processIf(Predictor && predictor)
|
||||
{
|
||||
if(! queueList.empty()) {
|
||||
BufferedItemList tempList;
|
||||
BufferedItemList idleList;
|
||||
|
||||
// Use a counter to tell the queue list is not empty during processing
|
||||
// even though queueList is swapped to empty.
|
||||
CounterGuard<decltype(queueEmptyCounter)> counterGuard(queueEmptyCounter);
|
||||
|
||||
{
|
||||
std::lock_guard<Mutex> queueListLock(queueListMutex);
|
||||
std::swap(queueList, tempList);
|
||||
}
|
||||
|
||||
if(! tempList.empty()) {
|
||||
for(auto it = tempList.begin(); it != tempList.end(); ) {
|
||||
if(doInvokeFuncWithQueuedEvent(
|
||||
predictor,
|
||||
it->get(),
|
||||
typename MakeIndexSequence<sizeof...(Args)>::Type())
|
||||
) {
|
||||
doDispatchQueuedEvent(
|
||||
it->get(),
|
||||
typename MakeIndexSequence<sizeof...(Args)>::Type()
|
||||
);
|
||||
it->clear();
|
||||
|
||||
auto tempIt = it;
|
||||
++it;
|
||||
idleList.splice(idleList.end(), tempList, tempIt);
|
||||
}
|
||||
else {
|
||||
++it;
|
||||
}
|
||||
}
|
||||
|
||||
if (! tempList.empty()) {
|
||||
std::lock_guard<Mutex> queueListLock(queueListMutex);
|
||||
queueList.splice(queueList.begin(), tempList);
|
||||
}
|
||||
|
||||
if(! idleList.empty()) {
|
||||
std::lock_guard<Mutex> queueListLock(freeListMutex);
|
||||
freeList.splice(freeList.end(), idleList);
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
template <typename Predictor>
|
||||
bool processUntil(Predictor && predictor)
|
||||
{
|
||||
if(! queueList.empty()) {
|
||||
BufferedItemList tempList;
|
||||
BufferedItemList idleList;
|
||||
|
||||
// Use a counter to tell the queue list is not empty during processing
|
||||
// even though queueList is swapped to empty.
|
||||
CounterGuard<decltype(queueEmptyCounter)> counterGuard(queueEmptyCounter);
|
||||
|
||||
{
|
||||
std::lock_guard<Mutex> queueListLock(queueListMutex);
|
||||
std::swap(queueList, tempList);
|
||||
}
|
||||
|
||||
if(! tempList.empty()) {
|
||||
for(auto it = tempList.begin(); it != tempList.end(); ) {
|
||||
if(doInvokeFuncWithQueuedEvent(
|
||||
predictor,
|
||||
it->get(),
|
||||
typename MakeIndexSequence<sizeof...(Args)>::Type())
|
||||
) {
|
||||
break;
|
||||
}
|
||||
else {
|
||||
doDispatchQueuedEvent(
|
||||
it->get(),
|
||||
typename MakeIndexSequence<sizeof...(Args)>::Type()
|
||||
);
|
||||
it->clear();
|
||||
|
||||
auto tempIt = it;
|
||||
++it;
|
||||
idleList.splice(idleList.end(), tempList, tempIt);
|
||||
}
|
||||
}
|
||||
|
||||
if (! tempList.empty()) {
|
||||
std::lock_guard<Mutex> queueListLock(queueListMutex);
|
||||
queueList.splice(queueList.begin(), tempList);
|
||||
}
|
||||
|
||||
if(! idleList.empty()) {
|
||||
std::lock_guard<Mutex> queueListLock(freeListMutex);
|
||||
freeList.splice(freeList.end(), idleList);
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
void wait() const
|
||||
{
|
||||
std::unique_lock<Mutex> queueListLock(queueListMutex);
|
||||
queueListConditionVariable.wait(queueListLock, [this]() -> bool {
|
||||
return doCanProcess();
|
||||
});
|
||||
}
|
||||
|
||||
template <class Rep, class Period>
|
||||
bool waitFor(const std::chrono::duration<Rep, Period> & duration) const
|
||||
{
|
||||
std::unique_lock<Mutex> queueListLock(queueListMutex);
|
||||
return queueListConditionVariable.wait_for(queueListLock, duration, [this]() -> bool {
|
||||
return doCanProcess();
|
||||
});
|
||||
}
|
||||
|
||||
using super::dispatch;
|
||||
|
||||
template <typename U>
|
||||
auto dispatch(const U & queuedEvent)
|
||||
-> typename std::enable_if<std::is_same<U, QueuedEvent>::value, void>::type
|
||||
{
|
||||
doDispatchQueuedEvent(
|
||||
queuedEvent,
|
||||
typename MakeIndexSequence<sizeof...(Args)>::Type()
|
||||
);
|
||||
}
|
||||
|
||||
bool peekEvent(QueuedEvent * queuedEvent)
|
||||
{
|
||||
if(! queueList.empty()) {
|
||||
std::lock_guard<Mutex> queueListLock(queueListMutex);
|
||||
|
||||
if(! queueList.empty()) {
|
||||
*queuedEvent = queueList.front().get();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
bool takeEvent(QueuedEvent * queuedEvent)
|
||||
{
|
||||
if(! queueList.empty()) {
|
||||
BufferedItemList tempList;
|
||||
|
||||
{
|
||||
std::lock_guard<Mutex> queueListLock(queueListMutex);
|
||||
|
||||
if(! queueList.empty()) {
|
||||
tempList.splice(tempList.end(), queueList, queueList.begin());
|
||||
}
|
||||
}
|
||||
|
||||
if(! tempList.empty()) {
|
||||
*queuedEvent = std::move(tempList.front().get());
|
||||
tempList.front().clear();
|
||||
|
||||
std::lock_guard<Mutex> queueListLock(freeListMutex);
|
||||
freeList.splice(freeList.end(), tempList);
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
protected:
|
||||
bool doCanProcess() const
|
||||
{
|
||||
return ! emptyQueue() && doCanNotifyQueueAvailable();
|
||||
}
|
||||
|
||||
bool doCanNotifyQueueAvailable() const
|
||||
{
|
||||
return queueNotifyCounter.load(std::memory_order_acquire) == 0;
|
||||
}
|
||||
|
||||
template <typename T, size_t ...Indexes>
|
||||
void doDispatchQueuedEvent(T && item, IndexSequence<Indexes...>)
|
||||
{
|
||||
this->directDispatch(item.event, std::get<Indexes>(item.arguments)...);
|
||||
}
|
||||
|
||||
template <typename F, typename T, size_t ...Indexes>
|
||||
bool doInvokeFuncWithQueuedEvent(F && func, T && item, IndexSequence<Indexes...>) const
|
||||
{
|
||||
return doInvokeFuncWithQueuedEventHelper(std::forward<F>(func), std::get<Indexes>(item.arguments)...);
|
||||
}
|
||||
|
||||
template <typename F>
|
||||
auto doInvokeFuncWithQueuedEventHelper(F && func, Args ...args) const
|
||||
-> typename std::enable_if<! CanInvoke<F>::value, bool>::type
|
||||
{
|
||||
return func(std::forward<Args>(args)...);
|
||||
}
|
||||
|
||||
template <typename F>
|
||||
auto doInvokeFuncWithQueuedEventHelper(F && func, Args .../*args*/) const
|
||||
-> typename std::enable_if<CanInvoke<F>::value, bool>::type
|
||||
{
|
||||
return func();
|
||||
}
|
||||
|
||||
void doEnqueue(QueuedEvent && item)
|
||||
{
|
||||
BufferedItemList tempList;
|
||||
if(! freeList.empty()) {
|
||||
{
|
||||
std::lock_guard<Mutex> queueListLock(freeListMutex);
|
||||
if(! freeList.empty()) {
|
||||
tempList.splice(tempList.end(), freeList, freeList.begin());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if(tempList.empty()) {
|
||||
tempList.emplace_back();
|
||||
}
|
||||
|
||||
auto it = tempList.begin();
|
||||
it->set(std::move(item));
|
||||
|
||||
std::lock_guard<Mutex> queueListLock(queueListMutex);
|
||||
queueList.splice(queueList.end(), tempList, it);
|
||||
}
|
||||
|
||||
private:
|
||||
mutable ConditionVariable queueListConditionVariable;
|
||||
typename Threading::template Atomic<int> queueEmptyCounter;
|
||||
typename Threading::template Atomic<int> queueNotifyCounter;
|
||||
mutable Mutex queueListMutex;
|
||||
BufferedItemList queueList;
|
||||
Mutex freeListMutex;
|
||||
BufferedItemList freeList;
|
||||
};
|
||||
|
||||
} //namespace internal_
|
||||
|
||||
template <
|
||||
typename Event_,
|
||||
typename Prototype_,
|
||||
typename Policies_ = DefaultPolicies
|
||||
>
|
||||
class EventQueue : public internal_::InheritMixins<
|
||||
internal_::EventQueueBase<Event_, Prototype_, Policies_>,
|
||||
typename internal_::SelectMixins<Policies_, internal_::HasTypeMixins<Policies_>::value >::Type
|
||||
>::Type, public TagEventDispatcher, public TagEventQueue
|
||||
{
|
||||
private:
|
||||
using super = typename internal_::InheritMixins<
|
||||
internal_::EventQueueBase<Event_, Prototype_, Policies_>,
|
||||
typename internal_::SelectMixins<Policies_, internal_::HasTypeMixins<Policies_>::value >::Type
|
||||
>::Type;
|
||||
|
||||
public:
|
||||
using super::super;
|
||||
};
|
||||
|
||||
|
||||
} //namespace eventpp
|
||||
|
||||
|
||||
#endif
|
||||
|
||||
@@ -1,319 +0,0 @@
|
||||
// eventpp library
|
||||
// Copyright (C) 2018 Wang Qi (wqking)
|
||||
// Github: https://github.com/wqking/eventpp
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#ifndef HETERCALLBACKLIST_H_966730936077
|
||||
#define HETERCALLBACKLIST_H_966730936077
|
||||
|
||||
#include "internal/hetercallbacklist_i.h"
|
||||
#include "callbacklist.h"
|
||||
|
||||
#include <array>
|
||||
#include <mutex>
|
||||
|
||||
namespace eventpp {
|
||||
|
||||
namespace internal_ {
|
||||
|
||||
template <
|
||||
typename PrototypeList_,
|
||||
typename Policies_
|
||||
>
|
||||
class HeterCallbackListBase
|
||||
{
|
||||
protected:
|
||||
struct HeterHandle_
|
||||
{
|
||||
int index;
|
||||
std::weak_ptr<void> homoHandle;
|
||||
|
||||
operator bool () const noexcept {
|
||||
return (bool)homoHandle;
|
||||
}
|
||||
};
|
||||
|
||||
struct UnderlyingPoliciesType_
|
||||
{
|
||||
};
|
||||
|
||||
class HomoCallbackListTypeBase
|
||||
{
|
||||
public:
|
||||
virtual ~HomoCallbackListTypeBase() {}
|
||||
|
||||
virtual bool empty() = 0;
|
||||
virtual bool doRemove(const HeterHandle_ & handle) = 0;
|
||||
virtual std::shared_ptr<HomoCallbackListTypeBase> doClone() = 0;
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
class HomoCallbackListType : public CallbackList<T, UnderlyingPoliciesType_>, public HomoCallbackListTypeBase
|
||||
{
|
||||
private:
|
||||
using super = CallbackList<T, UnderlyingPoliciesType_>;
|
||||
|
||||
public:
|
||||
virtual bool empty() override {
|
||||
return super::empty();
|
||||
}
|
||||
|
||||
virtual bool doRemove(const HeterHandle_ & handle) override {
|
||||
auto sp = handle.homoHandle.lock();
|
||||
if(! sp) {
|
||||
return false;
|
||||
}
|
||||
return this->remove(typename super::Handle(std::static_pointer_cast<typename super::Handle::element_type>(sp)));
|
||||
}
|
||||
|
||||
virtual std::shared_ptr<HomoCallbackListTypeBase> doClone() override {
|
||||
return std::make_shared<HomoCallbackListType<T> >(*this);
|
||||
}
|
||||
};
|
||||
|
||||
using Policies = Policies_;
|
||||
using Threading = typename SelectThreading<Policies, HasTypeThreading<Policies>::value>::Type;
|
||||
|
||||
using PrototypeList = PrototypeList_;
|
||||
|
||||
public:
|
||||
using Handle = HeterHandle_;
|
||||
using Mutex = typename Threading::Mutex;
|
||||
|
||||
public:
|
||||
HeterCallbackListBase()
|
||||
:
|
||||
callbackListList(),
|
||||
callbackListListMutex()
|
||||
{
|
||||
}
|
||||
|
||||
HeterCallbackListBase(const HeterCallbackListBase & other)
|
||||
:
|
||||
callbackListList(),
|
||||
callbackListListMutex()
|
||||
{
|
||||
for(size_t i = 0; i < callbackListList.size(); ++i) {
|
||||
if(other.callbackListList[i]) {
|
||||
callbackListList[i] = other.callbackListList[i]->doClone();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
HeterCallbackListBase(HeterCallbackListBase && other) noexcept
|
||||
:
|
||||
callbackListList(std::move(other.callbackListList)),
|
||||
callbackListListMutex()
|
||||
{
|
||||
}
|
||||
|
||||
// If we use pass by value idiom and omit the 'this' check,
|
||||
// when assigning to self there is a deep copy which is inefficient.
|
||||
HeterCallbackListBase & operator = (const HeterCallbackListBase & other) noexcept
|
||||
{
|
||||
if(this != &other) {
|
||||
HeterCallbackListBase copied(other);
|
||||
swap(copied);
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
HeterCallbackListBase & operator = (HeterCallbackListBase && other) noexcept
|
||||
{
|
||||
if(this != &other) {
|
||||
for(size_t i = 0; i < callbackListList.size(); ++i) {
|
||||
callbackListList[i] = std::move(other.callbackListList[i]);
|
||||
}
|
||||
}
|
||||
|
||||
return *this;
|
||||
}
|
||||
|
||||
void swap(HeterCallbackListBase & other) noexcept {
|
||||
using std::swap;
|
||||
|
||||
swap(callbackListList, other.callbackListList);
|
||||
}
|
||||
|
||||
bool empty() const {
|
||||
for(const auto & callbackList : callbackListList) {
|
||||
if(callbackList && ! callbackList->empty()) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
operator bool() const {
|
||||
return ! empty();
|
||||
}
|
||||
|
||||
template <typename C>
|
||||
Handle append(const C & callback)
|
||||
{
|
||||
using PrototypeInfo = FindPrototypeByCallable<PrototypeList_, C>;
|
||||
static_assert(PrototypeInfo::index >= 0, "Can't find invoker for the given argument types.");
|
||||
|
||||
auto callbackList= doGetCallbackList<PrototypeInfo>();
|
||||
return Handle {
|
||||
PrototypeInfo::index,
|
||||
callbackList->append(callback)
|
||||
};
|
||||
}
|
||||
|
||||
template <typename C>
|
||||
Handle prepend(const C & callback)
|
||||
{
|
||||
using PrototypeInfo = FindPrototypeByCallable<PrototypeList_, C>;
|
||||
static_assert(PrototypeInfo::index >= 0, "Can't find invoker for the given argument types.");
|
||||
|
||||
auto callbackList= doGetCallbackList<PrototypeInfo>();
|
||||
return Handle {
|
||||
PrototypeInfo::index,
|
||||
callbackList->prepend(callback)
|
||||
};
|
||||
}
|
||||
|
||||
template <typename C>
|
||||
Handle insert(const C & callback, const Handle & before)
|
||||
{
|
||||
using PrototypeInfo = FindPrototypeByCallable<PrototypeList_, C>;
|
||||
static_assert(PrototypeInfo::index >= 0, "Can't find invoker for the given argument types.");
|
||||
|
||||
auto callbackList= doGetCallbackList<PrototypeInfo>();
|
||||
|
||||
if(before.index != PrototypeInfo::index) {
|
||||
return Handle {
|
||||
PrototypeInfo::index,
|
||||
callbackList->append(callback)
|
||||
};
|
||||
}
|
||||
|
||||
using UnderlyingHandle = typename decltype(callbackList)::element_type::Handle;
|
||||
|
||||
return Handle {
|
||||
PrototypeInfo::index,
|
||||
callbackList->insert(
|
||||
callback,
|
||||
UnderlyingHandle(std::static_pointer_cast<typename UnderlyingHandle::element_type>(before.homoHandle.lock()))
|
||||
)
|
||||
};
|
||||
}
|
||||
|
||||
bool remove(const Handle & handle)
|
||||
{
|
||||
auto callbackList = callbackListList[handle.index];
|
||||
if(callbackList) {
|
||||
return callbackList->doRemove(handle);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
template <typename Prototype, typename Func>
|
||||
void forEach(Func && func) const
|
||||
{
|
||||
using PrototypeInfo = FindPrototypeByCallable<PrototypeList, Prototype>;
|
||||
static_assert(PrototypeInfo::index >= 0, "Can't find invoker for the given argument types.");
|
||||
|
||||
auto callbackList= doGetCallbackList<PrototypeInfo>();
|
||||
using CL = typename decltype(callbackList)::element_type;
|
||||
callbackList->forEach([this, &func](const typename CL::Handle & handle, const typename CL::Callback & callback) {
|
||||
doForEachInvoke<void, PrototypeInfo::index>(func, handle, callback);
|
||||
});
|
||||
}
|
||||
|
||||
template <typename Prototype, typename Func>
|
||||
bool forEachIf(Func && func) const
|
||||
{
|
||||
using PrototypeInfo = FindPrototypeByCallable<PrototypeList, Prototype>;
|
||||
static_assert(PrototypeInfo::index >= 0, "Can't find invoker for the given argument types.");
|
||||
|
||||
auto callbackList= doGetCallbackList<PrototypeInfo>();
|
||||
using CL = typename decltype(callbackList)::element_type;
|
||||
return callbackList->forEachIf([this, &func](const typename CL::Handle & handle, const typename CL::Callback & callback) {
|
||||
return doForEachInvoke<bool, PrototypeInfo::index>(func, handle, callback);
|
||||
});
|
||||
}
|
||||
|
||||
template <typename ...Args>
|
||||
void operator() (Args && ...args) const
|
||||
{
|
||||
using PrototypeInfo = FindPrototypeByArgs<PrototypeList, Args...>;
|
||||
static_assert(PrototypeInfo::index >= 0, "Can't find invoker for the given argument types.");
|
||||
|
||||
auto callbackList= doGetCallbackList<PrototypeInfo>();
|
||||
(*callbackList)(std::forward<Args>(args)...);
|
||||
}
|
||||
|
||||
private:
|
||||
template <typename RT, int PrototypeIndex, typename Func, typename H, typename CL>
|
||||
auto doForEachInvoke(Func && func, const H & handle, CL && callback) const
|
||||
-> typename std::enable_if<CanInvoke<Func, Handle, CL>::value, RT>::type
|
||||
{
|
||||
return func(Handle { PrototypeIndex, handle }, callback);
|
||||
}
|
||||
|
||||
template <typename RT, int PrototypeIndex, typename Func, typename H, typename CL>
|
||||
auto doForEachInvoke(Func && func, const H & /*handle*/, CL && callback) const
|
||||
-> typename std::enable_if<CanInvoke<Func, CL>::value, RT>::type
|
||||
{
|
||||
return func(callback);
|
||||
}
|
||||
|
||||
template <typename PrototypeInfo>
|
||||
auto doGetCallbackList() const
|
||||
-> std::shared_ptr<HomoCallbackListType<typename PrototypeInfo::Prototype> >
|
||||
{
|
||||
static_assert(PrototypeInfo::index >= 0, "Can't find invoker for the given argument types.");
|
||||
|
||||
if(! callbackListList[PrototypeInfo::index]) {
|
||||
std::lock_guard<Mutex> lockGuard(callbackListListMutex);
|
||||
|
||||
if(! callbackListList[PrototypeInfo::index]) {
|
||||
callbackListList[PrototypeInfo::index] = std::make_shared<HomoCallbackListType<typename PrototypeInfo::Prototype> >();
|
||||
}
|
||||
}
|
||||
|
||||
return std::static_pointer_cast<HomoCallbackListType<typename PrototypeInfo::Prototype> >(callbackListList[PrototypeInfo::index]);
|
||||
}
|
||||
|
||||
private:
|
||||
// the postfix 'ListList' is not good, but it's better to use consistent naming convention.
|
||||
mutable std::array<std::shared_ptr<HomoCallbackListTypeBase>, HeterTupleSize<PrototypeList_>::value> callbackListList;
|
||||
mutable Mutex callbackListListMutex;
|
||||
};
|
||||
|
||||
|
||||
} //namespace internal_
|
||||
|
||||
template <
|
||||
typename PrototypeList_,
|
||||
typename Policies_ = DefaultPolicies
|
||||
>
|
||||
class HeterCallbackList : public internal_::HeterCallbackListBase<PrototypeList_, Policies_>, public TagCallbackList, public TagHeterCallbackList
|
||||
{
|
||||
private:
|
||||
using super = internal_::HeterCallbackListBase<PrototypeList_, Policies_>;
|
||||
|
||||
public:
|
||||
using super::super;
|
||||
|
||||
friend void swap(HeterCallbackList & first, HeterCallbackList & second) noexcept {
|
||||
first.swap(second);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
} //namespace eventpp
|
||||
|
||||
#endif
|
||||
@@ -1,325 +0,0 @@
|
||||
// eventpp library
|
||||
// Copyright (C) 2018 Wang Qi (wqking)
|
||||
// Github: https://github.com/wqking/eventpp
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#ifndef HETEREVENTDISPATCHER_H_127766658555
|
||||
#define HETEREVENTDISPATCHER_H_127766658555
|
||||
|
||||
#include "mixins/mixinheterfilter.h"
|
||||
|
||||
namespace eventpp {
|
||||
|
||||
namespace internal_ {
|
||||
|
||||
template <
|
||||
typename EventType_,
|
||||
typename PrototypeList_,
|
||||
typename Policies_,
|
||||
typename MixinRoot_
|
||||
>
|
||||
class HeterEventDispatcherBase
|
||||
{
|
||||
protected:
|
||||
using ThisType = HeterEventDispatcherBase<
|
||||
EventType_,
|
||||
PrototypeList_,
|
||||
Policies_,
|
||||
MixinRoot_
|
||||
>;
|
||||
using MixinRoot = typename std::conditional<
|
||||
std::is_same<MixinRoot_, void>::value,
|
||||
ThisType,
|
||||
MixinRoot_
|
||||
>::type;
|
||||
using Policies = Policies_;
|
||||
|
||||
using Threading = typename SelectThreading<Policies, HasTypeThreading<Policies_>::value>::Type;
|
||||
|
||||
using ArgumentPassingMode = typename SelectArgumentPassingMode<
|
||||
Policies_,
|
||||
HasTypeArgumentPassingMode<Policies_>::value,
|
||||
ArgumentPassingExcludeEvent
|
||||
>::Type;
|
||||
|
||||
static_assert(! std::is_same<ArgumentPassingMode, ArgumentPassingAutoDetect>::value,
|
||||
"ArgumentPassingMode can't be ArgumentPassingAutoDetect in heterogeneous dispatcher.");
|
||||
|
||||
using CallbackList_ = HeterCallbackList<PrototypeList_, Policies_>;
|
||||
|
||||
using Map = typename SelectMap<
|
||||
EventType_,
|
||||
CallbackList_,
|
||||
Policies_,
|
||||
HasTemplateMap<Policies_>::value
|
||||
>::Type;
|
||||
|
||||
using Mixins = typename internal_::SelectMixins<
|
||||
Policies_,
|
||||
internal_::HasTypeMixins<Policies_>::value
|
||||
>::Type;
|
||||
|
||||
public:
|
||||
using PrototypeList = PrototypeList_;
|
||||
using Handle = typename CallbackList_::Handle;
|
||||
using Event = EventType_;
|
||||
using Mutex = typename Threading::Mutex;
|
||||
|
||||
public:
|
||||
HeterEventDispatcherBase()
|
||||
:
|
||||
eventCallbackListMap(),
|
||||
listenerMutex()
|
||||
{
|
||||
}
|
||||
|
||||
HeterEventDispatcherBase(const HeterEventDispatcherBase & other)
|
||||
:
|
||||
eventCallbackListMap(other.eventCallbackListMap),
|
||||
listenerMutex()
|
||||
{
|
||||
}
|
||||
|
||||
HeterEventDispatcherBase(HeterEventDispatcherBase && other) noexcept
|
||||
:
|
||||
eventCallbackListMap(std::move(other.eventCallbackListMap)),
|
||||
listenerMutex()
|
||||
{
|
||||
}
|
||||
|
||||
HeterEventDispatcherBase & operator = (const HeterEventDispatcherBase & other)
|
||||
{
|
||||
eventCallbackListMap = other.eventCallbackListMap;
|
||||
return *this;
|
||||
}
|
||||
|
||||
HeterEventDispatcherBase & operator = (HeterEventDispatcherBase && other) noexcept
|
||||
{
|
||||
eventCallbackListMap = std::move(other.eventCallbackListMap);
|
||||
return *this;
|
||||
}
|
||||
|
||||
void swap(HeterEventDispatcherBase & other) noexcept {
|
||||
using std::swap;
|
||||
|
||||
swap(eventCallbackListMap, other.eventCallbackListMap);
|
||||
}
|
||||
|
||||
template <typename C>
|
||||
Handle appendListener(const Event & event, const C & callback)
|
||||
{
|
||||
std::lock_guard<Mutex> lockGuard(listenerMutex);
|
||||
|
||||
return eventCallbackListMap[event].append(callback);
|
||||
}
|
||||
|
||||
template <typename C>
|
||||
Handle prependListener(const Event & event, const C & callback)
|
||||
{
|
||||
std::lock_guard<Mutex> lockGuard(listenerMutex);
|
||||
|
||||
return eventCallbackListMap[event].prepend(callback);
|
||||
}
|
||||
|
||||
template <typename C>
|
||||
Handle insertListener(const Event & event, const C & callback, const Handle & before)
|
||||
{
|
||||
std::lock_guard<Mutex> lockGuard(listenerMutex);
|
||||
|
||||
return eventCallbackListMap[event].insert(callback, before);
|
||||
}
|
||||
|
||||
bool removeListener(const Event & event, const Handle handle)
|
||||
{
|
||||
CallbackList_ * callableList = doFindCallableList(event);
|
||||
if(callableList) {
|
||||
return callableList->remove(handle);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
bool hasAnyListener(const Event & event) const
|
||||
{
|
||||
const CallbackList_ * callableList = doFindCallableList(event);
|
||||
if(callableList) {
|
||||
return ! callableList->empty();
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
template <typename Prototype, typename Func>
|
||||
void forEach(const Event & event, Func && func) const
|
||||
{
|
||||
const CallbackList_ * callableList = doFindCallableList(event);
|
||||
if(callableList) {
|
||||
callableList->template forEach<Prototype>(std::forward<Func>(func));
|
||||
}
|
||||
}
|
||||
|
||||
template <typename Prototype, typename Func>
|
||||
bool forEachIf(const Event & event, Func && func) const
|
||||
{
|
||||
const CallbackList_ * callableList = doFindCallableList(event);
|
||||
if (callableList) {
|
||||
return callableList->template forEachIf<Prototype>(std::forward<Func>(func));
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
template <typename T, typename ...Args>
|
||||
void dispatch(T && first, Args && ...args) const
|
||||
{
|
||||
doDispatch<ArgumentPassingMode>(std::forward<T>(first), std::forward<Args>(args)...);
|
||||
}
|
||||
|
||||
// Bypass any getEvent policy. The first argument is the event type.
|
||||
// Most used for internal purpose.
|
||||
template <typename ...Args>
|
||||
void directDispatch(const Event & e, Args && ...args) const
|
||||
{
|
||||
if(! internal_::ForEachMixins<MixinRoot, Mixins, DoMixinBeforeDispatch>::forEach(
|
||||
this, typename std::add_lvalue_reference<Args>::type(args)...)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const CallbackList_ * callableList = doFindCallableList(e);
|
||||
if(callableList) {
|
||||
(*callableList)(std::forward<Args>(args)...);
|
||||
}
|
||||
}
|
||||
|
||||
protected:
|
||||
template <typename ArgumentMode, typename T, typename ...Args>
|
||||
auto doDispatch(T && first, Args && ...args) const
|
||||
-> typename std::enable_if<std::is_same<ArgumentMode, ArgumentPassingIncludeEvent>::value>::type
|
||||
{
|
||||
if(! internal_::ForEachMixins<MixinRoot, Mixins, DoMixinBeforeDispatch>::forEach(
|
||||
this,
|
||||
typename std::add_lvalue_reference<T>::type(first),
|
||||
typename std::add_lvalue_reference<Args>::type(args)...)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
using GetEvent = typename SelectGetEvent<Policies_, EventType_, HasFunctionGetEvent<Policies_, T &&, Args...>::value>::Type;
|
||||
const auto e = GetEvent::getEvent(std::forward<T>(first), args...);
|
||||
const CallbackList_ * callableList = doFindCallableList(e);
|
||||
if(callableList) {
|
||||
(*callableList)(std::forward<T>(first), std::forward<Args>(args)...);
|
||||
}
|
||||
}
|
||||
|
||||
template <typename ArgumentMode, typename T, typename ...Args>
|
||||
auto doDispatch(T && first, Args && ...args) const
|
||||
-> typename std::enable_if<std::is_same<ArgumentMode, ArgumentPassingExcludeEvent>::value>::type
|
||||
{
|
||||
if(! internal_::ForEachMixins<MixinRoot, Mixins, DoMixinBeforeDispatch>::forEach(
|
||||
this,
|
||||
typename std::add_lvalue_reference<Args>::type(args)...)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
using GetEvent = typename SelectGetEvent<Policies_, EventType_, HasFunctionGetEvent<Policies_, T &&, Args...>::value>::Type;
|
||||
const auto e = GetEvent::getEvent(std::forward<T>(first), args...);
|
||||
const CallbackList_ * callableList = doFindCallableList(e);
|
||||
if(callableList) {
|
||||
(*callableList)(std::forward<Args>(args)...);
|
||||
}
|
||||
}
|
||||
|
||||
const CallbackList_ * doFindCallableList(const Event & e) const
|
||||
{
|
||||
return doFindCallableListHelper(this, e);
|
||||
}
|
||||
|
||||
CallbackList_ * doFindCallableList(const Event & e)
|
||||
{
|
||||
return doFindCallableListHelper(this, e);
|
||||
}
|
||||
|
||||
private:
|
||||
// template helper to avoid code duplication in doFindCallableList
|
||||
template <typename T>
|
||||
static auto doFindCallableListHelper(T * self, const Event & e)
|
||||
-> typename std::conditional<std::is_const<T>::value, const CallbackList_ *, CallbackList_ *>::type
|
||||
{
|
||||
std::lock_guard<Mutex> lockGuard(self->listenerMutex);
|
||||
|
||||
auto it = self->eventCallbackListMap.find(e);
|
||||
if(it != self->eventCallbackListMap.end()) {
|
||||
return &it->second;
|
||||
}
|
||||
else {
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
private:
|
||||
// Mixin related
|
||||
struct DoMixinBeforeDispatch
|
||||
{
|
||||
template <typename T, typename Self, typename ...A>
|
||||
static auto forEach(const Self * self, A && ...args)
|
||||
-> typename std::enable_if<HasFunctionMixinBeforeDispatch<T, A...>::value, bool>::type {
|
||||
return static_cast<const T *>(self)->mixinBeforeDispatch(std::forward<A>(args)...);
|
||||
}
|
||||
|
||||
template <typename T, typename Self, typename ...A>
|
||||
static auto forEach(const Self * self, A && ...args)
|
||||
-> typename std::enable_if<! HasFunctionMixinBeforeDispatch<T, A...>::value, bool>::type {
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
private:
|
||||
Map eventCallbackListMap;
|
||||
mutable Mutex listenerMutex;
|
||||
};
|
||||
|
||||
} //namespace internal_
|
||||
|
||||
|
||||
template <
|
||||
typename Event_,
|
||||
typename PrototypeList_,
|
||||
typename Policies_ = DefaultPolicies
|
||||
>
|
||||
class HeterEventDispatcher : public internal_::InheritMixins<
|
||||
internal_::HeterEventDispatcherBase<Event_, PrototypeList_, Policies_, void>,
|
||||
typename internal_::SelectMixins<Policies_, internal_::HasTypeMixins<Policies_>::value >::Type
|
||||
>::Type, public TagEventDispatcher, public TagHeterEventDispatcher
|
||||
{
|
||||
private:
|
||||
using super = typename internal_::InheritMixins<
|
||||
internal_::HeterEventDispatcherBase<Event_, PrototypeList_, Policies_, void>,
|
||||
typename internal_::SelectMixins<Policies_, internal_::HasTypeMixins<Policies_>::value >::Type
|
||||
>::Type;
|
||||
|
||||
public:
|
||||
using super::super;
|
||||
|
||||
friend void swap(HeterEventDispatcher & first, HeterEventDispatcher & second) noexcept {
|
||||
first.swap(second);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
} //namespace eventpp
|
||||
|
||||
|
||||
#endif
|
||||
|
||||
@@ -1,482 +0,0 @@
|
||||
// eventpp library
|
||||
// Copyright (C) 2018 Wang Qi (wqking)
|
||||
// Github: https://github.com/wqking/eventpp
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#ifndef HETEREVENTQUEUE_H_210892536510
|
||||
#define HETEREVENTQUEUE_H_210892536510
|
||||
|
||||
#include "hetereventdispatcher.h"
|
||||
|
||||
// temp, should move the internal code in eventqueue to separated file
|
||||
#include "eventqueue.h"
|
||||
|
||||
namespace eventpp {
|
||||
|
||||
namespace internal_ {
|
||||
|
||||
template <
|
||||
typename EventType_,
|
||||
typename PrototypeList_,
|
||||
typename Policies_
|
||||
>
|
||||
class HeterEventQueueBase : public HeterEventDispatcherBase<
|
||||
EventType_,
|
||||
PrototypeList_,
|
||||
Policies_,
|
||||
HeterEventQueueBase <
|
||||
EventType_,
|
||||
PrototypeList_,
|
||||
Policies_
|
||||
>
|
||||
>
|
||||
{
|
||||
private:
|
||||
using super = HeterEventDispatcherBase<
|
||||
EventType_,
|
||||
PrototypeList_,
|
||||
Policies_,
|
||||
HeterEventQueueBase <
|
||||
EventType_,
|
||||
PrototypeList_,
|
||||
Policies_
|
||||
>
|
||||
>;
|
||||
|
||||
using Policies = typename super::Policies;
|
||||
using Threading = typename super::Threading;
|
||||
using ConditionVariable = typename Threading::ConditionVariable;
|
||||
|
||||
struct QueuedItemBase;
|
||||
using ItemDispatcher = void (*)(const HeterEventQueueBase *, const QueuedItemBase &);
|
||||
|
||||
struct QueuedItemBase
|
||||
{
|
||||
QueuedItemBase(const int callableIndex, const EventType_ & event, const ItemDispatcher dispatcher)
|
||||
: callableIndex(callableIndex), event(event), dispatcher(dispatcher)
|
||||
{
|
||||
}
|
||||
|
||||
int callableIndex;
|
||||
EventType_ event;
|
||||
ItemDispatcher dispatcher;
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
struct QueuedItem : public QueuedItemBase
|
||||
{
|
||||
QueuedItem(const int callableIndex, const EventType_ & event, const ItemDispatcher dispatcher, T && arguments)
|
||||
: QueuedItemBase(callableIndex, event, dispatcher), arguments(std::move(arguments))
|
||||
{
|
||||
}
|
||||
|
||||
T arguments;
|
||||
};
|
||||
|
||||
template <typename ...Args>
|
||||
using QueuedItemSizer = QueuedItem<std::tuple<typename std::remove_cv<typename std::remove_reference<Args>::type>::type...> >;
|
||||
|
||||
using BufferedQueuedItem = BufferedUnion<GetCallablePrototypeMaxSize<PrototypeList_, QueuedItemSizer>::value>;
|
||||
|
||||
using BufferedItemList = std::list<BufferedQueuedItem>;
|
||||
|
||||
using PrototypeList = typename super::PrototypeList;
|
||||
|
||||
using ArgumentPassingMode = typename super::ArgumentPassingMode;
|
||||
|
||||
public:
|
||||
using Event = typename super::Event;
|
||||
using Handle = typename super::Handle;
|
||||
using Mutex = typename super::Mutex;
|
||||
|
||||
public:
|
||||
HeterEventQueueBase()
|
||||
:
|
||||
super(),
|
||||
queueListConditionVariable(),
|
||||
queueEmptyCounter(0),
|
||||
queueNotifyCounter(0),
|
||||
queueListMutex(),
|
||||
queueList(),
|
||||
freeListMutex(),
|
||||
freeList()
|
||||
{
|
||||
}
|
||||
|
||||
HeterEventQueueBase(const HeterEventQueueBase & other)
|
||||
: super(other)
|
||||
{
|
||||
}
|
||||
|
||||
HeterEventQueueBase(HeterEventQueueBase && other) noexcept
|
||||
: super(std::move(other))
|
||||
{
|
||||
}
|
||||
|
||||
HeterEventQueueBase & operator = (const HeterEventQueueBase & other)
|
||||
{
|
||||
super::operator = (other);
|
||||
return *this;
|
||||
}
|
||||
|
||||
HeterEventQueueBase & operator = (HeterEventQueueBase && other) noexcept
|
||||
{
|
||||
super::operator = (std::move(other));
|
||||
return *this;
|
||||
}
|
||||
|
||||
template <typename T, typename ...Args>
|
||||
void enqueue(T && first, Args && ...args)
|
||||
{
|
||||
doEnqueue<ArgumentPassingMode>(std::forward<T>(first), std::forward<Args>(args)...);
|
||||
}
|
||||
|
||||
bool emptyQueue() const
|
||||
{
|
||||
return queueList.empty() && (queueEmptyCounter.load(std::memory_order_acquire) == 0);
|
||||
}
|
||||
|
||||
void clearEvents()
|
||||
{
|
||||
if(! queueList.empty()) {
|
||||
BufferedItemList tempList;
|
||||
|
||||
{
|
||||
std::lock_guard<Mutex> queueListLock(queueListMutex);
|
||||
std::swap(queueList, tempList);
|
||||
}
|
||||
|
||||
if(! tempList.empty()) {
|
||||
for(auto & item : tempList) {
|
||||
item.clear();
|
||||
}
|
||||
|
||||
std::lock_guard<Mutex> queueListLock(freeListMutex);
|
||||
freeList.splice(freeList.end(), tempList);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bool process()
|
||||
{
|
||||
if(! queueList.empty()) {
|
||||
BufferedItemList tempList;
|
||||
|
||||
// Use a counter to tell the queue list is not empty during processing
|
||||
// even though queueList is swapped to empty.
|
||||
CounterGuard<decltype(queueEmptyCounter)> counterGuard(queueEmptyCounter);
|
||||
|
||||
{
|
||||
std::lock_guard<Mutex> queueListLock(queueListMutex);
|
||||
std::swap(queueList, tempList);
|
||||
}
|
||||
|
||||
if(! tempList.empty()) {
|
||||
for(auto & item : tempList) {
|
||||
doDispatchQueuedEvent(item.template get<QueuedItemBase>());
|
||||
item.clear();
|
||||
}
|
||||
|
||||
std::lock_guard<Mutex> queueListLock(freeListMutex);
|
||||
freeList.splice(freeList.end(), tempList);
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
bool processOne()
|
||||
{
|
||||
if(! queueList.empty()) {
|
||||
BufferedItemList tempList;
|
||||
|
||||
// Use a counter to tell the queue list is not empty during processing
|
||||
// even though queueList is swapped to empty.
|
||||
CounterGuard<decltype(queueEmptyCounter)> counterGuard(queueEmptyCounter);
|
||||
|
||||
{
|
||||
std::lock_guard<Mutex> queueListLock(queueListMutex);
|
||||
if(! queueList.empty()) {
|
||||
tempList.splice(tempList.end(), queueList, queueList.begin());
|
||||
}
|
||||
}
|
||||
|
||||
if(! tempList.empty()) {
|
||||
auto & item = tempList.front();
|
||||
doDispatchQueuedEvent(item.template get<QueuedItemBase>());
|
||||
item.clear();
|
||||
|
||||
std::lock_guard<Mutex> queueListLock(freeListMutex);
|
||||
freeList.splice(freeList.end(), tempList);
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
template <typename F>
|
||||
bool processIf(F && func)
|
||||
{
|
||||
if(queueList.empty()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
using PrototypeInfo = FindPrototypeByCallable<PrototypeList, F>;
|
||||
return doProcessIf<PrototypeInfo>(std::forward<F>(func));
|
||||
}
|
||||
|
||||
void wait() const
|
||||
{
|
||||
std::unique_lock<Mutex> queueListLock(queueListMutex);
|
||||
queueListConditionVariable.wait(queueListLock, [this]() -> bool {
|
||||
return doCanProcess();
|
||||
});
|
||||
}
|
||||
|
||||
template <class Rep, class Period>
|
||||
bool waitFor(const std::chrono::duration<Rep, Period> & duration) const
|
||||
{
|
||||
std::unique_lock<Mutex> queueListLock(queueListMutex);
|
||||
return queueListConditionVariable.wait_for(queueListLock, duration, [this]() -> bool {
|
||||
return doCanProcess();
|
||||
});
|
||||
}
|
||||
|
||||
using super::dispatch;
|
||||
|
||||
private:
|
||||
bool doCanProcess() const
|
||||
{
|
||||
return ! emptyQueue() && doCanNotifyQueueAvailable();
|
||||
}
|
||||
|
||||
bool doCanNotifyQueueAvailable() const
|
||||
{
|
||||
return queueNotifyCounter.load(std::memory_order_acquire) == 0;
|
||||
}
|
||||
|
||||
void doDispatchQueuedEvent(const QueuedItemBase & item)
|
||||
{
|
||||
item.dispatcher(this, item);
|
||||
}
|
||||
|
||||
template <typename PrototypeInfo>
|
||||
static void doDispatchItem(const HeterEventQueueBase * self, const QueuedItemBase & baseItem)
|
||||
{
|
||||
const auto & item = static_cast<const QueuedItem<typename PrototypeInfo::ArgsTuple> &>(baseItem);
|
||||
self->doDispatchQueuedItem<PrototypeInfo>(
|
||||
item,
|
||||
typename MakeIndexSequence<std::tuple_size<typename PrototypeInfo::ArgsTuple>::value>::Type()
|
||||
);
|
||||
}
|
||||
|
||||
template <typename PrototypeInfo, typename T, size_t ...Indexes>
|
||||
void doDispatchQueuedItem(T && item, IndexSequence<Indexes...>) const
|
||||
{
|
||||
this->directDispatch(item.event, std::get<Indexes>(item.arguments)...);
|
||||
}
|
||||
|
||||
template <typename PrototypeInfo, typename F>
|
||||
auto doProcessIf(F && func)
|
||||
-> typename std::enable_if<(PrototypeInfo::index >= 0), bool>::type
|
||||
{
|
||||
BufferedItemList tempList;
|
||||
BufferedItemList idleList;
|
||||
|
||||
// Use a counter to tell the queue list is not empty during processing
|
||||
// even though queueList is swapped to empty.
|
||||
CounterGuard<decltype(queueEmptyCounter)> counterGuard(queueEmptyCounter);
|
||||
|
||||
{
|
||||
std::lock_guard<Mutex> queueListLock(queueListMutex);
|
||||
std::swap(queueList, tempList);
|
||||
}
|
||||
|
||||
if(! tempList.empty()) {
|
||||
for(auto it = tempList.begin(); it != tempList.end(); ) {
|
||||
using ArgsTuple = typename PrototypeInfo::ArgsTuple;
|
||||
auto item = it->template get<QueuedItem<ArgsTuple> >();
|
||||
|
||||
if(item.callableIndex != PrototypeInfo::index) {
|
||||
++it;
|
||||
continue;
|
||||
}
|
||||
if(doInvokeFuncWithQueuedEvent(
|
||||
func,
|
||||
item,
|
||||
typename MakeIndexSequence<std::tuple_size<ArgsTuple>::value>::Type())
|
||||
) {
|
||||
doDispatchQueuedEvent(item);
|
||||
it->clear();
|
||||
|
||||
auto tempIt = it;
|
||||
++it;
|
||||
idleList.splice(idleList.end(), tempList, tempIt);
|
||||
}
|
||||
else {
|
||||
++it;
|
||||
}
|
||||
}
|
||||
|
||||
if (! tempList.empty()) {
|
||||
std::lock_guard<Mutex> queueListLock(queueListMutex);
|
||||
queueList.splice(queueList.begin(), tempList);
|
||||
}
|
||||
|
||||
if(! idleList.empty()) {
|
||||
std::lock_guard<Mutex> queueListLock(freeListMutex);
|
||||
freeList.splice(freeList.end(), idleList);
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
using NextPrototypeInfo = FindPrototypeByCallableFromIndex<PrototypeInfo::index + 1, PrototypeList, F>;
|
||||
if(doProcessIf<NextPrototypeInfo>(std::forward<F>(func))) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
template <typename PrototypeInfo, typename F>
|
||||
auto doProcessIf(F && /*func*/)
|
||||
-> typename std::enable_if<(PrototypeInfo::index < 0), bool>::type
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
template <typename F, typename T, size_t ...Indexes>
|
||||
bool doInvokeFuncWithQueuedEvent(F && func, T && item, IndexSequence<Indexes...>) const
|
||||
{
|
||||
return doInvokeFuncWithQueuedEventHelper(std::forward<F>(func), std::get<Indexes>(item.arguments)...);
|
||||
}
|
||||
|
||||
template <typename F, typename ...Args>
|
||||
bool doInvokeFuncWithQueuedEventHelper(F && func, Args && ...args) const
|
||||
{
|
||||
return func(std::forward<Args>(args)...);
|
||||
}
|
||||
|
||||
template <typename ArgumentMode, typename T, typename ...Args>
|
||||
auto doEnqueue(T && first, Args && ...args)
|
||||
-> typename std::enable_if<std::is_same<ArgumentMode, ArgumentPassingIncludeEvent>::value>::type
|
||||
{
|
||||
using GetEvent = typename SelectGetEvent<Policies_, EventType_, HasFunctionGetEvent<Policies_, T &&, Args...>::value>::Type;
|
||||
using PrototypeInfo = FindPrototypeByArgs<PrototypeList_, T, Args...>;
|
||||
using QueuedItemType = QueuedItem<typename PrototypeInfo::ArgsTuple>;
|
||||
|
||||
static_assert(PrototypeInfo::index >= 0, "Can't find invoker for the given argument types.");
|
||||
static_assert(std::tuple_size<typename PrototypeInfo::ArgsTuple>::value == 1 + sizeof...(Args), "Arguments count mismatch.");
|
||||
|
||||
doEnqueueItem(QueuedItemType(
|
||||
PrototypeInfo::index,
|
||||
GetEvent::getEvent(std::forward<T>(first), args...),
|
||||
&HeterEventQueueBase::doDispatchItem<PrototypeInfo>,
|
||||
typename PrototypeInfo::ArgsTuple(std::forward<T>(first), std::forward<Args>(args)...)
|
||||
));
|
||||
|
||||
if(doCanProcess()) {
|
||||
queueListConditionVariable.notify_one();
|
||||
}
|
||||
}
|
||||
|
||||
template <typename ArgumentMode, typename T, typename ...Args>
|
||||
auto doEnqueue(T && first, Args && ...args)
|
||||
-> typename std::enable_if<std::is_same<ArgumentMode, ArgumentPassingExcludeEvent>::value>::type
|
||||
{
|
||||
using GetEvent = typename SelectGetEvent<Policies_, EventType_, HasFunctionGetEvent<Policies_, T &&, Args...>::value>::Type;
|
||||
using PrototypeInfo = FindPrototypeByArgs<PrototypeList_, Args...>;
|
||||
using QueuedItemType = QueuedItem<typename PrototypeInfo::ArgsTuple>;
|
||||
|
||||
static_assert(PrototypeInfo::index >= 0, "Can't find invoker for the given argument types.");
|
||||
static_assert(std::tuple_size<typename PrototypeInfo::ArgsTuple>::value == sizeof...(Args), "Arguments count mismatch.");
|
||||
|
||||
doEnqueueItem(QueuedItemType(
|
||||
PrototypeInfo::index,
|
||||
GetEvent::getEvent(std::forward<T>(first), args...),
|
||||
&HeterEventQueueBase::doDispatchItem<PrototypeInfo>,
|
||||
typename PrototypeInfo::ArgsTuple(std::forward<Args>(args)...)
|
||||
));
|
||||
|
||||
if(doCanProcess()) {
|
||||
queueListConditionVariable.notify_one();
|
||||
}
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
void doEnqueueItem(T && item)
|
||||
{
|
||||
BufferedItemList tempList;
|
||||
if(! freeList.empty()) {
|
||||
{
|
||||
std::lock_guard<Mutex> queueListLock(freeListMutex);
|
||||
if(! freeList.empty()) {
|
||||
tempList.splice(tempList.end(), freeList, freeList.begin());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if(tempList.empty()) {
|
||||
tempList.emplace_back();
|
||||
}
|
||||
|
||||
auto it = tempList.begin();
|
||||
it->set(std::move(item));
|
||||
|
||||
std::lock_guard<Mutex> queueListLock(queueListMutex);
|
||||
queueList.splice(queueList.end(), tempList, it);
|
||||
}
|
||||
|
||||
private:
|
||||
mutable ConditionVariable queueListConditionVariable;
|
||||
typename Threading::template Atomic<int> queueEmptyCounter;
|
||||
typename Threading::template Atomic<int> queueNotifyCounter;
|
||||
mutable Mutex queueListMutex;
|
||||
BufferedItemList queueList;
|
||||
Mutex freeListMutex;
|
||||
BufferedItemList freeList;
|
||||
};
|
||||
|
||||
|
||||
|
||||
} //namespace internal_
|
||||
|
||||
template <
|
||||
typename Event_,
|
||||
typename PrototypeList_,
|
||||
typename Policies_ = DefaultPolicies
|
||||
>
|
||||
class HeterEventQueue : public internal_::InheritMixins<
|
||||
internal_::HeterEventQueueBase<Event_, PrototypeList_, Policies_>,
|
||||
typename internal_::SelectMixins<Policies_, internal_::HasTypeMixins<Policies_>::value >::Type
|
||||
>::Type, public TagEventDispatcher, public TagEventQueue, public TagHeterEventDispatcher, public TagHeterEventQueue
|
||||
{
|
||||
private:
|
||||
using super = typename internal_::InheritMixins<
|
||||
internal_::HeterEventQueueBase<Event_, PrototypeList_, Policies_>,
|
||||
typename internal_::SelectMixins<Policies_, internal_::HasTypeMixins<Policies_>::value >::Type
|
||||
>::Type;
|
||||
|
||||
public:
|
||||
using super::super;
|
||||
};
|
||||
|
||||
|
||||
} //namespace eventpp
|
||||
|
||||
|
||||
#endif
|
||||
|
||||
@@ -1,191 +0,0 @@
|
||||
// Don't include this header, include eventpolicies.h instead
|
||||
|
||||
namespace internal_ {
|
||||
|
||||
template <typename T>
|
||||
struct HasTypeArgumentPassingMode
|
||||
{
|
||||
template <typename C> static std::true_type test(typename C::ArgumentPassingMode *) ;
|
||||
template <typename C> static std::false_type test(...);
|
||||
|
||||
enum { value = !! decltype(test<T>(0))() };
|
||||
};
|
||||
template <typename T, bool, typename Default> struct SelectArgumentPassingMode { using Type = typename T::ArgumentPassingMode; };
|
||||
template <typename T, typename Default> struct SelectArgumentPassingMode <T, false, Default> { using Type = Default; };
|
||||
|
||||
template <typename T>
|
||||
struct HasTypeThreading
|
||||
{
|
||||
template <typename C> static std::true_type test(typename C::Threading *) ;
|
||||
template <typename C> static std::false_type test(...);
|
||||
|
||||
enum { value = !! decltype(test<T>(0))() };
|
||||
};
|
||||
template <typename T, bool> struct SelectThreading { using Type = typename T::Threading; };
|
||||
template <typename T> struct SelectThreading <T, false> { using Type = MultipleThreading; };
|
||||
|
||||
template <typename T>
|
||||
struct HasTypeCallback
|
||||
{
|
||||
template <typename C> static std::true_type test(typename C::Callback *) ;
|
||||
template <typename C> static std::false_type test(...);
|
||||
|
||||
enum { value = !! decltype(test<T>(0))() };
|
||||
};
|
||||
template <typename T, bool, typename D> struct SelectCallback { using Type = typename T::Callback; };
|
||||
template <typename T, typename D> struct SelectCallback<T, false, D> { using Type = D; };
|
||||
|
||||
template <typename T, typename ...Args>
|
||||
struct HasFunctionGetEvent
|
||||
{
|
||||
template <typename C> static std::true_type test(decltype(C::getEvent(std::declval<Args>()...)) *);
|
||||
template <typename C> static std::false_type test(...);
|
||||
|
||||
enum { value = !! decltype(test<T>(0))() };
|
||||
};
|
||||
template <typename E>
|
||||
struct DefaultGetEvent
|
||||
{
|
||||
template <typename U, typename ...Args>
|
||||
static E getEvent(U && e, Args && ...) {
|
||||
return e;
|
||||
}
|
||||
};
|
||||
template <typename T, typename Key, bool> struct SelectGetEvent { using Type = T; };
|
||||
template <typename T, typename Key> struct SelectGetEvent<T, Key, false> { using Type = DefaultGetEvent<Key>; };
|
||||
|
||||
template <typename T, typename ...Args>
|
||||
struct HasFunctionCanContinueInvoking
|
||||
{
|
||||
template <typename C> static std::true_type test(decltype(C::canContinueInvoking(std::declval<Args>()...)) *) ;
|
||||
template <typename C> static std::false_type test(...);
|
||||
|
||||
enum { value = !! decltype(test<T>(0))() };
|
||||
};
|
||||
struct DefaultCanContinueInvoking
|
||||
{
|
||||
template <typename ...Args>
|
||||
static bool canContinueInvoking(Args && ...) {
|
||||
return true;
|
||||
}
|
||||
};
|
||||
template <typename T, bool> struct SelectCanContinueInvoking { using Type = T; };
|
||||
template <typename T> struct SelectCanContinueInvoking<T, false> { using Type = DefaultCanContinueInvoking; };
|
||||
|
||||
template <typename T>
|
||||
struct HasTemplateMap
|
||||
{
|
||||
template <typename C> static std::true_type test(typename C::template Map<int, int> *) ;
|
||||
template <typename C> static std::false_type test(...);
|
||||
|
||||
enum { value = !! decltype(test<T>(0))() };
|
||||
};
|
||||
template <typename T>
|
||||
class HasHash
|
||||
{
|
||||
template <typename C> static std::true_type test(decltype(std::hash<C>()(std::declval<C>())) *) ;
|
||||
template <typename C> static std::false_type test(...);
|
||||
|
||||
public:
|
||||
enum { value = !! decltype(test<T>(0))() };
|
||||
};
|
||||
template <typename Key, typename Value, typename T, bool>
|
||||
struct SelectMap
|
||||
{
|
||||
using Type = typename T::template Map<Key, Value>;
|
||||
};
|
||||
template <typename Key, typename Value, typename T>
|
||||
struct SelectMap<Key, Value, T, false> {
|
||||
using Type = typename std::conditional<
|
||||
HasHash<Key>::value,
|
||||
std::unordered_map<Key, Value>,
|
||||
std::map<Key, Value>
|
||||
>::type;
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
struct HasTemplateQueueList
|
||||
{
|
||||
template <typename C> static std::true_type test(typename C::template QueueList<int> *);
|
||||
template <typename C> static std::false_type test(...);
|
||||
|
||||
enum { value = !! decltype(test<T>(0))() };
|
||||
};
|
||||
template <typename Value, typename T, bool>
|
||||
struct SelectQueueList
|
||||
{
|
||||
using Type = typename T::template QueueList<Value>;
|
||||
};
|
||||
template <typename Value, typename T>
|
||||
struct SelectQueueList<Value, T, false> {
|
||||
using Type = std::list<Value>;
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
struct HasTypeMixins
|
||||
{
|
||||
template <typename C> static std::true_type test(typename C::Mixins *) ;
|
||||
template <typename C> static std::false_type test(...);
|
||||
|
||||
enum { value = !! decltype(test<T>(0))() };
|
||||
};
|
||||
template <typename T, bool> struct SelectMixins { using Type = typename T::Mixins; };
|
||||
template <typename T> struct SelectMixins <T, false> { using Type = MixinList<>; };
|
||||
|
||||
|
||||
template <typename Root, typename TList>
|
||||
struct InheritMixins;
|
||||
|
||||
template <typename Root, template <typename> class T, template <typename> class ...Args>
|
||||
struct InheritMixins <Root, MixinList<T, Args...> >
|
||||
{
|
||||
using Type = T <typename InheritMixins<Root, MixinList<Args...> >::Type>;
|
||||
};
|
||||
|
||||
template <typename Root>
|
||||
struct InheritMixins <Root, MixinList<> >
|
||||
{
|
||||
using Type = Root;
|
||||
};
|
||||
|
||||
template <typename Root, typename TList, typename Func>
|
||||
struct ForEachMixins;
|
||||
|
||||
template <typename Func, typename Root, template <typename> class T, template <typename> class ...Args>
|
||||
struct ForEachMixins <Root, MixinList<T, Args...>, Func>
|
||||
{
|
||||
using Type = typename InheritMixins<Root, MixinList<T, Args...> >::Type;
|
||||
|
||||
template <typename ...A>
|
||||
static bool forEach(A && ...args) {
|
||||
if(Func::template forEach<Type>(args...)) {
|
||||
return ForEachMixins<Root, MixinList<Args...>, Func>::forEach(std::forward<A>(args)...);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
template <typename Root, typename Func>
|
||||
struct ForEachMixins <Root, MixinList<>, Func>
|
||||
{
|
||||
using Type = Root;
|
||||
|
||||
template <typename ...A>
|
||||
static bool forEach(A && .../*args*/) {
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
template <typename T, typename ...Args>
|
||||
struct HasFunctionMixinBeforeDispatch
|
||||
{
|
||||
template <typename C> static std::true_type test(
|
||||
decltype(std::declval<C>().mixinBeforeDispatch(std::declval<Args>()...)) *
|
||||
);
|
||||
template <typename C> static std::false_type test(...);
|
||||
|
||||
enum { value = !! decltype(test<T>(0))() };
|
||||
};
|
||||
|
||||
|
||||
} //namespace internal_
|
||||
@@ -1,174 +0,0 @@
|
||||
#ifndef EVENTQUEUE_I_H
|
||||
#define EVENTQUEUE_I_H
|
||||
|
||||
#include <array>
|
||||
#include <cassert>
|
||||
|
||||
namespace eventpp {
|
||||
|
||||
namespace internal_ {
|
||||
|
||||
template <size_t ...Indexes>
|
||||
struct IndexSequence
|
||||
{
|
||||
};
|
||||
|
||||
template <size_t N, size_t ...Indexes>
|
||||
struct MakeIndexSequence : MakeIndexSequence <N - 1, N - 1, Indexes...>
|
||||
{
|
||||
};
|
||||
|
||||
template <std::size_t ...Indexes>
|
||||
struct MakeIndexSequence<0, Indexes...>
|
||||
{
|
||||
using Type = IndexSequence<Indexes...>;
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
struct CounterGuard
|
||||
{
|
||||
explicit CounterGuard(T & v) : value(v) {
|
||||
++value;
|
||||
}
|
||||
|
||||
~CounterGuard() {
|
||||
--value;
|
||||
}
|
||||
|
||||
T & value;
|
||||
};
|
||||
|
||||
using DtorFunc = void (*)(void *);
|
||||
|
||||
template <typename T>
|
||||
void commonDtor(void * instance)
|
||||
{
|
||||
reinterpret_cast<T *>(instance)->~T();
|
||||
}
|
||||
|
||||
// used by EventQueue
|
||||
template <typename T>
|
||||
class BufferedItem
|
||||
{
|
||||
public:
|
||||
using ValueType = T;
|
||||
|
||||
public:
|
||||
explicit BufferedItem() : buffer(), dtor(nullptr)
|
||||
{
|
||||
}
|
||||
|
||||
~BufferedItem()
|
||||
{
|
||||
if(dtor != nullptr) {
|
||||
clear();
|
||||
}
|
||||
}
|
||||
|
||||
BufferedItem(BufferedItem &&) = delete;
|
||||
BufferedItem(const BufferedItem &) = delete;
|
||||
BufferedItem & operator = (const BufferedItem &) = delete;
|
||||
|
||||
void set(T && item) {
|
||||
assert(dtor == nullptr);
|
||||
|
||||
new (buffer.data()) T(std::forward<T>(item));
|
||||
dtor = &commonDtor<T>;
|
||||
}
|
||||
|
||||
T & get() {
|
||||
assert(dtor != nullptr);
|
||||
|
||||
return *reinterpret_cast<T *>(buffer.data());
|
||||
}
|
||||
|
||||
const T & get() const {
|
||||
assert(dtor != nullptr);
|
||||
|
||||
return *reinterpret_cast<const T *>(buffer.data());
|
||||
}
|
||||
|
||||
void clear() {
|
||||
assert(dtor != nullptr);
|
||||
|
||||
dtor(buffer.data());
|
||||
dtor = nullptr;
|
||||
}
|
||||
|
||||
bool empty() const {
|
||||
return dtor == nullptr;
|
||||
}
|
||||
|
||||
private:
|
||||
std::array<char, sizeof(T)> buffer;
|
||||
DtorFunc dtor;
|
||||
};
|
||||
|
||||
|
||||
// used by HeterEventQueue
|
||||
template <size_t Size>
|
||||
class BufferedUnion
|
||||
{
|
||||
public:
|
||||
explicit BufferedUnion() : buffer(), dtor(nullptr)
|
||||
{
|
||||
}
|
||||
|
||||
~BufferedUnion()
|
||||
{
|
||||
if(dtor != nullptr) {
|
||||
clear();
|
||||
}
|
||||
}
|
||||
|
||||
BufferedUnion(BufferedUnion &&) = delete;
|
||||
BufferedUnion(const BufferedUnion &) = delete;
|
||||
BufferedUnion & operator = (const BufferedUnion &) = delete;
|
||||
|
||||
template <typename U>
|
||||
void set(U && item) {
|
||||
static_assert(sizeof(U) <= Size, "Item is too large to fit in BufferedUnion");
|
||||
assert(dtor == nullptr);
|
||||
|
||||
new (buffer.data()) U(std::forward<U>(item));
|
||||
dtor = &commonDtor<U>;
|
||||
}
|
||||
|
||||
template <typename U>
|
||||
U & get() {
|
||||
assert(dtor != nullptr);
|
||||
|
||||
return *reinterpret_cast<U *>(buffer.data());
|
||||
}
|
||||
|
||||
template <typename U>
|
||||
const U & get() const {
|
||||
assert(dtor != nullptr);
|
||||
|
||||
return *reinterpret_cast<const U *>(buffer.data());
|
||||
}
|
||||
|
||||
void clear() {
|
||||
assert(dtor != nullptr);
|
||||
|
||||
dtor(buffer.data());
|
||||
dtor = nullptr;
|
||||
}
|
||||
|
||||
bool empty() const {
|
||||
return dtor == nullptr;
|
||||
}
|
||||
|
||||
private:
|
||||
std::array<char, Size> buffer;
|
||||
DtorFunc dtor;
|
||||
};
|
||||
|
||||
|
||||
} //namespace internal_
|
||||
|
||||
} //namespace eventpp
|
||||
|
||||
|
||||
#endif
|
||||
|
||||
@@ -1,292 +0,0 @@
|
||||
// eventpp library
|
||||
// Copyright (C) 2018 Wang Qi (wqking)
|
||||
// Github: https://github.com/wqking/eventpp
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#ifndef HETERCALLBACKLIST_I_H
|
||||
#define HETERCALLBACKLIST_I_H
|
||||
|
||||
#include "typeutil_i.h"
|
||||
|
||||
#include <tuple>
|
||||
|
||||
namespace eventpp {
|
||||
|
||||
/*
|
||||
// We can't use std::tuple as HeterTuple because std::tuple is instantialized
|
||||
// somewhere in the Map in HeterEventDispatcherBase, that causes compile error
|
||||
// for that function type can't be declared.
|
||||
template <typename ...Types>
|
||||
using HeterTuple = std::tuple<Types...>;
|
||||
|
||||
template <typename T>
|
||||
struct HeterTupleSize;
|
||||
|
||||
template <typename ...Types>
|
||||
struct HeterTupleSize <HeterTuple <Types...> >
|
||||
{
|
||||
enum { value = std::tuple_size<HeterTuple <Types...> >::value };
|
||||
};
|
||||
*/
|
||||
|
||||
template <typename ...Types>
|
||||
struct HeterTuple
|
||||
{
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
struct HeterTupleSize;
|
||||
|
||||
template <typename ...Types>
|
||||
struct HeterTupleSize <HeterTuple <Types...> >
|
||||
{
|
||||
enum { value = sizeof...(Types) };
|
||||
};
|
||||
|
||||
namespace internal_ {
|
||||
|
||||
template <typename T>
|
||||
struct FindPrototypeDefaultArgTransformer
|
||||
{
|
||||
using type = T;
|
||||
};
|
||||
|
||||
template <
|
||||
int N,
|
||||
typename PrototypeList_,
|
||||
typename Callable,
|
||||
template <typename> class ArgTransformer = FindPrototypeDefaultArgTransformer,
|
||||
int M = HeterTupleSize<PrototypeList_>::value,
|
||||
typename Enabled = void
|
||||
>
|
||||
struct FindPrototypeByCallableFromIndex;
|
||||
|
||||
template <
|
||||
int N,
|
||||
typename RT,
|
||||
typename ...Args,
|
||||
typename ...Others,
|
||||
typename Callable,
|
||||
template <typename> class ArgTransformer,
|
||||
int M
|
||||
>
|
||||
struct FindPrototypeByCallableFromIndex <
|
||||
N,
|
||||
HeterTuple<RT (Args...), Others...>,
|
||||
Callable,
|
||||
ArgTransformer,
|
||||
M,
|
||||
typename std::enable_if<(N < M)>::type
|
||||
>
|
||||
{
|
||||
enum { canInvoke = CanInvoke<Callable, typename ArgTransformer<Args>::type...>::value };
|
||||
|
||||
using Prototype = typename std::conditional<
|
||||
canInvoke,
|
||||
RT (Args...),
|
||||
typename FindPrototypeByCallableFromIndex<N + 1, HeterTuple<Others...>, Callable, ArgTransformer, M>::Prototype
|
||||
>::type;
|
||||
|
||||
using ArgsTuple = typename std::conditional<
|
||||
canInvoke,
|
||||
std::tuple<typename std::remove_cv<typename std::remove_reference<Args>::type>::type...>,
|
||||
typename FindPrototypeByCallableFromIndex<N + 1, HeterTuple<Others...>, Callable, ArgTransformer, M>::ArgsTuple
|
||||
>::type;
|
||||
|
||||
enum {
|
||||
index = canInvoke
|
||||
? N
|
||||
: FindPrototypeByCallableFromIndex<N + 1, HeterTuple<Others...>, Callable, ArgTransformer, M>::index
|
||||
};
|
||||
};
|
||||
|
||||
template <
|
||||
int N,
|
||||
typename PrototypeList_,
|
||||
typename Callable,
|
||||
template <typename> class ArgTransformer,
|
||||
int M
|
||||
>
|
||||
struct FindPrototypeByCallableFromIndex <
|
||||
N,
|
||||
PrototypeList_,
|
||||
Callable,
|
||||
ArgTransformer,
|
||||
M,
|
||||
typename std::enable_if<(N >= M)>::type
|
||||
>
|
||||
{
|
||||
using Prototype = void;
|
||||
|
||||
using ArgsTuple = std::tuple<>;
|
||||
|
||||
enum {
|
||||
index = -1
|
||||
};
|
||||
};
|
||||
|
||||
template <typename PrototypeList_, typename Callable, template <typename> class ArgTransformer = FindPrototypeDefaultArgTransformer>
|
||||
struct FindPrototypeByCallable : public FindPrototypeByCallableFromIndex <0, PrototypeList_, Callable, ArgTransformer>
|
||||
{
|
||||
};
|
||||
|
||||
template <int N, typename PrototypeList_, typename ...InArgs>
|
||||
struct FindPrototypeByArgsFromIndex;
|
||||
|
||||
template <int N, typename RT, typename ...Args, typename ...Others, typename ...InArgs>
|
||||
struct FindPrototypeByArgsFromIndex <N, HeterTuple<RT (Args...), Others...>, InArgs...>
|
||||
{
|
||||
enum { canInvoke = CanInvoke<RT (Args...), InArgs...>::value };
|
||||
|
||||
using Prototype = typename std::conditional<
|
||||
canInvoke,
|
||||
RT (Args...),
|
||||
typename FindPrototypeByArgsFromIndex<N + 1, HeterTuple<Others...>, InArgs...>::Prototype
|
||||
>::type;
|
||||
|
||||
using ArgsTuple = typename std::conditional<
|
||||
canInvoke,
|
||||
std::tuple<typename std::remove_cv<typename std::remove_reference<Args>::type>::type...>,
|
||||
typename FindPrototypeByArgsFromIndex<N + 1, HeterTuple<Others...>, InArgs...>::ArgsTuple
|
||||
>::type;
|
||||
|
||||
enum {
|
||||
index = canInvoke
|
||||
? N
|
||||
: FindPrototypeByArgsFromIndex<N + 1, HeterTuple<Others...>, InArgs...>::index
|
||||
};
|
||||
};
|
||||
|
||||
template <int N, typename ...InArgs>
|
||||
struct FindPrototypeByArgsFromIndex <N, HeterTuple<>, InArgs...>
|
||||
{
|
||||
using Prototype = void;
|
||||
|
||||
using ArgsTuple = std::tuple<>;
|
||||
|
||||
enum { index = -1 };
|
||||
};
|
||||
|
||||
template <typename PrototypeList_, typename ...InArgs>
|
||||
struct FindPrototypeByArgs : public FindPrototypeByArgsFromIndex <0, PrototypeList_, InArgs...>
|
||||
{
|
||||
};
|
||||
|
||||
template <int I, int N, typename PrototypeList_>
|
||||
struct FindPrototypeByIndexHelper;
|
||||
|
||||
template <int I, int N, typename RT, typename ...Args, typename ...Others>
|
||||
struct FindPrototypeByIndexHelper <I, N, HeterTuple<RT (Args...), Others...> >
|
||||
{
|
||||
using NextType = FindPrototypeByIndexHelper<I + 1, N, HeterTuple<Others...> >;
|
||||
using Prototype = typename NextType::Prototype;
|
||||
|
||||
using ArgsTuple = typename NextType::ArgsTuple;
|
||||
|
||||
enum { index = NextType::index };
|
||||
};
|
||||
|
||||
template <int N, typename RT, typename ...Args, typename ...Others>
|
||||
struct FindPrototypeByIndexHelper <N, N, HeterTuple<RT (Args...), Others...> >
|
||||
{
|
||||
using Prototype = RT (Args...);
|
||||
|
||||
using ArgsTuple = HeterTuple<typename std::remove_cv<typename std::remove_reference<Args>::type>::type...>;
|
||||
|
||||
enum { index = N };
|
||||
};
|
||||
|
||||
template <int I, int N>
|
||||
struct FindPrototypeByIndexHelper <I, N, HeterTuple<>>
|
||||
{
|
||||
using Prototype = void;
|
||||
|
||||
using ArgsTuple = HeterTuple<>;
|
||||
|
||||
enum { index = -1 };
|
||||
};
|
||||
|
||||
template <typename PrototypeList_, int N>
|
||||
struct FindPrototypeByIndex : public FindPrototypeByIndexHelper <0, N, PrototypeList_>
|
||||
{
|
||||
};
|
||||
|
||||
template <typename PrototypeList_, template <typename ...> class Record>
|
||||
struct GetCallablePrototypeMaxSize;
|
||||
|
||||
template <typename RT, typename ...Args, typename ...Others, template <typename ...> class Record>
|
||||
struct GetCallablePrototypeMaxSize <HeterTuple<RT (Args...), Others...>, Record>
|
||||
{
|
||||
enum {
|
||||
my = sizeof(Record<Args...>),
|
||||
other = GetCallablePrototypeMaxSize<HeterTuple<Others...>, Record>::value
|
||||
};
|
||||
enum { value = (my > other ? (int)my : (int)other) };
|
||||
};
|
||||
|
||||
template <template <typename ...> class Record>
|
||||
struct GetCallablePrototypeMaxSize <HeterTuple<>, Record>
|
||||
{
|
||||
enum { value = 1 }; // set minimum size to 1 instead of 0
|
||||
};
|
||||
|
||||
template <typename List, typename Item>
|
||||
struct PrependHeterTuple;
|
||||
|
||||
template <typename Item, typename ...Types>
|
||||
struct PrependHeterTuple <HeterTuple<Types...>, Item>
|
||||
{
|
||||
using Type = HeterTuple<Item, Types...>;
|
||||
};
|
||||
|
||||
template <typename List, typename Replacement>
|
||||
struct ReplaceReturnTypeList;
|
||||
|
||||
template <typename Replacement, typename RT, typename ...Args, typename ...Others>
|
||||
struct ReplaceReturnTypeList <HeterTuple<RT (Args...), Others...>, Replacement>
|
||||
{
|
||||
using Type = typename PrependHeterTuple<
|
||||
typename ReplaceReturnTypeList<HeterTuple<Others...>, Replacement>::Type,
|
||||
Replacement (Args...)
|
||||
>::Type;
|
||||
};
|
||||
|
||||
template <typename Replacement>
|
||||
struct ReplaceReturnTypeList <HeterTuple<>, Replacement>
|
||||
{
|
||||
using Type = HeterTuple<>;
|
||||
};
|
||||
|
||||
template <typename F, template <typename> class T>
|
||||
struct TransformArgumentsList;
|
||||
|
||||
template <template <typename> class T, typename RT, typename ...Args, typename ...Others>
|
||||
struct TransformArgumentsList <HeterTuple<RT (Args...), Others...>, T>
|
||||
{
|
||||
using Type = typename PrependHeterTuple<
|
||||
typename TransformArgumentsList<HeterTuple<Others...>, T>::Type,
|
||||
RT (typename T<Args>::type...)
|
||||
>::Type;
|
||||
};
|
||||
|
||||
template <template <typename> class T>
|
||||
struct TransformArgumentsList <HeterTuple<>, T>
|
||||
{
|
||||
using Type = HeterTuple<>;
|
||||
};
|
||||
|
||||
|
||||
} //namespace internal_
|
||||
|
||||
|
||||
} //namespace eventpp
|
||||
|
||||
#endif
|
||||
@@ -1,127 +0,0 @@
|
||||
// eventpp library
|
||||
// Copyright (C) 2018 Wang Qi (wqking)
|
||||
// Github: https://github.com/wqking/eventpp
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#ifndef TYPEUTIL_I_H
|
||||
#define TYPEUTIL_I_H
|
||||
|
||||
#include <utility>
|
||||
#include <tuple>
|
||||
|
||||
namespace eventpp {
|
||||
|
||||
namespace internal_ {
|
||||
|
||||
template <typename F, template <typename> class T>
|
||||
struct TransformArguments;
|
||||
|
||||
template <template <typename> class T, typename RT, typename ...Args>
|
||||
struct TransformArguments <RT (Args...), T>
|
||||
{
|
||||
using Type = RT (typename T<Args>::type...);
|
||||
};
|
||||
|
||||
template <typename F, typename Replacement>
|
||||
struct ReplaceReturnType;
|
||||
|
||||
template <typename Replacement, typename RT, typename ...Args>
|
||||
struct ReplaceReturnType <RT (Args...), Replacement>
|
||||
{
|
||||
using Type = Replacement (Args...);
|
||||
};
|
||||
|
||||
template <int N, int M>
|
||||
struct IntToConstantHelper
|
||||
{
|
||||
template <typename C, typename ...Args>
|
||||
static auto find(const int index, C && c, Args && ...args)
|
||||
-> decltype(std::declval<C>().template operator()<0>(std::declval<Args>()...))
|
||||
{
|
||||
if(N == index) {
|
||||
return c.template operator()<N>(std::forward<Args>(args)...);
|
||||
}
|
||||
else {
|
||||
return IntToConstantHelper<N + 1, M>::find(index, std::forward<C>(c), std::forward<Args>(args)...);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
template <int M>
|
||||
struct IntToConstantHelper <M, M>
|
||||
{
|
||||
template <typename C, typename ...Args>
|
||||
static auto find(const int /*index*/, C && c, Args && ...args)
|
||||
-> decltype(std::declval<C>().template operator()<0>(std::declval<Args>()...))
|
||||
{
|
||||
return decltype(c.template operator()<0>(std::forward<Args>(args)...))();
|
||||
}
|
||||
};
|
||||
|
||||
template <int M, typename C, typename ...Args>
|
||||
auto intToConstant(const int index, C && c, Args && ...args)
|
||||
-> decltype(std::declval<C>().template operator()<0>(std::declval<Args>()...))
|
||||
{
|
||||
return IntToConstantHelper<0, M>::find(index, std::forward<C>(c), std::forward<Args>(args)...);
|
||||
}
|
||||
|
||||
template <typename F, typename ...Args>
|
||||
struct CanInvoke
|
||||
{
|
||||
template <typename U, typename ...X>
|
||||
static auto invoke(int) -> decltype(std::declval<U>()(std::declval<X>()...), std::true_type());
|
||||
|
||||
template <typename U, typename ...X>
|
||||
static auto invoke(...) -> std::false_type;
|
||||
|
||||
enum {
|
||||
value = !! decltype(invoke<F, Args...>(0))()
|
||||
};
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
struct ShiftTuple;
|
||||
|
||||
template <typename A, typename ...Args>
|
||||
struct ShiftTuple <std::tuple<A, Args...> >
|
||||
{
|
||||
using Type = std::tuple<Args...>;
|
||||
};
|
||||
|
||||
template <>
|
||||
struct ShiftTuple <std::tuple<> >
|
||||
{
|
||||
using Type = std::tuple<>;
|
||||
};
|
||||
|
||||
// for compile time debug
|
||||
template<typename T>
|
||||
void printTypeInCompileTime(T * = 0)
|
||||
{
|
||||
static_assert(std::is_same<T, int>::value && ! std::is_same<T, int>::value, "The error shows the type name.");
|
||||
}
|
||||
template<int N>
|
||||
void printIntInCompileTime()
|
||||
{
|
||||
int n = 0;
|
||||
switch(n) {
|
||||
case N:
|
||||
case N:
|
||||
break;
|
||||
};
|
||||
}
|
||||
|
||||
} //namespace internal_
|
||||
|
||||
} //namespace eventpp
|
||||
|
||||
#endif
|
||||
|
||||
@@ -1,75 +0,0 @@
|
||||
// eventpp library
|
||||
// Copyright (C) 2018 Wang Qi (wqking)
|
||||
// Github: https://github.com/wqking/eventpp
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#ifndef MIXINFILTER_H_713231680355
|
||||
#define MIXINFILTER_H_713231680355
|
||||
|
||||
#include "../callbacklist.h"
|
||||
|
||||
namespace eventpp {
|
||||
|
||||
template <typename Base>
|
||||
class MixinFilter : public Base
|
||||
{
|
||||
private:
|
||||
using super = Base;
|
||||
|
||||
using BoolReferencePrototype = typename internal_::ReplaceReturnType<
|
||||
typename internal_::TransformArguments<
|
||||
typename super::Prototype,
|
||||
std::add_lvalue_reference
|
||||
>::Type,
|
||||
bool
|
||||
>::Type;
|
||||
|
||||
using Filter = std::function<BoolReferencePrototype>;
|
||||
using FilterList = CallbackList<BoolReferencePrototype>;
|
||||
|
||||
public:
|
||||
using FilterHandle = typename FilterList::Handle;
|
||||
|
||||
public:
|
||||
FilterHandle appendFilter(const Filter & filter)
|
||||
{
|
||||
return filterList.append(filter);
|
||||
}
|
||||
|
||||
bool removeFilter(const FilterHandle & filterHandle)
|
||||
{
|
||||
return filterList.remove(filterHandle);
|
||||
}
|
||||
|
||||
template <typename ...Args>
|
||||
bool mixinBeforeDispatch(Args && ...args) const {
|
||||
if(! filterList.empty()) {
|
||||
if(! filterList.forEachIf([&args...](typename FilterList::Callback & callback) {
|
||||
return callback(args...);
|
||||
})
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private:
|
||||
FilterList filterList;
|
||||
};
|
||||
|
||||
|
||||
} //namespace eventpp
|
||||
|
||||
|
||||
#endif
|
||||
|
||||
@@ -1,73 +0,0 @@
|
||||
// eventpp library
|
||||
// Copyright (C) 2018 Wang Qi (wqking)
|
||||
// Github: https://github.com/wqking/eventpp
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#ifndef MIXINHETERFILTER_H_990158796753
|
||||
#define MIXINHETERFILTER_H_990158796753
|
||||
|
||||
#include "../hetercallbacklist.h"
|
||||
|
||||
namespace eventpp {
|
||||
|
||||
template <typename Base>
|
||||
class MixinHeterFilter : public Base
|
||||
{
|
||||
private:
|
||||
using super = Base;
|
||||
|
||||
using BoolReferencePrototypeList = typename internal_::ReplaceReturnTypeList<
|
||||
typename internal_::TransformArgumentsList<
|
||||
typename super::PrototypeList,
|
||||
std::add_lvalue_reference
|
||||
>::Type,
|
||||
bool
|
||||
>::Type;
|
||||
|
||||
using FilterList = HeterCallbackList<BoolReferencePrototypeList>;
|
||||
|
||||
public:
|
||||
using FilterHandle = typename FilterList::Handle;
|
||||
|
||||
public:
|
||||
template <typename Callback>
|
||||
FilterHandle appendFilter(const Callback & filter)
|
||||
{
|
||||
return filterList.append(filter);
|
||||
}
|
||||
|
||||
bool removeFilter(const FilterHandle & filterHandle)
|
||||
{
|
||||
return filterList.remove(filterHandle);
|
||||
}
|
||||
|
||||
template <typename ...Args>
|
||||
bool mixinBeforeDispatch(Args && ...args) const {
|
||||
if(! filterList.template forEachIf<void (Args...)>([&args...](const typename std::function<bool (Args...)> & callback) -> bool {
|
||||
return callback(std::forward<Args>(args)...);
|
||||
})
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private:
|
||||
FilterList filterList;
|
||||
};
|
||||
|
||||
|
||||
} //namespace eventpp
|
||||
|
||||
|
||||
#endif
|
||||
|
||||
@@ -1,247 +0,0 @@
|
||||
// eventpp library
|
||||
// Copyright (C) 2018 Wang Qi (wqking)
|
||||
// Github: https://github.com/wqking/eventpp
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#ifndef ANYDATA_H_320827729782
|
||||
#define ANYDATA_H_320827729782
|
||||
|
||||
#include <array>
|
||||
#include <type_traits>
|
||||
#include <cstdint>
|
||||
#include <cassert>
|
||||
#include <memory>
|
||||
|
||||
namespace eventpp {
|
||||
|
||||
namespace anydata_internal_ {
|
||||
|
||||
template <typename T>
|
||||
void funcDeleteObject(void * object)
|
||||
{
|
||||
delete static_cast<T *>(object);
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
void funcFreeObject(void * object)
|
||||
{
|
||||
static_cast<T *>(object)->~T();
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
auto doFuncMoveConstruct(void * object, void * buffer)
|
||||
-> typename std::enable_if<std::is_move_constructible<T>::value>::type
|
||||
{
|
||||
new (buffer) T(std::move(*(T *)object));
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
auto doFuncMoveConstruct(void * object, void * buffer)
|
||||
-> typename std::enable_if<! std::is_move_constructible<T>::value>::type
|
||||
{
|
||||
static_assert(std::is_move_constructible<T>::value, "AnyData: object must be either copy or move constructible");
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
void funcMoveConstruct(void * object, void * buffer)
|
||||
{
|
||||
doFuncMoveConstruct<T>(object, buffer);
|
||||
}
|
||||
|
||||
struct AnyDataFunctions
|
||||
{
|
||||
void (*free)(void *);
|
||||
void (*moveConstruct)(void *, void *);
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
const AnyDataFunctions * doGetAnyDataFunctions()
|
||||
{
|
||||
static const AnyDataFunctions functions {
|
||||
&funcFreeObject<T>,
|
||||
&funcMoveConstruct<T>
|
||||
};
|
||||
return &functions;
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
struct RemoveCvRef
|
||||
{
|
||||
using Type = typename std::remove_cv<typename std::remove_reference<T>::type>::type;
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
const AnyDataFunctions * getAnyDataFunctions()
|
||||
{
|
||||
using U = typename RemoveCvRef<T>::Type;
|
||||
return doGetAnyDataFunctions<U>();
|
||||
}
|
||||
|
||||
template <typename ...Ts>
|
||||
struct MaxSizeOf;
|
||||
|
||||
template <typename T, typename ...Ts>
|
||||
struct MaxSizeOf <T, Ts...>
|
||||
{
|
||||
static constexpr std::size_t otherSize = MaxSizeOf<Ts...>::value;
|
||||
static constexpr std::size_t tSize = sizeof(T);
|
||||
|
||||
static constexpr std::size_t value = tSize > otherSize ? tSize : otherSize;
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
struct MaxSizeOf <T>
|
||||
{
|
||||
static constexpr std::size_t value = sizeof(T);
|
||||
};
|
||||
|
||||
class LargeData
|
||||
{
|
||||
public:
|
||||
template <typename T>
|
||||
explicit LargeData(T && object) : data(), deleter() {
|
||||
using U = typename RemoveCvRef<T>::Type;
|
||||
deleter = &funcDeleteObject<U>;
|
||||
data = new U(std::forward<T>(object));
|
||||
}
|
||||
|
||||
~LargeData() {
|
||||
if(data != nullptr) {
|
||||
assert(deleter != nullptr);
|
||||
deleter(data);
|
||||
}
|
||||
}
|
||||
|
||||
LargeData(LargeData && other) : data(), deleter() {
|
||||
std::swap(data, other.data);
|
||||
std::swap(deleter, other.deleter);
|
||||
}
|
||||
|
||||
LargeData(const LargeData & other) = delete;
|
||||
LargeData & operator = (const LargeData & other) = delete;
|
||||
LargeData & operator = (LargeData && other) = delete;
|
||||
|
||||
const void * getAddress() const {
|
||||
return data;
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
bool isType() const {
|
||||
using U = typename RemoveCvRef<T>::Type;
|
||||
return deleter == &funcDeleteObject<U>;
|
||||
}
|
||||
|
||||
private:
|
||||
void * data;
|
||||
void (*deleter)(void *);
|
||||
};
|
||||
|
||||
} //namespace anydata_internal_
|
||||
|
||||
template <std::size_t maxSize_>
|
||||
class AnyData
|
||||
{
|
||||
private:
|
||||
using LargeData = anydata_internal_::LargeData;
|
||||
static constexpr std::size_t maxSize = maxSize_ < sizeof(LargeData) ? sizeof(LargeData) : maxSize_;
|
||||
|
||||
static_assert(maxSize > 0, "AnyData: maxSize must be greater than 0");
|
||||
|
||||
public:
|
||||
~AnyData() {
|
||||
if(functions != nullptr) {
|
||||
functions->free(buffer.data());
|
||||
}
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
AnyData(T && object,
|
||||
typename std::enable_if<(sizeof(typename anydata_internal_::RemoveCvRef<T>::Type) <= maxSize)>::type * = 0)
|
||||
: functions(anydata_internal_::getAnyDataFunctions<T>()), buffer() {
|
||||
using U = typename std::remove_reference<T>::type;
|
||||
new (buffer.data()) U(std::forward<T>(object));
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
AnyData(T && object,
|
||||
typename std::enable_if<(sizeof(typename anydata_internal_::RemoveCvRef<T>::Type) > maxSize)>::type * = 0)
|
||||
: functions(anydata_internal_::getAnyDataFunctions<LargeData>()), buffer() {
|
||||
new (buffer.data()) LargeData(std::forward<T>(object));
|
||||
}
|
||||
|
||||
AnyData(AnyData && other) : functions(other.functions), buffer() {
|
||||
if(functions != nullptr) {
|
||||
functions->moveConstruct(other.buffer.data(), buffer.data());
|
||||
}
|
||||
}
|
||||
|
||||
AnyData(const AnyData & other) = delete;
|
||||
AnyData(AnyData & other) = delete;
|
||||
AnyData & operator = (const AnyData & other) = delete;
|
||||
AnyData & operator = (AnyData && other) = delete;
|
||||
|
||||
template <typename T>
|
||||
const T & get() const {
|
||||
return *(T *)getAddress();
|
||||
}
|
||||
|
||||
const void * getAddress() const {
|
||||
assert(functions != nullptr);
|
||||
|
||||
if(! isLargerData()) {
|
||||
return buffer.data();
|
||||
}
|
||||
else {
|
||||
return ((const LargeData *)buffer.data())->getAddress();
|
||||
}
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
bool isType() const {
|
||||
if(! isLargerData()) {
|
||||
return anydata_internal_::getAnyDataFunctions<T>() == functions;
|
||||
}
|
||||
else {
|
||||
return ((const LargeData *)buffer.data())->isType<T>();
|
||||
}
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
operator T & () const {
|
||||
return *(T *)getAddress();
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
operator T * () const {
|
||||
return (T *)getAddress();
|
||||
}
|
||||
|
||||
private:
|
||||
bool isLargerData() const {
|
||||
return functions == anydata_internal_::getAnyDataFunctions<LargeData>();
|
||||
}
|
||||
|
||||
private:
|
||||
const anydata_internal_::AnyDataFunctions * functions;
|
||||
std::array<std::uint8_t, maxSize> buffer;
|
||||
};
|
||||
|
||||
template <typename ...Ts>
|
||||
constexpr std::size_t maxSizeOf()
|
||||
{
|
||||
return anydata_internal_::MaxSizeOf<Ts...>::value;
|
||||
}
|
||||
|
||||
} //namespace eventpp
|
||||
|
||||
|
||||
#endif
|
||||
|
||||
@@ -1,161 +0,0 @@
|
||||
// eventpp library
|
||||
// Copyright (C) 2018 Wang Qi (wqking)
|
||||
// Github: https://github.com/wqking/eventpp
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#ifndef ANYID_H_320827729782
|
||||
#define ANYID_H_320827729782
|
||||
|
||||
#include <functional>
|
||||
|
||||
namespace eventpp {
|
||||
|
||||
namespace anyid_internal_ {
|
||||
|
||||
template <typename T, typename Enabled = void>
|
||||
struct MakeHash;
|
||||
|
||||
template <typename T>
|
||||
struct MakeHash <T, typename std::enable_if<std::is_convertible<T, std::size_t>::value>::type>
|
||||
{
|
||||
std::size_t operator() (T value) const {
|
||||
return static_cast<std::size_t>(value);
|
||||
}
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
struct MakeHash <T, typename std::enable_if<! std::is_convertible<T, std::size_t>::value>::type>
|
||||
{
|
||||
std::size_t operator() (const T & value) const {
|
||||
return std::hash<T>()(value);
|
||||
}
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
class HasLess
|
||||
{
|
||||
template <typename C> static std::true_type test(decltype(std::declval<C>() < std::declval<C>()) *);
|
||||
template <typename C> static std::false_type test(...);
|
||||
|
||||
public:
|
||||
enum { value = !! decltype(test<T>(0))() };
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
auto compareLessThan(const T & a, const T & b)
|
||||
-> typename std::enable_if<HasLess<T>::value, bool>::type
|
||||
{
|
||||
return a < b;
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
auto compareLessThan(const T &, const T &)
|
||||
-> typename std::enable_if<! HasLess<T>::value, bool>::type
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
class HasEqual
|
||||
{
|
||||
template <typename C> static std::true_type test(decltype(std::declval<C>() == std::declval<C>()) *);
|
||||
template <typename C> static std::false_type test(...);
|
||||
|
||||
public:
|
||||
enum { value = !! decltype(test<T>(0))() };
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
auto compareEqual(const T & a, const T & b)
|
||||
-> typename std::enable_if<HasEqual<T>::value, bool>::type
|
||||
{
|
||||
return a == b;
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
auto compareEqual(const T &, const T &)
|
||||
-> typename std::enable_if<! HasEqual<T>::value, bool>::type
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
} //namespace anyid_internal_
|
||||
|
||||
struct EmptyAnyStorage
|
||||
{
|
||||
EmptyAnyStorage() {}
|
||||
|
||||
template <typename T>
|
||||
EmptyAnyStorage(const T &) {}
|
||||
};
|
||||
|
||||
template <template <typename> class Digester = std::hash, typename Storage = EmptyAnyStorage>
|
||||
class AnyId
|
||||
{
|
||||
public:
|
||||
using DigestType = decltype(std::declval<Digester<int>>()(0));
|
||||
|
||||
public:
|
||||
AnyId() : digest(), value() {
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
AnyId(const T & value)
|
||||
: digest(Digester<T>()(value)), value(value)
|
||||
{
|
||||
}
|
||||
|
||||
DigestType getDigest() const {
|
||||
return digest;
|
||||
}
|
||||
|
||||
const Storage & getValue() const {
|
||||
return value;
|
||||
}
|
||||
|
||||
private:
|
||||
DigestType digest;
|
||||
Storage value;
|
||||
};
|
||||
|
||||
template <template <typename> class Digester, typename Storage>
|
||||
bool operator == (const AnyId<Digester, Storage> & a, const AnyId<Digester, Storage> & b)
|
||||
{
|
||||
return a.getDigest() == b.getDigest() && anyid_internal_::compareEqual(a.getValue(), b.getValue());
|
||||
}
|
||||
|
||||
template <template <typename> class Digester, typename Storage>
|
||||
bool operator < (const AnyId<Digester, Storage> & a, const AnyId<Digester, Storage> & b)
|
||||
{
|
||||
return (a.getDigest() < b.getDigest())
|
||||
|| (anyid_internal_::compareLessThan(a.getValue(), b.getValue()) && a.getDigest() == b.getDigest())
|
||||
;
|
||||
}
|
||||
|
||||
using AnyHashableId = AnyId<>;
|
||||
|
||||
} //namespace eventpp
|
||||
|
||||
namespace std
|
||||
{
|
||||
template <template <typename> class Digester, typename Storage>
|
||||
struct hash<eventpp::AnyId<Digester, Storage> >
|
||||
{
|
||||
std::size_t operator()(const eventpp::AnyId<Digester, Storage> & value) const noexcept
|
||||
{
|
||||
return eventpp::anyid_internal_::MakeHash<typename eventpp::AnyId<Digester, Storage>::DigestType>()(value.getDigest());
|
||||
}
|
||||
};
|
||||
} //namespace std
|
||||
|
||||
#endif
|
||||
|
||||
@@ -1,136 +0,0 @@
|
||||
// eventpp library
|
||||
// Copyright (C) 2018 Wang Qi (wqking)
|
||||
// Github: https://github.com/wqking/eventpp
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#ifndef ARGUMENTADAPTER_H_566280692673
|
||||
#define ARGUMENTADAPTER_H_566280692673
|
||||
|
||||
#include <memory>
|
||||
|
||||
namespace eventpp {
|
||||
|
||||
namespace adapter_internal_ {
|
||||
|
||||
template <typename T>
|
||||
struct StaticCast
|
||||
{
|
||||
template <typename U>
|
||||
static T cast(U && value)
|
||||
{
|
||||
return static_cast<T>(value);
|
||||
}
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
struct StaticCast<std::shared_ptr<T> >
|
||||
{
|
||||
template <typename U>
|
||||
static std::shared_ptr<T> cast(U && value)
|
||||
{
|
||||
return std::static_pointer_cast<T>(value);
|
||||
}
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
struct IsSharedPtr
|
||||
{
|
||||
enum { value = false };
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
struct IsSharedPtr<std::shared_ptr<T> >
|
||||
{
|
||||
enum { value = true };
|
||||
};
|
||||
|
||||
template <typename ...Args>
|
||||
struct IsAnySharedPtr
|
||||
{
|
||||
enum { value = false };
|
||||
};
|
||||
|
||||
template <typename First, typename ...Others>
|
||||
struct IsAnySharedPtr <First, Others...>
|
||||
{
|
||||
enum { value = IsSharedPtr<First>::value
|
||||
|| IsAnySharedPtr<Others...>::value };
|
||||
};
|
||||
|
||||
} //namespace adapter_internal_
|
||||
|
||||
template <typename Func, typename Prototype, typename IsSharedPtr = void>
|
||||
struct ArgumentAdapter;
|
||||
|
||||
template <typename Func, typename R, typename ...Args>
|
||||
struct ArgumentAdapter <
|
||||
Func,
|
||||
R(Args...),
|
||||
typename std::enable_if<! adapter_internal_::IsAnySharedPtr<Args...>::value>::type
|
||||
>
|
||||
{
|
||||
explicit ArgumentAdapter(Func f)
|
||||
: func(std::move(f))
|
||||
{
|
||||
}
|
||||
|
||||
template <typename ...A>
|
||||
void operator() (A &&...args) {
|
||||
func(std::forward<Args>(static_cast<Args>(args))...);
|
||||
}
|
||||
|
||||
Func func;
|
||||
};
|
||||
|
||||
template <typename Func, typename R, typename ...Args>
|
||||
struct ArgumentAdapter <
|
||||
Func,
|
||||
R(Args...),
|
||||
typename std::enable_if<adapter_internal_::IsAnySharedPtr<Args...>::value>::type
|
||||
>
|
||||
{
|
||||
explicit ArgumentAdapter(Func f)
|
||||
: func(std::move(f))
|
||||
{
|
||||
}
|
||||
|
||||
template <typename ...A>
|
||||
void operator() (A &&...args) {
|
||||
func(std::forward<Args>(adapter_internal_::StaticCast<Args>::cast(args))...);
|
||||
}
|
||||
|
||||
Func func;
|
||||
};
|
||||
|
||||
template <template <typename> class Func, typename R, typename ...Args>
|
||||
ArgumentAdapter<Func<R(Args...)>, R(Args...)> argumentAdapter(Func<R(Args...)> func)
|
||||
{
|
||||
return ArgumentAdapter<Func<R(Args...)>, R(Args...)>(std::move(func));
|
||||
}
|
||||
|
||||
template <typename Prototype, typename Func>
|
||||
ArgumentAdapter<Func, Prototype> argumentAdapter(Func func)
|
||||
{
|
||||
return ArgumentAdapter<Func, Prototype>(std::move(func));
|
||||
}
|
||||
|
||||
template <typename R, typename ...Args>
|
||||
ArgumentAdapter<R(*)(Args...), R(Args...)> argumentAdapter(R(*func)(Args...))
|
||||
{
|
||||
return ArgumentAdapter<R(*)(Args...), R(Args...)>(std::move(func));
|
||||
}
|
||||
|
||||
|
||||
} //namespace eventpp
|
||||
|
||||
|
||||
#endif
|
||||
|
||||
@@ -1,50 +0,0 @@
|
||||
// eventpp library
|
||||
// Copyright (C) 2018 Wang Qi (wqking)
|
||||
// Github: https://github.com/wqking/eventpp
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#ifndef CONDITIONALFUNCTOR_H_828958739581
|
||||
#define CONDITIONALFUNCTOR_H_828958739581
|
||||
|
||||
#include <utility>
|
||||
|
||||
namespace eventpp {
|
||||
|
||||
template <typename Func, typename Condition>
|
||||
struct ConditionalFunctor
|
||||
{
|
||||
ConditionalFunctor(Func f, Condition condition)
|
||||
: func(std::move(f)), condition(std::move(condition))
|
||||
{
|
||||
}
|
||||
|
||||
template <typename ...A>
|
||||
void operator() (A &&...args) {
|
||||
if(condition(args...)) {
|
||||
func(std::forward<A>(args)...);
|
||||
}
|
||||
}
|
||||
|
||||
Func func;
|
||||
Condition condition;
|
||||
};
|
||||
|
||||
template <typename Func, typename Condition>
|
||||
ConditionalFunctor<Func, Condition> conditionalFunctor(Func func, Condition condition)
|
||||
{
|
||||
return ConditionalFunctor<Func, Condition>(std::move(func), std::move(condition));
|
||||
}
|
||||
|
||||
|
||||
} //namespace eventpp
|
||||
|
||||
#endif
|
||||
|
||||
@@ -1,222 +0,0 @@
|
||||
// eventpp library
|
||||
// Copyright (C) 2018 Wang Qi (wqking)
|
||||
// Github: https://github.com/wqking/eventpp
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#ifndef CONDITIONALREMOVER_H_882115092280
|
||||
#define CONDITIONALREMOVER_H_882115092280
|
||||
|
||||
#include "../eventpolicies.h"
|
||||
|
||||
namespace eventpp {
|
||||
|
||||
template <typename DispatcherType, typename Enabled = void>
|
||||
class ConditionalRemover;
|
||||
|
||||
template <typename DispatcherType>
|
||||
class ConditionalRemover <
|
||||
DispatcherType,
|
||||
typename std::enable_if<std::is_base_of<TagEventDispatcher, DispatcherType>::value>::type
|
||||
>
|
||||
{
|
||||
private:
|
||||
template <typename Callback, typename Condition>
|
||||
struct ItemByCondition
|
||||
{
|
||||
struct Data
|
||||
{
|
||||
Condition shouldRemove;
|
||||
DispatcherType & dispatcher;
|
||||
typename DispatcherType::Event event;
|
||||
Callback listener;
|
||||
typename DispatcherType::Handle handle;
|
||||
};
|
||||
|
||||
template <typename ...Args>
|
||||
auto operator() (Args && ...args) const
|
||||
-> typename std::enable_if<internal_::CanInvoke<Condition, Args...>::value>::type {
|
||||
if(data->shouldRemove(args...)) {
|
||||
data->dispatcher.removeListener(data->event, data->handle);
|
||||
}
|
||||
data->listener(std::forward<Args>(args)...);
|
||||
}
|
||||
|
||||
template <typename ...Args>
|
||||
auto operator() (Args && ...args) const
|
||||
-> typename std::enable_if<! internal_::CanInvoke<Condition, Args...>::value>::type {
|
||||
if(data->shouldRemove()) {
|
||||
data->dispatcher.removeListener(data->event, data->handle);
|
||||
}
|
||||
data->listener(std::forward<Args>(args)...);
|
||||
}
|
||||
|
||||
std::shared_ptr<Data> data;
|
||||
};
|
||||
|
||||
public:
|
||||
explicit ConditionalRemover(DispatcherType & dispatcher)
|
||||
: dispatcher(dispatcher)
|
||||
{
|
||||
}
|
||||
|
||||
template <typename Callback, typename Condition>
|
||||
typename DispatcherType::Handle appendListener(
|
||||
const typename DispatcherType::Event & event,
|
||||
const Callback & listener,
|
||||
const Condition & condition
|
||||
)
|
||||
{
|
||||
using Wrapper = ItemByCondition<Callback, Condition>;
|
||||
auto data = std::make_shared<typename Wrapper::Data>(typename Wrapper::Data {
|
||||
condition, dispatcher, event, listener, typename DispatcherType::Handle()
|
||||
});
|
||||
data->handle = dispatcher.appendListener(event, Wrapper{data});
|
||||
return data->handle;
|
||||
}
|
||||
|
||||
template <typename Callback, typename Condition>
|
||||
typename DispatcherType::Handle prependListener(
|
||||
const typename DispatcherType::Event & event,
|
||||
const Callback & listener,
|
||||
const Condition & condition
|
||||
)
|
||||
{
|
||||
using Wrapper = ItemByCondition<Callback, Condition>;
|
||||
auto data = std::make_shared<typename Wrapper::Data>(typename Wrapper::Data {
|
||||
condition, dispatcher, event, listener, typename DispatcherType::Handle()
|
||||
});
|
||||
data->handle = dispatcher.prependListener(event, Wrapper{data});
|
||||
return data->handle;
|
||||
}
|
||||
|
||||
template <typename Callback, typename Condition>
|
||||
typename DispatcherType::Handle insertListener(
|
||||
const typename DispatcherType::Event & event,
|
||||
const Callback & listener,
|
||||
const typename DispatcherType::Handle & before,
|
||||
const Condition & condition
|
||||
)
|
||||
{
|
||||
using Wrapper = ItemByCondition<Callback, Condition>;
|
||||
auto data = std::make_shared<typename Wrapper::Data>(typename Wrapper::Data {
|
||||
condition, dispatcher, event, listener, typename DispatcherType::Handle()
|
||||
});
|
||||
data->handle = dispatcher.insertListener(event, Wrapper{data}, before);
|
||||
return data->handle;
|
||||
}
|
||||
|
||||
private:
|
||||
DispatcherType & dispatcher;
|
||||
};
|
||||
|
||||
template <typename CallbackListType>
|
||||
class ConditionalRemover <
|
||||
CallbackListType,
|
||||
typename std::enable_if<std::is_base_of<TagCallbackList, CallbackListType>::value>::type
|
||||
>
|
||||
{
|
||||
private:
|
||||
template <typename Callback, typename Condition>
|
||||
struct ItemByCondition
|
||||
{
|
||||
struct Data
|
||||
{
|
||||
Condition shouldRemove;
|
||||
CallbackListType & callbackList;
|
||||
Callback listener;
|
||||
typename CallbackListType::Handle handle;
|
||||
};
|
||||
|
||||
template <typename ...Args>
|
||||
auto operator() (Args && ...args) const
|
||||
-> typename std::enable_if<internal_::CanInvoke<Condition, Args...>::value>::type const {
|
||||
if(data->shouldRemove(args...)) {
|
||||
data->callbackList.remove(data->handle);
|
||||
}
|
||||
data->listener(std::forward<Args>(args)...);
|
||||
}
|
||||
|
||||
template <typename ...Args>
|
||||
auto operator() (Args && ...args) const
|
||||
-> typename std::enable_if<! internal_::CanInvoke<Condition, Args...>::value>::type {
|
||||
if(data->shouldRemove()) {
|
||||
data->callbackList.remove(data->handle);
|
||||
}
|
||||
data->listener(std::forward<Args>(args)...);
|
||||
}
|
||||
|
||||
std::shared_ptr<Data> data;
|
||||
};
|
||||
|
||||
public:
|
||||
explicit ConditionalRemover(CallbackListType & callbackList)
|
||||
: callbackList(callbackList)
|
||||
{
|
||||
}
|
||||
|
||||
template <typename Callback, typename Condition>
|
||||
typename CallbackListType::Handle append(
|
||||
const Callback & listener,
|
||||
const Condition & condition
|
||||
)
|
||||
{
|
||||
using Wrapper = ItemByCondition<Callback, Condition>;
|
||||
auto data = std::make_shared<typename Wrapper::Data>(typename Wrapper::Data {
|
||||
condition, callbackList, listener, typename CallbackListType::Handle()
|
||||
});
|
||||
data->handle = callbackList.append(Wrapper{data});
|
||||
return data->handle;
|
||||
}
|
||||
|
||||
template <typename Callback, typename Condition>
|
||||
typename CallbackListType::Handle prepend(
|
||||
const Callback & listener,
|
||||
const Condition & condition
|
||||
)
|
||||
{
|
||||
using Wrapper = ItemByCondition<Callback, Condition>;
|
||||
auto data = std::make_shared<typename Wrapper::Data>(typename Wrapper::Data {
|
||||
condition, callbackList, listener, typename CallbackListType::Handle()
|
||||
});
|
||||
data->handle = callbackList.prepend(Wrapper{data});
|
||||
return data->handle;
|
||||
}
|
||||
|
||||
template <typename Callback, typename Condition>
|
||||
typename CallbackListType::Handle insert(
|
||||
const Callback & listener,
|
||||
const typename CallbackListType::Handle & before,
|
||||
const Condition & condition
|
||||
)
|
||||
{
|
||||
using Wrapper = ItemByCondition<Callback, Condition>;
|
||||
auto data = std::make_shared<typename Wrapper::Data>(typename Wrapper::Data {
|
||||
condition, callbackList, listener, typename CallbackListType::Handle()
|
||||
});
|
||||
data->handle = callbackList.insert(Wrapper{data}, before);
|
||||
return data->handle;
|
||||
}
|
||||
|
||||
private:
|
||||
CallbackListType & callbackList;
|
||||
};
|
||||
|
||||
template <typename DispatcherType>
|
||||
ConditionalRemover<DispatcherType> conditionalRemover(DispatcherType & dispatcher)
|
||||
{
|
||||
return ConditionalRemover<DispatcherType>(dispatcher);
|
||||
}
|
||||
|
||||
|
||||
} //namespace eventpp
|
||||
|
||||
#endif
|
||||
|
||||
@@ -1,196 +0,0 @@
|
||||
// eventpp library
|
||||
// Copyright (C) 2018 Wang Qi (wqking)
|
||||
// Github: https://github.com/wqking/eventpp
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#ifndef COUNTERREMOVER_H_211532679833
|
||||
#define COUNTERREMOVER_H_211532679833
|
||||
|
||||
#include "../eventpolicies.h"
|
||||
|
||||
namespace eventpp {
|
||||
|
||||
template <typename DispatcherType, typename Enabled = void>
|
||||
class CounterRemover;
|
||||
|
||||
template <typename DispatcherType>
|
||||
class CounterRemover <
|
||||
DispatcherType,
|
||||
typename std::enable_if<std::is_base_of<TagEventDispatcher, DispatcherType>::value>::type
|
||||
>
|
||||
{
|
||||
private:
|
||||
template <typename Callback>
|
||||
struct Wrapper
|
||||
{
|
||||
struct Data
|
||||
{
|
||||
int triggerCount;
|
||||
DispatcherType & dispatcher;
|
||||
typename DispatcherType::Event event;
|
||||
Callback listener;
|
||||
typename DispatcherType::Handle handle;
|
||||
};
|
||||
|
||||
template <typename ...Args>
|
||||
void operator() (Args && ...args) const {
|
||||
if(--data->triggerCount <= 0) {
|
||||
data->dispatcher.removeListener(data->event, data->handle);
|
||||
}
|
||||
data->listener(std::forward<Args>(args)...);
|
||||
}
|
||||
|
||||
std::shared_ptr<Data> data;
|
||||
};
|
||||
|
||||
public:
|
||||
explicit CounterRemover(DispatcherType & dispatcher)
|
||||
: dispatcher(dispatcher)
|
||||
{
|
||||
}
|
||||
|
||||
template <typename Callback>
|
||||
typename DispatcherType::Handle appendListener(
|
||||
const typename DispatcherType::Event & event,
|
||||
const Callback & listener,
|
||||
const int triggerCount = 1
|
||||
)
|
||||
{
|
||||
auto data = std::make_shared<typename Wrapper<Callback>::Data>(typename Wrapper<Callback>::Data {
|
||||
triggerCount, dispatcher, event, listener, typename DispatcherType::Handle()
|
||||
});
|
||||
data->handle = dispatcher.appendListener(event, Wrapper<Callback>{data});
|
||||
return data->handle;
|
||||
}
|
||||
|
||||
template <typename Callback>
|
||||
typename DispatcherType::Handle prependListener(
|
||||
const typename DispatcherType::Event & event,
|
||||
const Callback & listener,
|
||||
const int triggerCount = 1
|
||||
)
|
||||
{
|
||||
auto data = std::make_shared<typename Wrapper<Callback>::Data>(typename Wrapper<Callback>::Data {
|
||||
triggerCount, dispatcher, event, listener, typename DispatcherType::Handle()
|
||||
});
|
||||
data->handle = dispatcher.prependListener(event, Wrapper<Callback>{data});
|
||||
return data->handle;
|
||||
}
|
||||
|
||||
template <typename Callback>
|
||||
typename DispatcherType::Handle insertListener(
|
||||
const typename DispatcherType::Event & event,
|
||||
const Callback & listener,
|
||||
const typename DispatcherType::Handle & before,
|
||||
const int triggerCount = 1
|
||||
)
|
||||
{
|
||||
auto data = std::make_shared<typename Wrapper<Callback>::Data>(typename Wrapper<Callback>::Data {
|
||||
triggerCount, dispatcher, event, listener, typename DispatcherType::Handle()
|
||||
});
|
||||
data->handle = dispatcher.insertListener(event, Wrapper<Callback>{data}, before);
|
||||
return data->handle;
|
||||
}
|
||||
|
||||
private:
|
||||
DispatcherType & dispatcher;
|
||||
};
|
||||
|
||||
template <typename CallbackListType>
|
||||
class CounterRemover <
|
||||
CallbackListType,
|
||||
typename std::enable_if<std::is_base_of<TagCallbackList, CallbackListType>::value>::type
|
||||
>
|
||||
{
|
||||
private:
|
||||
template <typename Callback>
|
||||
struct Wrapper
|
||||
{
|
||||
struct Data
|
||||
{
|
||||
int triggerCount;
|
||||
CallbackListType & callbackList;
|
||||
Callback listener;
|
||||
typename CallbackListType::Handle handle;
|
||||
};
|
||||
|
||||
template <typename ...Args>
|
||||
void operator() (Args && ...args) const {
|
||||
if(--data->triggerCount <= 0) {
|
||||
data->callbackList.remove(data->handle);
|
||||
}
|
||||
data->listener(std::forward<Args>(args)...);
|
||||
}
|
||||
|
||||
std::shared_ptr<Data> data;
|
||||
};
|
||||
|
||||
public:
|
||||
explicit CounterRemover(CallbackListType & callbackList)
|
||||
: callbackList(callbackList)
|
||||
{
|
||||
}
|
||||
|
||||
template <typename Callback>
|
||||
typename CallbackListType::Handle append(
|
||||
const Callback & listener,
|
||||
const int triggerCount = 1
|
||||
)
|
||||
{
|
||||
auto data = std::make_shared<typename Wrapper<Callback>::Data>(typename Wrapper<Callback>::Data {
|
||||
triggerCount, callbackList, listener, typename CallbackListType::Handle()
|
||||
});
|
||||
data->handle = callbackList.append(Wrapper<Callback>{data});
|
||||
return data->handle;
|
||||
}
|
||||
|
||||
template <typename Callback>
|
||||
typename CallbackListType::Handle prepend(
|
||||
const Callback & listener,
|
||||
const int triggerCount = 1
|
||||
)
|
||||
{
|
||||
auto data = std::make_shared<typename Wrapper<Callback>::Data>(typename Wrapper<Callback>::Data {
|
||||
triggerCount, callbackList, listener, typename CallbackListType::Handle()
|
||||
});
|
||||
data->handle = callbackList.prepend(Wrapper<Callback>{data});
|
||||
return data->handle;
|
||||
}
|
||||
|
||||
template <typename Callback>
|
||||
typename CallbackListType::Handle insert(
|
||||
const Callback & listener,
|
||||
const typename CallbackListType::Handle & before,
|
||||
const int triggerCount = 1
|
||||
)
|
||||
{
|
||||
auto data = std::make_shared<typename Wrapper<Callback>::Data>(typename Wrapper<Callback>::Data {
|
||||
triggerCount, callbackList, listener, typename CallbackListType::Handle()
|
||||
});
|
||||
data->handle = callbackList.insert(Wrapper<Callback>{data}, before);
|
||||
return data->handle;
|
||||
}
|
||||
|
||||
private:
|
||||
CallbackListType & callbackList;
|
||||
};
|
||||
|
||||
template <typename DispatcherType>
|
||||
CounterRemover<DispatcherType> counterRemover(DispatcherType & dispatcher)
|
||||
{
|
||||
return CounterRemover<DispatcherType>(dispatcher);
|
||||
}
|
||||
|
||||
|
||||
} //namespace eventpp
|
||||
|
||||
#endif
|
||||
|
||||
@@ -1,177 +0,0 @@
|
||||
// eventpp library
|
||||
// Copyright (C) 2018 Wang Qi (wqking)
|
||||
// Github: https://github.com/wqking/eventpp
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#ifndef EVENTMAKER_H_378278023815
|
||||
#define EVENTMAKER_H_378278023815
|
||||
|
||||
// auto generated macros begin
|
||||
|
||||
#define I_EVENTPP_ARG_COUNT(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15, ...) p15
|
||||
#define EVENTPP_ARG_COUNT(...) EVENTPP_EXPAND(I_EVENTPP_ARG_COUNT(__VA_ARGS__, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0))
|
||||
|
||||
#define I_EVENTPP_ITERATE_ARGS_0(EXEC, DELI)
|
||||
#define I_EVENTPP_ITERATE_ARGS_1(EXEC, DELI, p0) I_EVENTPP_ITERATE_ARGS_0(EXEC, DELI ) EXEC(p0)
|
||||
#define I_EVENTPP_ITERATE_ARGS_2(EXEC, DELI, p0, p1) I_EVENTPP_ITERATE_ARGS_1(EXEC, DELI, p0) DELI() EXEC(p1)
|
||||
#define I_EVENTPP_ITERATE_ARGS_3(EXEC, DELI, p0, p1, p2) I_EVENTPP_ITERATE_ARGS_2(EXEC, DELI, p0, p1) DELI() EXEC(p2)
|
||||
#define I_EVENTPP_ITERATE_ARGS_4(EXEC, DELI, p0, p1, p2, p3) I_EVENTPP_ITERATE_ARGS_3(EXEC, DELI, p0, p1, p2) DELI() EXEC(p3)
|
||||
#define I_EVENTPP_ITERATE_ARGS_5(EXEC, DELI, p0, p1, p2, p3, p4) I_EVENTPP_ITERATE_ARGS_4(EXEC, DELI, p0, p1, p2, p3) DELI() EXEC(p4)
|
||||
#define I_EVENTPP_ITERATE_ARGS_6(EXEC, DELI, p0, p1, p2, p3, p4, p5) I_EVENTPP_ITERATE_ARGS_5(EXEC, DELI, p0, p1, p2, p3, p4) DELI() EXEC(p5)
|
||||
#define I_EVENTPP_ITERATE_ARGS_7(EXEC, DELI, p0, p1, p2, p3, p4, p5, p6) I_EVENTPP_ITERATE_ARGS_6(EXEC, DELI, p0, p1, p2, p3, p4, p5) DELI() EXEC(p6)
|
||||
#define I_EVENTPP_ITERATE_ARGS_8(EXEC, DELI, p0, p1, p2, p3, p4, p5, p6, p7) I_EVENTPP_ITERATE_ARGS_7(EXEC, DELI, p0, p1, p2, p3, p4, p5, p6) DELI() EXEC(p7)
|
||||
#define I_EVENTPP_ITERATE_ARGS_9(EXEC, DELI, p0, p1, p2, p3, p4, p5, p6, p7, p8) I_EVENTPP_ITERATE_ARGS_8(EXEC, DELI, p0, p1, p2, p3, p4, p5, p6, p7) DELI() EXEC(p8)
|
||||
#define I_EVENTPP_ITERATE_ARGS_10(EXEC, DELI, p0, p1, p2, p3, p4, p5, p6, p7, p8, p9) I_EVENTPP_ITERATE_ARGS_9(EXEC, DELI, p0, p1, p2, p3, p4, p5, p6, p7, p8) DELI() EXEC(p9)
|
||||
#define I_EVENTPP_ITERATE_ARGS_11(EXEC, DELI, p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10) I_EVENTPP_ITERATE_ARGS_10(EXEC, DELI, p0, p1, p2, p3, p4, p5, p6, p7, p8, p9) DELI() EXEC(p10)
|
||||
#define I_EVENTPP_ITERATE_ARGS_12(EXEC, DELI, p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11) I_EVENTPP_ITERATE_ARGS_11(EXEC, DELI, p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10) DELI() EXEC(p11)
|
||||
#define I_EVENTPP_ITERATE_ARGS_13(EXEC, DELI, p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12) I_EVENTPP_ITERATE_ARGS_12(EXEC, DELI, p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11) DELI() EXEC(p12)
|
||||
#define I_EVENTPP_ITERATE_ARGS_14(EXEC, DELI, p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13) I_EVENTPP_ITERATE_ARGS_13(EXEC, DELI, p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12) DELI() EXEC(p13)
|
||||
#define I_EVENTPP_ITERATE_ARGS_15(EXEC, DELI, p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14) I_EVENTPP_ITERATE_ARGS_14(EXEC, DELI, p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13) DELI() EXEC(p14)
|
||||
#define I_EVENTPP_ITERATE_ARGS_N(EXEC, DELI, N, ...) EVENTPP_EXPAND(EVENTPP_CONCAT(I_EVENTPP_ITERATE_ARGS_, N) (EXEC, DELI, __VA_ARGS__))
|
||||
#define EVENTPP_ITERATE_ARGS(EXEC, DELI, ...) I_EVENTPP_ITERATE_ARGS_N(EXEC, DELI, EVENTPP_ARG_COUNT(__VA_ARGS__), __VA_ARGS__)
|
||||
|
||||
// auto generated macros end
|
||||
|
||||
#define I_EVENTPP_STRINGIFY(x) #x
|
||||
#define EVENTPP_STRINGIFY(x) I_EVENTPP_STRINGIFY(x)
|
||||
|
||||
#define I_EVENTPP_CONCAT(a, b) a ## b
|
||||
#define EVENTPP_CONCAT(a, b) I_EVENTPP_CONCAT(a, b)
|
||||
|
||||
// EVENTPP_EXPAND is used to expand __VA_ARGS__ correctly in VC++
|
||||
#define EVENTPP_EXPAND(...) __VA_ARGS__
|
||||
#define EVENTPP_BRACKETS_EXPAND(...) EVENTPP_EXPAND(EVENTPP_EXPAND __VA_ARGS__)
|
||||
|
||||
#define EVENTPP_EMPTY()
|
||||
#define EVENTPP_COMMA() ,
|
||||
#define EVENTPP_SEMICOLON() ;
|
||||
|
||||
#define I_EVENTPP_GET0_2(p0, ...) p0
|
||||
#define I_EVENTPP_GET0(...) EVENTPP_EXPAND(I_EVENTPP_GET0_2(__VA_ARGS__, ))
|
||||
#define EVENTPP_GET0(p0) EVENTPP_EXPAND(I_EVENTPP_GET0 p0)
|
||||
|
||||
#define I_EVENTPP_GET1_2(p0, p1, ...) p1
|
||||
#define I_EVENTPP_GET1(...) EVENTPP_EXPAND(I_EVENTPP_GET1_2(__VA_ARGS__, ))
|
||||
#define EVENTPP_GET1(p0) EVENTPP_EXPAND(I_EVENTPP_GET1 p0)
|
||||
|
||||
#define I_EVENTPP_GET2_2(p0, p1, p2, ...) p2
|
||||
#define I_EVENTPP_GET2(...) EVENTPP_EXPAND(I_EVENTPP_GET2_2(__VA_ARGS__, ))
|
||||
#define EVENTPP_GET2(p0) EVENTPP_EXPAND(I_EVENTPP_GET2 p0)
|
||||
|
||||
#define EVENTPP_MAKE_FIELD_NAME(p0) EVENTPP_CONCAT(v, EVENTPP_GET1(p0))
|
||||
#define EVENTPP_EXEC_MAKE_FIELD(p0) EVENTPP_GET0(p0) EVENTPP_MAKE_FIELD_NAME(p0)
|
||||
#define EVENTPP_EXEC_MAKE_GETTER(p0) const EVENTPP_GET0(p0) & EVENTPP_GET1(p0) () const { return EVENTPP_MAKE_FIELD_NAME(p0); }
|
||||
|
||||
#define I_EVENTPP_EXEC_MAKE_SETTER_0(p0)
|
||||
#define I_EVENTPP_EXEC_MAKE_SETTER_1(p0)
|
||||
#define I_EVENTPP_EXEC_MAKE_SETTER_2(p0)
|
||||
#define I_EVENTPP_EXEC_MAKE_SETTER_3(p0) void EVENTPP_GET2(p0) (const EVENTPP_GET0(p0) & value) { EVENTPP_MAKE_FIELD_NAME(p0) = value; }
|
||||
#define I_EVENTPP_EXEC_MAKE_SETTER_4(p0) I_EVENTPP_MAKE_SETTER_HELPER_3(p0)
|
||||
#define I_EVENTPP_EXEC_MAKE_SETTER_5(p0) I_EVENTPP_MAKE_SETTER_HELPER_3(p0)
|
||||
#define I_EVENTPP_EXEC_MAKE_SETTER_6(p0) I_EVENTPP_MAKE_SETTER_HELPER_3(p0)
|
||||
#define I_EVENTPP_EXEC_MAKE_SETTER_N(N, p0) EVENTPP_EXPAND(EVENTPP_CONCAT(I_EVENTPP_EXEC_MAKE_SETTER_, N) (p0))
|
||||
#define EVENTPP_EXEC_MAKE_SETTER(p0) EVENTPP_EXPAND(I_EVENTPP_EXEC_MAKE_SETTER_N(EVENTPP_ARG_COUNT EVENTPP_EXPAND(p0), p0))
|
||||
|
||||
#define EVENTPP_EXEC_MAKE_INITIALIZE(p0) EVENTPP_MAKE_FIELD_NAME(p0)(EVENTPP_MAKE_FIELD_NAME(p0))
|
||||
#define EVENTPP_EXEC_MAKE_DEFAULT_INITIALIZE(p0) EVENTPP_MAKE_FIELD_NAME(p0)()
|
||||
#define EVENTPP_EXEC_MAKE_CTOR_FIELD(p0) const EVENTPP_GET0(p0) & EVENTPP_MAKE_FIELD_NAME(p0)
|
||||
|
||||
#define I_EVENTPP_CHECK(x, n, ...) n
|
||||
#define EVENTPP_CHECK(...) EVENTPP_EXPAND(I_EVENTPP_CHECK(__VA_ARGS__, 0, ))
|
||||
|
||||
#define I_EVENTPP_IS_ENCLOSED_BY_BRACKETS(...) x, 1
|
||||
#define EVENTPP_IS_ENCLOSED_BY_BRACKETS(x) EVENTPP_CHECK(I_EVENTPP_IS_ENCLOSED_BY_BRACKETS x)
|
||||
|
||||
#define I_EVENTPP_IF_1(t, f) t
|
||||
#define I_EVENTPP_IF_0(t, f) f
|
||||
#define EVENTPP_IF(b, t, f) EVENTPP_CONCAT(I_EVENTPP_IF_, b)(t, f)
|
||||
|
||||
#define EVENTPP_ADD_BACKETS(x) EVENTPP_IF(EVENTPP_IS_ENCLOSED_BY_BRACKETS(x), x, (x))
|
||||
#define EVENTPP_REMOVE_BACKETS(x) EVENTPP_BRACKETS_EXPAND(EVENTPP_IF(EVENTPP_IS_ENCLOSED_BY_BRACKETS(x), (EVENTPP_EXPAND x), (x)))
|
||||
|
||||
#define I_EVENTPP_MAKE_EVENT(className, baseClassName, baseClassArgs, ...) \
|
||||
class className : public EVENTPP_REMOVE_BACKETS(baseClassName) { \
|
||||
public: \
|
||||
className() \
|
||||
: EVENTPP_REMOVE_BACKETS(baseClassName) EVENTPP_ADD_BACKETS(baseClassArgs), \
|
||||
EVENTPP_ITERATE_ARGS(EVENTPP_EXEC_MAKE_DEFAULT_INITIALIZE, EVENTPP_COMMA, __VA_ARGS__) {} \
|
||||
className(EVENTPP_ITERATE_ARGS(EVENTPP_EXEC_MAKE_CTOR_FIELD, EVENTPP_COMMA, __VA_ARGS__)) \
|
||||
: EVENTPP_REMOVE_BACKETS(baseClassName) EVENTPP_ADD_BACKETS(baseClassArgs), \
|
||||
EVENTPP_ITERATE_ARGS(EVENTPP_EXEC_MAKE_INITIALIZE, EVENTPP_COMMA, __VA_ARGS__) {} \
|
||||
EVENTPP_ITERATE_ARGS(EVENTPP_EXEC_MAKE_GETTER, EVENTPP_EMPTY, __VA_ARGS__) \
|
||||
EVENTPP_ITERATE_ARGS(EVENTPP_EXEC_MAKE_SETTER, EVENTPP_EMPTY, __VA_ARGS__) \
|
||||
private: \
|
||||
EVENTPP_ITERATE_ARGS(EVENTPP_EXEC_MAKE_FIELD, EVENTPP_SEMICOLON, __VA_ARGS__); \
|
||||
}
|
||||
|
||||
#define EVENTPP_MAKE_EVENT(className, baseClassName, baseClassArgs, ...) EVENTPP_EXPAND(I_EVENTPP_MAKE_EVENT(className, baseClassName, baseClassArgs, __VA_ARGS__))
|
||||
|
||||
#define EVENTPP_MAKE_EMPTY_EVENT(className, baseClassName, baseClassArgs) \
|
||||
class className : public EVENTPP_REMOVE_BACKETS(baseClassName) { \
|
||||
public: \
|
||||
className() \
|
||||
: EVENTPP_REMOVE_BACKETS(baseClassName) EVENTPP_ADD_BACKETS(baseClassArgs) {} \
|
||||
}
|
||||
|
||||
|
||||
#endif
|
||||
|
||||
|
||||
/*
|
||||
Perl script to generate some of the macros
|
||||
|
||||
use strict;
|
||||
use warnings;
|
||||
|
||||
my $paramCount = 15;
|
||||
|
||||
sub outputParams
|
||||
{
|
||||
my ($count) = @_;
|
||||
|
||||
for(my $i = 0; $i < $count; ++$i) {
|
||||
print ', ' if($i > 0);
|
||||
print 'p', $i;
|
||||
}
|
||||
}
|
||||
|
||||
sub doMain
|
||||
{
|
||||
print '#define I_EVENTPP_ARG_COUNT(';
|
||||
&outputParams($paramCount + 1);
|
||||
print ', ...) p', $paramCount, "\n";
|
||||
print '#define EVENTPP_ARG_COUNT(...) EVENTPP_EXPAND(I_EVENTPP_ARG_COUNT(__VA_ARGS__';
|
||||
for(my $i = $paramCount; $i >= 0; --$i) {
|
||||
print ', ', $i;
|
||||
}
|
||||
print "))\n";
|
||||
print "\n";
|
||||
|
||||
print "#define I_EVENTPP_ITERATE_ARGS_0(EXEC, DELI)\n";
|
||||
for(my $i = 1; $i <= $paramCount; ++$i) {
|
||||
print '#define I_EVENTPP_ITERATE_ARGS_', $i, '(EXEC, DELI, ';
|
||||
&outputParams($i);
|
||||
print ') I_EVENTPP_ITERATE_ARGS_', ($i - 1), '(EXEC, DELI';
|
||||
print ($i > 1 ? ', ' : ' ');
|
||||
&outputParams($i - 1);
|
||||
print ')', ($i > 1 ? ' DELI()' : ''), ' EXEC(p', ($i - 1), ')';
|
||||
print "\n";
|
||||
}
|
||||
print "#define I_EVENTPP_ITERATE_ARGS_N(EXEC, DELI, N, ...) EVENTPP_EXPAND(EVENTPP_CONCAT(I_EVENTPP_ITERATE_ARGS_, N) (EXEC, DELI, __VA_ARGS__))\n";
|
||||
print "#define EVENTPP_ITERATE_ARGS(EXEC, DELI, ...) I_EVENTPP_ITERATE_ARGS_N(EXEC, DELI, EVENTPP_ARG_COUNT(__VA_ARGS__), __VA_ARGS__)\n";
|
||||
print "\n";
|
||||
|
||||
}
|
||||
|
||||
&doMain;
|
||||
|
||||
|
||||
*/
|
||||
@@ -1,169 +0,0 @@
|
||||
// eventpp library
|
||||
// Copyright (C) 2018 Wang Qi (wqking)
|
||||
// Github: https://github.com/wqking/eventpp
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#ifndef EVENTUTIL_H_802615012766
|
||||
#define EVENTUTIL_H_802615012766
|
||||
|
||||
namespace eventpp {
|
||||
|
||||
template <typename DispatcherType>
|
||||
bool removeListener(
|
||||
DispatcherType & dispatcher,
|
||||
const typename DispatcherType::Event & event,
|
||||
const typename DispatcherType::Callback & listener
|
||||
)
|
||||
{
|
||||
bool found = false;
|
||||
dispatcher.forEachIf(
|
||||
event,
|
||||
[&found, &dispatcher, &event, &listener](
|
||||
const typename DispatcherType::Handle & handle,
|
||||
const typename DispatcherType::Callback & item
|
||||
) -> bool {
|
||||
if(item == listener) {
|
||||
found = true;
|
||||
dispatcher.removeListener(event, handle);
|
||||
return false;
|
||||
}
|
||||
else {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
return found;
|
||||
}
|
||||
|
||||
template <typename CallbackListType>
|
||||
bool removeListener(
|
||||
CallbackListType & callbackList,
|
||||
const typename CallbackListType::Callback & callback
|
||||
)
|
||||
{
|
||||
bool found = false;
|
||||
callbackList.forEachIf(
|
||||
[&found, &callbackList, &callback](
|
||||
const typename CallbackListType::Handle & handle,
|
||||
const typename CallbackListType::Callback & item
|
||||
) -> bool {
|
||||
if(item == callback) {
|
||||
found = true;
|
||||
callbackList.remove(handle);
|
||||
return false;
|
||||
}
|
||||
else {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
return found;
|
||||
}
|
||||
|
||||
template <typename DispatcherType>
|
||||
bool hasListener(
|
||||
DispatcherType & dispatcher,
|
||||
const typename DispatcherType::Event & event,
|
||||
const typename DispatcherType::Callback & listener
|
||||
)
|
||||
{
|
||||
bool found = false;
|
||||
dispatcher.forEachIf(
|
||||
event,
|
||||
[&found, &listener](
|
||||
const typename DispatcherType::Handle & /*handle*/,
|
||||
const typename DispatcherType::Callback & item
|
||||
) -> bool {
|
||||
if(item == listener) {
|
||||
found = true;
|
||||
return false;
|
||||
}
|
||||
else {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
return found;
|
||||
}
|
||||
|
||||
template <typename DispatcherType>
|
||||
bool hasAnyListener(
|
||||
DispatcherType & dispatcher,
|
||||
const typename DispatcherType::Event & event
|
||||
)
|
||||
{
|
||||
bool found = false;
|
||||
dispatcher.forEachIf(
|
||||
event,
|
||||
[&found](
|
||||
const typename DispatcherType::Handle & /*handle*/,
|
||||
const typename DispatcherType::Callback & /*item*/
|
||||
) -> bool {
|
||||
found = true;
|
||||
return false;
|
||||
}
|
||||
);
|
||||
|
||||
return found;
|
||||
}
|
||||
|
||||
template <typename CallbackListType>
|
||||
bool hasListener(
|
||||
CallbackListType & callbackList,
|
||||
const typename CallbackListType::Callback & callback
|
||||
)
|
||||
{
|
||||
bool found = false;
|
||||
callbackList.forEachIf(
|
||||
[&found, &callback](
|
||||
const typename CallbackListType::Handle & /*handle*/,
|
||||
const typename CallbackListType::Callback & item
|
||||
) -> bool {
|
||||
if(item == callback) {
|
||||
found = true;
|
||||
return false;
|
||||
}
|
||||
else {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
return found;
|
||||
}
|
||||
|
||||
template <typename CallbackListType>
|
||||
bool hasAnyListener(
|
||||
CallbackListType & callbackList
|
||||
)
|
||||
{
|
||||
bool found = false;
|
||||
callbackList.forEachIf(
|
||||
[&found](
|
||||
const typename CallbackListType::Handle & /*handle*/,
|
||||
const typename CallbackListType::Callback & /*item*/
|
||||
) -> bool {
|
||||
found = true;
|
||||
return false;
|
||||
}
|
||||
);
|
||||
|
||||
return found;
|
||||
}
|
||||
|
||||
|
||||
} //namespace eventpp
|
||||
|
||||
#endif
|
||||
|
||||
@@ -1,81 +0,0 @@
|
||||
// eventpp library
|
||||
// Copyright (C) 2018 Wang Qi (wqking)
|
||||
// Github: https://github.com/wqking/eventpp
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#ifndef ORDEREDQUEUELIST_H_862875671799
|
||||
#define ORDEREDQUEUELIST_H_862875671799
|
||||
|
||||
#include "../eventpolicies.h"
|
||||
|
||||
#include <list>
|
||||
|
||||
namespace eventpp {
|
||||
|
||||
struct OrderedQueueListCompare
|
||||
{
|
||||
template <typename T>
|
||||
bool operator() (const T & a, const T & b) const {
|
||||
return a.event < b.event;
|
||||
}
|
||||
};
|
||||
|
||||
template <typename T, typename Compare = OrderedQueueListCompare>
|
||||
class OrderedQueueList : private std::list<T>
|
||||
{
|
||||
private:
|
||||
using super = std::list<T>;
|
||||
|
||||
public:
|
||||
using iterator = typename super::iterator;
|
||||
using const_iterator = typename super::const_iterator;
|
||||
using super::empty;
|
||||
using super::begin;
|
||||
using super::end;
|
||||
using super::front;
|
||||
using super::swap;
|
||||
using super::emplace_back;
|
||||
|
||||
void splice(const_iterator pos, OrderedQueueList & other) {
|
||||
super::splice(pos, other);
|
||||
doSort();
|
||||
}
|
||||
|
||||
void splice(const_iterator pos, OrderedQueueList & other, const_iterator it) {
|
||||
super::splice(pos, other, it);
|
||||
doSort();
|
||||
}
|
||||
|
||||
private:
|
||||
void doSort() {
|
||||
auto compare = Compare();
|
||||
this->sort([compare](const T & a, const T & b) {
|
||||
// a and b may be empty if they are recycled to free list.
|
||||
if(a.empty()) {
|
||||
if(b.empty()) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
else if(b.empty()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return compare(a.get(), b.get());
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
} //namespace eventpp
|
||||
|
||||
#endif
|
||||
|
||||
@@ -1,330 +0,0 @@
|
||||
// eventpp library
|
||||
// Copyright (C) 2018 Wang Qi (wqking)
|
||||
// Github: https://github.com/wqking/eventpp
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#ifndef SCOPEDREMOVER_H_695291515513
|
||||
#define SCOPEDREMOVER_H_695291515513
|
||||
|
||||
#include "../eventpolicies.h"
|
||||
|
||||
#include <vector>
|
||||
#include <algorithm>
|
||||
|
||||
namespace eventpp {
|
||||
|
||||
namespace internal_ {
|
||||
|
||||
template <typename Item, typename Handle, typename Mutex>
|
||||
bool removeHandleFromScopedRemoverItemList(std::vector<Item> & itemList, Handle & handle, Mutex & mutex)
|
||||
{
|
||||
if(! handle) {
|
||||
return false;
|
||||
}
|
||||
auto handlePointer = handle.lock();
|
||||
std::unique_lock<Mutex> lock(mutex);
|
||||
auto it = std::find_if(itemList.begin(), itemList.end(), [&handlePointer](Item & item) {
|
||||
return item.handle && item.handle.lock() == handlePointer;
|
||||
});
|
||||
if(it != itemList.end()) {
|
||||
itemList.erase(it);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
} //namespace internal_
|
||||
|
||||
template <typename DispatcherType, typename Enabled = void>
|
||||
class ScopedRemover;
|
||||
|
||||
template <typename DispatcherType>
|
||||
class ScopedRemover <
|
||||
DispatcherType,
|
||||
typename std::enable_if<std::is_base_of<TagEventDispatcher, DispatcherType>::value>::type
|
||||
>
|
||||
{
|
||||
private:
|
||||
struct Item
|
||||
{
|
||||
typename DispatcherType::Event event;
|
||||
typename DispatcherType::Handle handle;
|
||||
};
|
||||
|
||||
public:
|
||||
ScopedRemover()
|
||||
: dispatcher(nullptr)
|
||||
{
|
||||
}
|
||||
|
||||
explicit ScopedRemover(DispatcherType & dispatcher)
|
||||
: dispatcher(&dispatcher)
|
||||
{
|
||||
}
|
||||
|
||||
ScopedRemover(ScopedRemover && other) noexcept
|
||||
: dispatcher(std::move(other.dispatcher)), itemList(std::move(other.itemList))
|
||||
{
|
||||
other.reset();
|
||||
}
|
||||
|
||||
ScopedRemover & operator = (ScopedRemover && other) noexcept
|
||||
{
|
||||
dispatcher = std::move(other.dispatcher);
|
||||
itemList = std::move(other.itemList);
|
||||
other.reset();
|
||||
return *this;
|
||||
}
|
||||
|
||||
~ScopedRemover()
|
||||
{
|
||||
reset();
|
||||
}
|
||||
|
||||
void swap(ScopedRemover & other) noexcept {
|
||||
using std::swap;
|
||||
|
||||
swap(dispatcher, other.dispatcher);
|
||||
swap(itemList, other.itemList);
|
||||
}
|
||||
|
||||
void reset()
|
||||
{
|
||||
if(dispatcher != nullptr) {
|
||||
for(const auto & item : itemList) {
|
||||
dispatcher->removeListener(item.event, item.handle);
|
||||
}
|
||||
}
|
||||
|
||||
std::unique_lock<typename DispatcherType::Mutex> lock(itemListMutex);
|
||||
itemList.clear();
|
||||
}
|
||||
|
||||
void setDispatcher(DispatcherType & dispatcher_)
|
||||
{
|
||||
if(this->dispatcher != &dispatcher_) {
|
||||
reset();
|
||||
this->dispatcher = &dispatcher_;
|
||||
}
|
||||
}
|
||||
|
||||
template <typename Callback>
|
||||
typename DispatcherType::Handle appendListener(
|
||||
const typename DispatcherType::Event & event,
|
||||
const Callback & listener
|
||||
)
|
||||
{
|
||||
Item item {
|
||||
event,
|
||||
dispatcher->appendListener(event, listener)
|
||||
};
|
||||
|
||||
{
|
||||
std::unique_lock<typename DispatcherType::Mutex> lock(itemListMutex);
|
||||
itemList.push_back(item);
|
||||
}
|
||||
|
||||
return item.handle;
|
||||
}
|
||||
|
||||
template <typename Callback>
|
||||
typename DispatcherType::Handle prependListener(
|
||||
const typename DispatcherType::Event & event,
|
||||
const Callback & listener
|
||||
)
|
||||
{
|
||||
Item item {
|
||||
event,
|
||||
dispatcher->prependListener(event, listener)
|
||||
};
|
||||
|
||||
{
|
||||
std::unique_lock<typename DispatcherType::Mutex> lock(itemListMutex);
|
||||
itemList.push_back(item);
|
||||
}
|
||||
|
||||
return item.handle;
|
||||
}
|
||||
|
||||
template <typename Callback>
|
||||
typename DispatcherType::Handle insertListener(
|
||||
const typename DispatcherType::Event & event,
|
||||
const Callback & listener,
|
||||
const typename DispatcherType::Handle & before
|
||||
)
|
||||
{
|
||||
Item item {
|
||||
event,
|
||||
dispatcher->insertListener(event, listener, before)
|
||||
};
|
||||
|
||||
{
|
||||
std::unique_lock<typename DispatcherType::Mutex> lock(itemListMutex);
|
||||
itemList.push_back(item);
|
||||
}
|
||||
|
||||
return item.handle;
|
||||
}
|
||||
|
||||
bool removeListener(const typename DispatcherType::Event & event, const typename DispatcherType::Handle handle)
|
||||
{
|
||||
if(internal_::removeHandleFromScopedRemoverItemList(itemList, handle, itemListMutex)) {
|
||||
return dispatcher->removeListener(event, handle);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private:
|
||||
DispatcherType * dispatcher;
|
||||
std::vector<Item> itemList;
|
||||
typename DispatcherType::Mutex itemListMutex;
|
||||
};
|
||||
|
||||
template <typename CallbackListType>
|
||||
class ScopedRemover <
|
||||
CallbackListType,
|
||||
typename std::enable_if<std::is_base_of<TagCallbackList, CallbackListType>::value>::type
|
||||
>
|
||||
{
|
||||
private:
|
||||
struct Item
|
||||
{
|
||||
typename CallbackListType::Handle handle;
|
||||
};
|
||||
|
||||
public:
|
||||
ScopedRemover()
|
||||
: callbackList(nullptr)
|
||||
{
|
||||
}
|
||||
|
||||
explicit ScopedRemover(CallbackListType & callbackList)
|
||||
: callbackList(&callbackList)
|
||||
{
|
||||
}
|
||||
|
||||
ScopedRemover(ScopedRemover && other) noexcept
|
||||
: callbackList(std::move(other.callbackList)), itemList(std::move(other.itemList))
|
||||
{
|
||||
other.reset();
|
||||
}
|
||||
|
||||
ScopedRemover & operator = (ScopedRemover && other) noexcept
|
||||
{
|
||||
callbackList = std::move(other.callbackList);
|
||||
itemList = std::move(other.itemList);
|
||||
other.reset();
|
||||
return *this;
|
||||
}
|
||||
|
||||
~ScopedRemover()
|
||||
{
|
||||
reset();
|
||||
}
|
||||
|
||||
void swap(ScopedRemover & other) noexcept {
|
||||
using std::swap;
|
||||
|
||||
swap(callbackList, other.callbackList);
|
||||
swap(itemList, other.itemList);
|
||||
}
|
||||
|
||||
void reset()
|
||||
{
|
||||
if(callbackList != nullptr) {
|
||||
for(const auto & item : itemList) {
|
||||
callbackList->remove(item.handle);
|
||||
}
|
||||
}
|
||||
|
||||
std::unique_lock<typename CallbackListType::Mutex> lock(itemListMutex);
|
||||
itemList.clear();
|
||||
}
|
||||
|
||||
void setCallbackList(CallbackListType & callbackList_)
|
||||
{
|
||||
if(this->callbackList != &callbackList_) {
|
||||
reset();
|
||||
this->callbackList = &callbackList_;
|
||||
}
|
||||
}
|
||||
|
||||
template <typename Callback>
|
||||
typename CallbackListType::Handle append(
|
||||
const Callback & callback
|
||||
)
|
||||
{
|
||||
Item item {
|
||||
callbackList->append(callback)
|
||||
};
|
||||
|
||||
{
|
||||
std::unique_lock<typename CallbackListType::Mutex> lock(itemListMutex);
|
||||
itemList.push_back(item);
|
||||
}
|
||||
|
||||
return item.handle;
|
||||
}
|
||||
|
||||
template <typename Callback>
|
||||
typename CallbackListType::Handle prepend(
|
||||
const Callback & callback
|
||||
)
|
||||
{
|
||||
Item item {
|
||||
callbackList->prepend(callback)
|
||||
};
|
||||
|
||||
{
|
||||
std::unique_lock<typename CallbackListType::Mutex> lock(itemListMutex);
|
||||
itemList.push_back(item);
|
||||
}
|
||||
|
||||
return item.handle;
|
||||
}
|
||||
|
||||
template <typename Callback>
|
||||
typename CallbackListType::Handle insert(
|
||||
const Callback & callback,
|
||||
const typename CallbackListType::Handle & before
|
||||
)
|
||||
{
|
||||
Item item {
|
||||
callbackList->insert(callback, before)
|
||||
};
|
||||
|
||||
{
|
||||
std::unique_lock<typename CallbackListType::Mutex> lock(itemListMutex);
|
||||
itemList.push_back(item);
|
||||
}
|
||||
|
||||
return item.handle;
|
||||
}
|
||||
|
||||
bool remove(const typename CallbackListType::Handle handle)
|
||||
{
|
||||
if(internal_::removeHandleFromScopedRemoverItemList(itemList, handle, itemListMutex)) {
|
||||
return callbackList->remove(handle);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private:
|
||||
CallbackListType * callbackList;
|
||||
std::vector<Item> itemList;
|
||||
typename CallbackListType::Mutex itemListMutex;
|
||||
};
|
||||
|
||||
|
||||
} //namespace eventpp
|
||||
|
||||
#endif
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
/*
|
||||
* Copyright (c) 1999, 2001, Oracle and/or its affiliates. All rights reserved.
|
||||
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
|
||||
*
|
||||
* This code is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License version 2 only, as
|
||||
* published by the Free Software Foundation. Oracle designates this
|
||||
* particular file as subject to the "Classpath" exception as provided
|
||||
* by Oracle in the LICENSE file that accompanied this code.
|
||||
*
|
||||
* This code is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
|
||||
* version 2 for more details (a copy is included in the LICENSE file that
|
||||
* accompanied this code).
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License version
|
||||
* 2 along with this work; if not, write to the Free Software Foundation,
|
||||
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
*
|
||||
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
|
||||
* or visit www.oracle.com if you need additional information or have any
|
||||
* questions.
|
||||
*/
|
||||
|
||||
#ifndef _JAVASOFT_JAWT_MD_H_
|
||||
#define _JAVASOFT_JAWT_MD_H_
|
||||
|
||||
#include <X11/Xlib.h>
|
||||
#include <X11/Xutil.h>
|
||||
#include "jawt.h"
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/*
|
||||
* X11-specific declarations for AWT native interface.
|
||||
* See notes in jawt.h for an example of use.
|
||||
*/
|
||||
typedef struct jawt_X11DrawingSurfaceInfo {
|
||||
Drawable drawable;
|
||||
Display* display;
|
||||
VisualID visualID;
|
||||
Colormap colormapID;
|
||||
int depth;
|
||||
/*
|
||||
* Since 1.4
|
||||
* Returns a pixel value from a set of RGB values.
|
||||
* This is useful for paletted color (256 color) modes.
|
||||
*/
|
||||
int (JNICALL *GetAWTColor)(JAWT_DrawingSurface* ds,
|
||||
int r, int g, int b);
|
||||
} JAWT_X11DrawingSurfaceInfo;
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* !_JAVASOFT_JAWT_MD_H_ */
|
||||
@@ -0,0 +1,66 @@
|
||||
/*
|
||||
* Copyright (c) 1996, 2020, Oracle and/or its affiliates. All rights reserved.
|
||||
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
|
||||
*
|
||||
* This code is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License version 2 only, as
|
||||
* published by the Free Software Foundation. Oracle designates this
|
||||
* particular file as subject to the "Classpath" exception as provided
|
||||
* by Oracle in the LICENSE file that accompanied this code.
|
||||
*
|
||||
* This code is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
|
||||
* version 2 for more details (a copy is included in the LICENSE file that
|
||||
* accompanied this code).
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License version
|
||||
* 2 along with this work; if not, write to the Free Software Foundation,
|
||||
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
*
|
||||
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
|
||||
* or visit www.oracle.com if you need additional information or have any
|
||||
* questions.
|
||||
*/
|
||||
|
||||
#ifndef _JAVASOFT_JNI_MD_H_
|
||||
#define _JAVASOFT_JNI_MD_H_
|
||||
|
||||
#ifndef __has_attribute
|
||||
#define __has_attribute(x) 0
|
||||
#endif
|
||||
|
||||
#ifndef JNIEXPORT
|
||||
#if (defined(__GNUC__) && ((__GNUC__ > 4) || (__GNUC__ == 4) && (__GNUC_MINOR__ > 2))) || __has_attribute(visibility)
|
||||
#ifdef ARM
|
||||
#define JNIEXPORT __attribute__((externally_visible,visibility("default")))
|
||||
#else
|
||||
#define JNIEXPORT __attribute__((visibility("default")))
|
||||
#endif
|
||||
#else
|
||||
#define JNIEXPORT
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#if (defined(__GNUC__) && ((__GNUC__ > 4) || (__GNUC__ == 4) && (__GNUC_MINOR__ > 2))) || __has_attribute(visibility)
|
||||
#ifdef ARM
|
||||
#define JNIIMPORT __attribute__((externally_visible,visibility("default")))
|
||||
#else
|
||||
#define JNIIMPORT __attribute__((visibility("default")))
|
||||
#endif
|
||||
#else
|
||||
#define JNIIMPORT
|
||||
#endif
|
||||
|
||||
#define JNICALL
|
||||
|
||||
typedef int jint;
|
||||
#ifdef _LP64
|
||||
typedef long jlong;
|
||||
#else
|
||||
typedef long long jlong;
|
||||
#endif
|
||||
|
||||
typedef signed char jbyte;
|
||||
|
||||
#endif /* !_JAVASOFT_JNI_MD_H_ */
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,382 @@
|
||||
//# This file is a part of toml++ and is subject to the the terms of the MIT license.
|
||||
//# Copyright (c) Mark Gillard <mark.gillard@outlook.com.au>
|
||||
//# See https://github.com/marzer/tomlplusplus/blob/master/LICENSE for the full license text.
|
||||
// SPDX-License-Identifier: MIT
|
||||
#pragma once
|
||||
|
||||
//# {{
|
||||
#include "preprocessor.hpp"
|
||||
#if !TOML_IMPLEMENTATION
|
||||
#error This is an implementation-only header.
|
||||
#endif
|
||||
//# }}
|
||||
|
||||
#include "array.hpp"
|
||||
#include "header_start.hpp"
|
||||
|
||||
TOML_NAMESPACE_START
|
||||
{
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
array::array() noexcept
|
||||
{
|
||||
#if TOML_LIFETIME_HOOKS
|
||||
TOML_ARRAY_CREATED;
|
||||
#endif
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
array::~array() noexcept
|
||||
{
|
||||
#if TOML_LIFETIME_HOOKS
|
||||
TOML_ARRAY_DESTROYED;
|
||||
#endif
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
array::array(const impl::array_init_elem* b, const impl::array_init_elem* e)
|
||||
{
|
||||
#if TOML_LIFETIME_HOOKS
|
||||
TOML_ARRAY_CREATED;
|
||||
#endif
|
||||
|
||||
TOML_ASSERT_ASSUME(b);
|
||||
TOML_ASSERT_ASSUME(e);
|
||||
TOML_ASSERT_ASSUME(b <= e);
|
||||
|
||||
if TOML_UNLIKELY(b == e)
|
||||
return;
|
||||
|
||||
size_t cap{};
|
||||
for (auto it = b; it != e; it++)
|
||||
{
|
||||
if (it->value)
|
||||
cap++;
|
||||
}
|
||||
if TOML_UNLIKELY(!cap)
|
||||
return;
|
||||
|
||||
elems_.reserve(cap);
|
||||
for (; b != e; b++)
|
||||
{
|
||||
if (b->value)
|
||||
elems_.push_back(std::move(b->value));
|
||||
}
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
array::array(const array& other) //
|
||||
: node(other)
|
||||
{
|
||||
elems_.reserve(other.elems_.size());
|
||||
for (const auto& elem : other)
|
||||
elems_.emplace_back(impl::make_node(elem));
|
||||
|
||||
#if TOML_LIFETIME_HOOKS
|
||||
TOML_ARRAY_CREATED;
|
||||
#endif
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
array::array(array && other) noexcept //
|
||||
: node(std::move(other)),
|
||||
elems_(std::move(other.elems_))
|
||||
{
|
||||
#if TOML_LIFETIME_HOOKS
|
||||
TOML_ARRAY_CREATED;
|
||||
#endif
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
array& array::operator=(const array& rhs)
|
||||
{
|
||||
if (&rhs != this)
|
||||
{
|
||||
node::operator=(rhs);
|
||||
elems_.clear();
|
||||
elems_.reserve(rhs.elems_.size());
|
||||
for (const auto& elem : rhs)
|
||||
elems_.emplace_back(impl::make_node(elem));
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
array& array::operator=(array&& rhs) noexcept
|
||||
{
|
||||
if (&rhs != this)
|
||||
{
|
||||
node::operator=(std::move(rhs));
|
||||
elems_ = std::move(rhs.elems_);
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
void array::preinsertion_resize(size_t idx, size_t count)
|
||||
{
|
||||
TOML_ASSERT(idx <= elems_.size());
|
||||
TOML_ASSERT_ASSUME(count >= 1u);
|
||||
const auto old_size = elems_.size();
|
||||
const auto new_size = old_size + count;
|
||||
const auto inserting_at_end = idx == old_size;
|
||||
elems_.resize(new_size);
|
||||
if (!inserting_at_end)
|
||||
{
|
||||
for (size_t left = old_size, right = new_size - 1u; left-- > idx; right--)
|
||||
elems_[right] = std::move(elems_[left]);
|
||||
}
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
void array::insert_at_back(impl::node_ptr && elem)
|
||||
{
|
||||
TOML_ASSERT(elem);
|
||||
elems_.push_back(std::move(elem));
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
array::vector_iterator array::insert_at(const_vector_iterator pos, impl::node_ptr && elem)
|
||||
{
|
||||
return elems_.insert(pos, std::move(elem));
|
||||
}
|
||||
|
||||
TOML_PURE_GETTER
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
bool array::is_homogeneous(node_type ntype) const noexcept
|
||||
{
|
||||
if (elems_.empty())
|
||||
return false;
|
||||
|
||||
if (ntype == node_type::none)
|
||||
ntype = elems_[0]->type();
|
||||
|
||||
for (const auto& val : elems_)
|
||||
if (val->type() != ntype)
|
||||
return false;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
TOML_PURE_GETTER
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
bool array::is_homogeneous(node_type ntype, node * &first_nonmatch) noexcept
|
||||
{
|
||||
if (elems_.empty())
|
||||
{
|
||||
first_nonmatch = {};
|
||||
return false;
|
||||
}
|
||||
if (ntype == node_type::none)
|
||||
ntype = elems_[0]->type();
|
||||
for (const auto& val : elems_)
|
||||
{
|
||||
if (val->type() != ntype)
|
||||
{
|
||||
first_nonmatch = val.get();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
TOML_PURE_GETTER
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
bool array::is_homogeneous(node_type ntype, const node*& first_nonmatch) const noexcept
|
||||
{
|
||||
node* fnm = nullptr;
|
||||
const auto result = const_cast<array&>(*this).is_homogeneous(ntype, fnm);
|
||||
first_nonmatch = fnm;
|
||||
return result;
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
node& array::at(size_t index)
|
||||
{
|
||||
#if TOML_COMPILER_HAS_EXCEPTIONS
|
||||
|
||||
return *elems_.at(index);
|
||||
|
||||
#else
|
||||
|
||||
auto n = get(index);
|
||||
TOML_ASSERT_ASSUME(n && "element index not found in array!");
|
||||
return *n;
|
||||
|
||||
#endif
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
void array::reserve(size_t new_capacity)
|
||||
{
|
||||
elems_.reserve(new_capacity);
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
void array::shrink_to_fit()
|
||||
{
|
||||
elems_.shrink_to_fit();
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
void array::truncate(size_t new_size)
|
||||
{
|
||||
if (new_size < elems_.size())
|
||||
elems_.resize(new_size);
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
array::iterator array::erase(const_iterator pos) noexcept
|
||||
{
|
||||
return iterator{ elems_.erase(const_vector_iterator{ pos }) };
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
array::iterator array::erase(const_iterator first, const_iterator last) noexcept
|
||||
{
|
||||
return iterator{ elems_.erase(const_vector_iterator{ first }, const_vector_iterator{ last }) };
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
size_t array::total_leaf_count() const noexcept
|
||||
{
|
||||
size_t leaves{};
|
||||
for (size_t i = 0, e = elems_.size(); i < e; i++)
|
||||
{
|
||||
auto arr = elems_[i]->as_array();
|
||||
leaves += arr ? arr->total_leaf_count() : size_t{ 1 };
|
||||
}
|
||||
return leaves;
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
void array::flatten_child(array && child, size_t & dest_index) noexcept
|
||||
{
|
||||
for (size_t i = 0, e = child.size(); i < e; i++)
|
||||
{
|
||||
auto type = child.elems_[i]->type();
|
||||
if (type == node_type::array)
|
||||
{
|
||||
array& arr = *reinterpret_cast<array*>(child.elems_[i].get());
|
||||
if (!arr.empty())
|
||||
flatten_child(std::move(arr), dest_index);
|
||||
}
|
||||
else
|
||||
elems_[dest_index++] = std::move(child.elems_[i]);
|
||||
}
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
array& array::flatten()&
|
||||
{
|
||||
if (elems_.empty())
|
||||
return *this;
|
||||
|
||||
bool requires_flattening = false;
|
||||
size_t size_after_flattening = elems_.size();
|
||||
for (size_t i = elems_.size(); i-- > 0u;)
|
||||
{
|
||||
auto arr = elems_[i]->as_array();
|
||||
if (!arr)
|
||||
continue;
|
||||
size_after_flattening--; // discount the array itself
|
||||
const auto leaf_count = arr->total_leaf_count();
|
||||
if (leaf_count > 0u)
|
||||
{
|
||||
requires_flattening = true;
|
||||
size_after_flattening += leaf_count;
|
||||
}
|
||||
else
|
||||
elems_.erase(elems_.cbegin() + static_cast<ptrdiff_t>(i));
|
||||
}
|
||||
|
||||
if (!requires_flattening)
|
||||
return *this;
|
||||
|
||||
elems_.reserve(size_after_flattening);
|
||||
|
||||
size_t i = 0;
|
||||
while (i < elems_.size())
|
||||
{
|
||||
auto arr = elems_[i]->as_array();
|
||||
if (!arr)
|
||||
{
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
|
||||
impl::node_ptr arr_storage = std::move(elems_[i]);
|
||||
const auto leaf_count = arr->total_leaf_count();
|
||||
if (leaf_count > 1u)
|
||||
preinsertion_resize(i + 1u, leaf_count - 1u);
|
||||
flatten_child(std::move(*arr), i); // increments i
|
||||
}
|
||||
|
||||
return *this;
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
array& array::prune(bool recursive)& noexcept
|
||||
{
|
||||
if (elems_.empty())
|
||||
return *this;
|
||||
|
||||
for (size_t i = elems_.size(); i-- > 0u;)
|
||||
{
|
||||
if (auto arr = elems_[i]->as_array())
|
||||
{
|
||||
if (recursive)
|
||||
arr->prune(true);
|
||||
if (arr->empty())
|
||||
elems_.erase(elems_.cbegin() + static_cast<ptrdiff_t>(i));
|
||||
}
|
||||
else if (auto tbl = elems_[i]->as_table())
|
||||
{
|
||||
if (recursive)
|
||||
tbl->prune(true);
|
||||
if (tbl->empty())
|
||||
elems_.erase(elems_.cbegin() + static_cast<ptrdiff_t>(i));
|
||||
}
|
||||
}
|
||||
|
||||
return *this;
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
void array::pop_back() noexcept
|
||||
{
|
||||
elems_.pop_back();
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
void array::clear() noexcept
|
||||
{
|
||||
elems_.clear();
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
bool TOML_CALLCONV array::equal(const array& lhs, const array& rhs) noexcept
|
||||
{
|
||||
if (&lhs == &rhs)
|
||||
return true;
|
||||
if (lhs.elems_.size() != rhs.elems_.size())
|
||||
return false;
|
||||
for (size_t i = 0, e = lhs.elems_.size(); i < e; i++)
|
||||
{
|
||||
const auto lhs_type = lhs.elems_[i]->type();
|
||||
const node& rhs_ = *rhs.elems_[i];
|
||||
const auto rhs_type = rhs_.type();
|
||||
if (lhs_type != rhs_type)
|
||||
return false;
|
||||
|
||||
const bool equal = lhs.elems_[i]->visit(
|
||||
[&](const auto& lhs_) noexcept
|
||||
{ return lhs_ == *reinterpret_cast<std::remove_reference_t<decltype(lhs_)>*>(&rhs_); });
|
||||
if (!equal)
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
TOML_NAMESPACE_END;
|
||||
|
||||
#include "header_end.hpp"
|
||||
@@ -0,0 +1,97 @@
|
||||
//# This file is a part of toml++ and is subject to the the terms of the MIT license.
|
||||
//# Copyright (c) Mark Gillard <mark.gillard@outlook.com.au>
|
||||
//# See https://github.com/marzer/tomlplusplus/blob/master/LICENSE for the full license text.
|
||||
// SPDX-License-Identifier: MIT
|
||||
#pragma once
|
||||
|
||||
#include "forward_declarations.hpp"
|
||||
|
||||
/// \cond
|
||||
TOML_IMPL_NAMESPACE_START
|
||||
{
|
||||
template <typename T>
|
||||
using parse_path_callback = bool(TOML_CALLCONV*)(void*, T);
|
||||
|
||||
TOML_NODISCARD
|
||||
bool TOML_CALLCONV parse_path(std::string_view,
|
||||
void*,
|
||||
parse_path_callback<std::string_view>,
|
||||
parse_path_callback<size_t>);
|
||||
}
|
||||
TOML_IMPL_NAMESPACE_END;
|
||||
/// \endcond
|
||||
|
||||
TOML_NAMESPACE_START
|
||||
{
|
||||
/// \brief Returns a view of the node matching a fully-qualified "TOML path".
|
||||
///
|
||||
/// \detail \cpp
|
||||
/// auto config = toml::parse(R"(
|
||||
///
|
||||
/// [foo]
|
||||
/// bar = [ 0, 1, 2, [ 3 ], { kek = 4 } ]
|
||||
///
|
||||
/// )"sv);
|
||||
///
|
||||
/// std::cout << toml::at_path(config, "foo.bar[2]") << "\n";
|
||||
/// std::cout << toml::at_path(config, "foo.bar[3][0]") << "\n";
|
||||
/// std::cout << toml::at_path(config, "foo.bar[4].kek") << "\n";
|
||||
/// \ecpp
|
||||
///
|
||||
/// \out
|
||||
/// 2
|
||||
/// 3
|
||||
/// 4
|
||||
/// \eout
|
||||
///
|
||||
///
|
||||
/// \note Keys in paths are interpreted literally, so whitespace (or lack thereof) matters:
|
||||
/// \cpp
|
||||
/// toml::at_path(config, "foo.bar") // same as config["foo"]["bar"]
|
||||
/// toml::at_path(config, "foo. bar") // same as config["foo"][" bar"]
|
||||
/// toml::at_path(config, "foo..bar") // same as config["foo"][""]["bar"]
|
||||
/// toml::at_path(config, ".foo.bar") // same as config[""]["foo"]["bar"]
|
||||
/// \ecpp
|
||||
/// <br>
|
||||
/// Additionally, TOML allows '.' (period) characters to appear in keys if they are quoted strings.
|
||||
/// This function makes no allowance for this, instead treating all period characters as sub-table delimiters.
|
||||
/// If you have periods in your table keys, first consider:
|
||||
/// 1. Not doing that
|
||||
/// 2. Using node_view::operator[] instead.
|
||||
///
|
||||
/// \param root The root node from which the path will be traversed.
|
||||
/// \param path The "TOML path" to traverse.
|
||||
TOML_NODISCARD
|
||||
TOML_EXPORTED_FREE_FUNCTION
|
||||
node_view<node> TOML_CALLCONV at_path(node & root, std::string_view path) noexcept;
|
||||
|
||||
/// \brief Returns a const view of the node matching a fully-qualified "TOML path".
|
||||
///
|
||||
/// \see #toml::at_path(node&, std::string_view)
|
||||
TOML_NODISCARD
|
||||
TOML_EXPORTED_FREE_FUNCTION
|
||||
node_view<const node> TOML_CALLCONV at_path(const node& root, std::string_view path) noexcept;
|
||||
|
||||
#if TOML_ENABLE_WINDOWS_COMPAT
|
||||
|
||||
/// \brief Returns a view of the node matching a fully-qualified "TOML path".
|
||||
///
|
||||
/// \availability This overload is only available when #TOML_ENABLE_WINDOWS_COMPAT is enabled.
|
||||
///
|
||||
/// \see #toml::at_path(node&, std::string_view)
|
||||
TOML_NODISCARD
|
||||
TOML_EXPORTED_FREE_FUNCTION
|
||||
node_view<node> TOML_CALLCONV at_path(node & root, std::wstring_view path);
|
||||
|
||||
/// \brief Returns a const view of the node matching a fully-qualified "TOML path".
|
||||
///
|
||||
/// \availability This overload is only available when #TOML_ENABLE_WINDOWS_COMPAT is enabled.
|
||||
///
|
||||
/// \see #toml::at_path(node&, std::string_view)
|
||||
TOML_NODISCARD
|
||||
TOML_EXPORTED_FREE_FUNCTION
|
||||
node_view<const node> TOML_CALLCONV at_path(const node& root, std::wstring_view path);
|
||||
|
||||
#endif
|
||||
}
|
||||
TOML_NAMESPACE_END;
|
||||
@@ -0,0 +1,290 @@
|
||||
//# This file is a part of toml++ and is subject to the the terms of the MIT license.
|
||||
//# Copyright (c) Mark Gillard <mark.gillard@outlook.com.au>
|
||||
//# See https://github.com/marzer/tomlplusplus/blob/master/LICENSE for the full license text.
|
||||
// SPDX-License-Identifier: MIT
|
||||
#pragma once
|
||||
|
||||
//# {{
|
||||
#include "preprocessor.hpp"
|
||||
#if !TOML_IMPLEMENTATION
|
||||
#error This is an implementation-only header.
|
||||
#endif
|
||||
//# }}
|
||||
|
||||
#include "at_path.hpp"
|
||||
#include "array.hpp"
|
||||
#include "table.hpp"
|
||||
TOML_DISABLE_WARNINGS;
|
||||
#if TOML_INT_CHARCONV
|
||||
#include <charconv>
|
||||
#else
|
||||
#include <sstream>
|
||||
#endif
|
||||
TOML_ENABLE_WARNINGS;
|
||||
#include "header_start.hpp"
|
||||
|
||||
TOML_IMPL_NAMESPACE_START
|
||||
{
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
bool TOML_CALLCONV parse_path(const std::string_view path,
|
||||
void* const data,
|
||||
const parse_path_callback<std::string_view> on_key,
|
||||
const parse_path_callback<size_t> on_index)
|
||||
{
|
||||
// a blank string is a valid path; it's just one component representing the "" key
|
||||
if (path.empty())
|
||||
return on_key(data, ""sv);
|
||||
|
||||
size_t pos = 0;
|
||||
const auto end = path.length();
|
||||
bool prev_was_array_indexer = false;
|
||||
bool prev_was_dot = true; // invisible root 'dot'
|
||||
|
||||
while (pos < end)
|
||||
{
|
||||
// start of an array indexer
|
||||
if (path[pos] == '[')
|
||||
{
|
||||
// find first digit in index
|
||||
size_t index_start = pos + 1u;
|
||||
while (true)
|
||||
{
|
||||
if TOML_UNLIKELY(index_start >= path.length())
|
||||
return false;
|
||||
|
||||
const auto c = path[index_start];
|
||||
if TOML_LIKELY(c >= '0' && c <= '9')
|
||||
break;
|
||||
else if (c == ' ' || c == '\t')
|
||||
index_start++;
|
||||
else
|
||||
return false;
|
||||
}
|
||||
TOML_ASSERT(path[index_start] >= '0');
|
||||
TOML_ASSERT(path[index_start] <= '9');
|
||||
|
||||
// find end of index (first non-digit character)
|
||||
size_t index_end = index_start + 1u;
|
||||
while (true)
|
||||
{
|
||||
// if an array indexer is missing the trailing ']' at the end of the string, permissively accept it
|
||||
if TOML_UNLIKELY(index_end >= path.length())
|
||||
break;
|
||||
|
||||
const auto c = path[index_end];
|
||||
if (c >= '0' && c <= '9')
|
||||
index_end++;
|
||||
else if (c == ']' || c == ' ' || c == '\t' || c == '.' || c == '[')
|
||||
break;
|
||||
else
|
||||
return false;
|
||||
}
|
||||
TOML_ASSERT(path[index_end - 1u] >= '0');
|
||||
TOML_ASSERT(path[index_end - 1u] <= '9');
|
||||
|
||||
// move pos to after indexer (char after closing ']' or permissively EOL/subkey '.'/next opening '[')
|
||||
pos = index_end;
|
||||
while (true)
|
||||
{
|
||||
if TOML_UNLIKELY(pos >= path.length())
|
||||
break;
|
||||
|
||||
const auto c = path[pos];
|
||||
if (c == ']')
|
||||
{
|
||||
pos++;
|
||||
break;
|
||||
}
|
||||
else if TOML_UNLIKELY(c == '.' || c == '[')
|
||||
break;
|
||||
else if (c == '\t' || c == ' ')
|
||||
pos++;
|
||||
else
|
||||
return false;
|
||||
}
|
||||
|
||||
// get array index substring
|
||||
auto index_str = path.substr(index_start, index_end - index_start);
|
||||
|
||||
// parse the actual array index to an integer type
|
||||
size_t index;
|
||||
if (index_str.length() == 1u)
|
||||
index = static_cast<size_t>(index_str[0] - '0');
|
||||
else
|
||||
{
|
||||
#if TOML_INT_CHARCONV
|
||||
|
||||
auto fc_result = std::from_chars(index_str.data(), index_str.data() + index_str.length(), index);
|
||||
if (fc_result.ec != std::errc{})
|
||||
return false;
|
||||
|
||||
#else
|
||||
|
||||
std::stringstream ss;
|
||||
ss.imbue(std::locale::classic());
|
||||
ss.write(index_str.data(), static_cast<std::streamsize>(index_str.length()));
|
||||
if (!(ss >> index))
|
||||
return false;
|
||||
|
||||
#endif
|
||||
}
|
||||
|
||||
prev_was_dot = false;
|
||||
prev_was_array_indexer = true;
|
||||
|
||||
if (!on_index(data, index))
|
||||
return false;
|
||||
}
|
||||
|
||||
// start of a new table child
|
||||
else if (path[pos] == '.')
|
||||
{
|
||||
// a dot immediately following another dot (or at the beginning of the string) is as if we'd asked
|
||||
// for an empty child in between, e.g.
|
||||
//
|
||||
// foo..bar
|
||||
//
|
||||
// is equivalent to
|
||||
//
|
||||
// "foo".""."bar"
|
||||
//
|
||||
if (prev_was_dot && !on_key(data, ""sv))
|
||||
return false;
|
||||
|
||||
pos++;
|
||||
prev_was_dot = true;
|
||||
prev_was_array_indexer = false;
|
||||
}
|
||||
|
||||
// an errant closing ']'
|
||||
else if TOML_UNLIKELY(path[pos] == ']')
|
||||
return false;
|
||||
|
||||
// some regular subkey
|
||||
else
|
||||
{
|
||||
const auto subkey_start = pos;
|
||||
const auto subkey_len =
|
||||
impl::min(path.find_first_of(".[]"sv, subkey_start + 1u), path.length()) - subkey_start;
|
||||
const auto subkey = path.substr(subkey_start, subkey_len);
|
||||
|
||||
// a regular subkey segment immediately after an array indexer is OK if it was all whitespace, e.g.:
|
||||
//
|
||||
// "foo[0] .bar"
|
||||
// ^^ skip this
|
||||
//
|
||||
// otherwise its an error (since it would have to be preceeded by a dot)
|
||||
if (prev_was_array_indexer)
|
||||
{
|
||||
auto non_ws = subkey.find_first_not_of(" \t");
|
||||
if (non_ws == std::string_view::npos)
|
||||
{
|
||||
pos += subkey_len;
|
||||
prev_was_dot = false;
|
||||
prev_was_array_indexer = false;
|
||||
continue;
|
||||
}
|
||||
else
|
||||
return false;
|
||||
}
|
||||
|
||||
pos += subkey_len;
|
||||
prev_was_dot = false;
|
||||
prev_was_array_indexer = false;
|
||||
|
||||
if (!on_key(data, subkey))
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// Last character was a '.', which implies an empty string key at the end of the path
|
||||
if (prev_was_dot && !on_key(data, ""sv))
|
||||
return false;
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
TOML_IMPL_NAMESPACE_END;
|
||||
|
||||
TOML_NAMESPACE_START
|
||||
{
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
node_view<node> TOML_CALLCONV at_path(node & root, std::string_view path) noexcept
|
||||
{
|
||||
// early-exit sanity-checks
|
||||
if (root.is_value())
|
||||
return {};
|
||||
if (auto tbl = root.as_table(); tbl && tbl->empty())
|
||||
return {};
|
||||
if (auto arr = root.as_array(); arr && arr->empty())
|
||||
return {};
|
||||
|
||||
node* current = &root;
|
||||
|
||||
static constexpr auto on_key = [](void* data, std::string_view key) noexcept -> bool
|
||||
{
|
||||
auto& curr = *static_cast<node**>(data);
|
||||
TOML_ASSERT_ASSUME(curr);
|
||||
|
||||
const auto current_table = curr->as<table>();
|
||||
if (!current_table)
|
||||
return false;
|
||||
|
||||
curr = current_table->get(key);
|
||||
return curr != nullptr;
|
||||
};
|
||||
|
||||
static constexpr auto on_index = [](void* data, size_t index) noexcept -> bool
|
||||
{
|
||||
auto& curr = *static_cast<node**>(data);
|
||||
TOML_ASSERT_ASSUME(curr);
|
||||
|
||||
const auto current_array = curr->as<array>();
|
||||
if (!current_array)
|
||||
return false;
|
||||
|
||||
curr = current_array->get(index);
|
||||
return curr != nullptr;
|
||||
};
|
||||
|
||||
if (!impl::parse_path(path, ¤t, on_key, on_index))
|
||||
current = nullptr;
|
||||
|
||||
return node_view{ current };
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
node_view<const node> TOML_CALLCONV at_path(const node& root, std::string_view path) noexcept
|
||||
{
|
||||
return node_view<const node>{ at_path(const_cast<node&>(root), path).node() };
|
||||
}
|
||||
|
||||
#if TOML_ENABLE_WINDOWS_COMPAT
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
node_view<node> TOML_CALLCONV at_path(node & root, std::wstring_view path)
|
||||
{
|
||||
// these are the same top-level checks from the narrow-string version;
|
||||
// they're hoisted up here to avoid doing the wide -> narrow conversion where it would not be necessary
|
||||
// (avoids an allocation)
|
||||
if (root.is_value())
|
||||
return {};
|
||||
if (auto tbl = root.as_table(); tbl && tbl->empty())
|
||||
return {};
|
||||
if (auto arr = root.as_array(); arr && arr->empty())
|
||||
return {};
|
||||
|
||||
return at_path(root, impl::narrow(path));
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
node_view<const node> TOML_CALLCONV at_path(const node& root, std::wstring_view path)
|
||||
{
|
||||
return node_view<const node>{ at_path(const_cast<node&>(root), path).node() };
|
||||
}
|
||||
|
||||
#endif // TOML_ENABLE_WINDOWS_COMPAT
|
||||
}
|
||||
TOML_NAMESPACE_END;
|
||||
|
||||
#include "header_end.hpp"
|
||||
@@ -0,0 +1,468 @@
|
||||
//# This file is a part of toml++ and is subject to the the terms of the MIT license.
|
||||
//# Copyright (c) Mark Gillard <mark.gillard@outlook.com.au>
|
||||
//# See https://github.com/marzer/tomlplusplus/blob/master/LICENSE for the full license text.
|
||||
// SPDX-License-Identifier: MIT
|
||||
#pragma once
|
||||
|
||||
#include "forward_declarations.hpp"
|
||||
#include "print_to_stream.hpp"
|
||||
#include "header_start.hpp"
|
||||
|
||||
TOML_NAMESPACE_START
|
||||
{
|
||||
/// \brief A local date.
|
||||
struct TOML_TRIVIAL_ABI date
|
||||
{
|
||||
/// \brief The year component.
|
||||
uint16_t year;
|
||||
|
||||
/// \brief The month component, from 1 - 12.
|
||||
uint8_t month;
|
||||
|
||||
/// \brief The day component, from 1 - 31.
|
||||
uint8_t day;
|
||||
|
||||
/// \brief Default constructor. Does not initialize the members.
|
||||
TOML_NODISCARD_CTOR
|
||||
date() noexcept = default;
|
||||
|
||||
/// \brief Constructs a date from individual date component values.
|
||||
TOML_CONSTRAINED_TEMPLATE((impl::all_integral<Y, M, D>), typename Y, typename M, typename D)
|
||||
TOML_NODISCARD_CTOR
|
||||
constexpr date(Y y, M m, D d) noexcept //
|
||||
: year{ static_cast<uint16_t>(y) },
|
||||
month{ static_cast<uint8_t>(m) },
|
||||
day{ static_cast<uint8_t>(d) }
|
||||
{}
|
||||
|
||||
/// \brief Equality operator.
|
||||
TOML_PURE_GETTER
|
||||
friend constexpr bool operator==(const date& lhs, const date& rhs) noexcept
|
||||
{
|
||||
return lhs.year == rhs.year //
|
||||
&& lhs.month == rhs.month //
|
||||
&& lhs.day == rhs.day;
|
||||
}
|
||||
|
||||
/// \brief Inequality operator.
|
||||
TOML_PURE_INLINE_GETTER
|
||||
friend constexpr bool operator!=(const date& lhs, const date& rhs) noexcept
|
||||
{
|
||||
return !(lhs == rhs);
|
||||
}
|
||||
|
||||
private:
|
||||
/// \cond
|
||||
|
||||
TOML_PURE_GETTER
|
||||
static constexpr uint32_t pack(const date& d) noexcept
|
||||
{
|
||||
return (static_cast<uint32_t>(d.year) << 16) | (static_cast<uint32_t>(d.month) << 8)
|
||||
| static_cast<uint32_t>(d.day);
|
||||
}
|
||||
|
||||
/// \endcond
|
||||
|
||||
public:
|
||||
/// \brief Less-than operator.
|
||||
TOML_PURE_GETTER
|
||||
friend constexpr bool operator<(const date& lhs, const date& rhs) noexcept
|
||||
{
|
||||
return pack(lhs) < pack(rhs);
|
||||
}
|
||||
|
||||
/// \brief Less-than-or-equal-to operator.
|
||||
TOML_PURE_GETTER
|
||||
friend constexpr bool operator<=(const date& lhs, const date& rhs) noexcept
|
||||
{
|
||||
return pack(lhs) <= pack(rhs);
|
||||
}
|
||||
|
||||
/// \brief Greater-than operator.
|
||||
TOML_PURE_GETTER
|
||||
friend constexpr bool operator>(const date& lhs, const date& rhs) noexcept
|
||||
{
|
||||
return pack(lhs) > pack(rhs);
|
||||
}
|
||||
|
||||
/// \brief Greater-than-or-equal-to operator.
|
||||
TOML_PURE_GETTER
|
||||
friend constexpr bool operator>=(const date& lhs, const date& rhs) noexcept
|
||||
{
|
||||
return pack(lhs) >= pack(rhs);
|
||||
}
|
||||
|
||||
/// \brief Prints a date out to a stream as `YYYY-MM-DD` (per RFC 3339).
|
||||
///
|
||||
/// \detail \cpp
|
||||
/// std::cout << toml::date{ 1987, 3, 16 } << "\n";
|
||||
/// \ecpp
|
||||
///
|
||||
/// \out
|
||||
/// 1987-03-16
|
||||
/// \eout
|
||||
friend std::ostream& operator<<(std::ostream& lhs, const date& rhs)
|
||||
{
|
||||
impl::print_to_stream(lhs, rhs);
|
||||
return lhs;
|
||||
}
|
||||
};
|
||||
|
||||
/// \brief A local time-of-day.
|
||||
struct TOML_TRIVIAL_ABI time
|
||||
{
|
||||
/// \brief The hour component, from 0 - 23.
|
||||
uint8_t hour;
|
||||
|
||||
/// \brief The minute component, from 0 - 59.
|
||||
uint8_t minute;
|
||||
|
||||
/// \brief The second component, from 0 - 59.
|
||||
uint8_t second;
|
||||
|
||||
/// \brief The fractional nanoseconds component, from 0 - 999999999.
|
||||
uint32_t nanosecond;
|
||||
|
||||
/// \brief Default constructor. Does not initialize the members.
|
||||
TOML_NODISCARD_CTOR
|
||||
time() noexcept = default;
|
||||
|
||||
/// \brief Constructs a time from individual time component values.
|
||||
TOML_CONSTRAINED_TEMPLATE((impl::all_integral<H, M, S, NS>),
|
||||
typename H,
|
||||
typename M,
|
||||
typename S = uint8_t,
|
||||
typename NS = uint32_t)
|
||||
TOML_NODISCARD_CTOR
|
||||
constexpr time(H h, M m, S s = S{}, NS ns = NS{}) noexcept //
|
||||
: hour{ static_cast<uint8_t>(h) },
|
||||
minute{ static_cast<uint8_t>(m) },
|
||||
second{ static_cast<uint8_t>(s) },
|
||||
nanosecond{ static_cast<uint32_t>(ns) }
|
||||
{}
|
||||
|
||||
/// \brief Equality operator.
|
||||
TOML_PURE_GETTER
|
||||
friend constexpr bool operator==(const time& lhs, const time& rhs) noexcept
|
||||
{
|
||||
return lhs.hour == rhs.hour //
|
||||
&& lhs.minute == rhs.minute //
|
||||
&& lhs.second == rhs.second //
|
||||
&& lhs.nanosecond == rhs.nanosecond;
|
||||
}
|
||||
|
||||
/// \brief Inequality operator.
|
||||
TOML_PURE_INLINE_GETTER
|
||||
friend constexpr bool operator!=(const time& lhs, const time& rhs) noexcept
|
||||
{
|
||||
return !(lhs == rhs);
|
||||
}
|
||||
|
||||
private:
|
||||
/// \cond
|
||||
|
||||
TOML_PURE_GETTER
|
||||
static constexpr uint64_t pack(const time& t) noexcept
|
||||
{
|
||||
return static_cast<uint64_t>(t.hour) << 48 | static_cast<uint64_t>(t.minute) << 40
|
||||
| static_cast<uint64_t>(t.second) << 32 | static_cast<uint64_t>(t.nanosecond);
|
||||
}
|
||||
|
||||
/// \endcond
|
||||
|
||||
public:
|
||||
/// \brief Less-than operator.
|
||||
TOML_PURE_GETTER
|
||||
friend constexpr bool operator<(const time& lhs, const time& rhs) noexcept
|
||||
{
|
||||
return pack(lhs) < pack(rhs);
|
||||
}
|
||||
|
||||
/// \brief Less-than-or-equal-to operator.
|
||||
TOML_PURE_GETTER
|
||||
friend constexpr bool operator<=(const time& lhs, const time& rhs) noexcept
|
||||
{
|
||||
return pack(lhs) <= pack(rhs);
|
||||
}
|
||||
|
||||
/// \brief Greater-than operator.
|
||||
TOML_PURE_GETTER
|
||||
friend constexpr bool operator>(const time& lhs, const time& rhs) noexcept
|
||||
{
|
||||
return pack(lhs) > pack(rhs);
|
||||
}
|
||||
|
||||
/// \brief Greater-than-or-equal-to operator.
|
||||
TOML_PURE_GETTER
|
||||
friend constexpr bool operator>=(const time& lhs, const time& rhs) noexcept
|
||||
{
|
||||
return pack(lhs) >= pack(rhs);
|
||||
}
|
||||
|
||||
/// \brief Prints a time out to a stream as `HH:MM:SS.FFFFFF` (per RFC 3339).
|
||||
/// \detail \cpp
|
||||
/// std::cout << toml::time{ 10, 20, 34 } << "\n";
|
||||
/// std::cout << toml::time{ 10, 20, 34, 500000000 } << "\n";
|
||||
/// \ecpp
|
||||
///
|
||||
/// \out
|
||||
/// 10:20:34
|
||||
/// 10:20:34.5
|
||||
/// \eout
|
||||
friend std::ostream& operator<<(std::ostream& lhs, const time& rhs)
|
||||
{
|
||||
impl::print_to_stream(lhs, rhs);
|
||||
return lhs;
|
||||
}
|
||||
};
|
||||
|
||||
/// \brief A timezone offset.
|
||||
struct TOML_TRIVIAL_ABI time_offset
|
||||
{
|
||||
/// \brief Offset from UTC+0, in minutes.
|
||||
int16_t minutes;
|
||||
|
||||
/// \brief Default constructor. Does not initialize the members.
|
||||
TOML_NODISCARD_CTOR
|
||||
time_offset() noexcept = default;
|
||||
|
||||
/// \brief Constructs a timezone offset from individual hour and minute totals.
|
||||
///
|
||||
/// \detail \cpp
|
||||
/// std::cout << toml::time_offset{ 2, 30 } << "\n";
|
||||
/// std::cout << toml::time_offset{ -2, 30 } << "\n";
|
||||
/// std::cout << toml::time_offset{ -2, -30 } << "\n";
|
||||
/// std::cout << toml::time_offset{ 0, 0 } << "\n";
|
||||
/// \ecpp
|
||||
///
|
||||
/// \out
|
||||
/// +02:30
|
||||
/// -01:30
|
||||
/// -02:30
|
||||
/// Z
|
||||
/// \eout
|
||||
///
|
||||
/// \tparam H An integral type.
|
||||
/// \tparam M An integral type.
|
||||
///
|
||||
/// \param h The total hours.
|
||||
/// \param m The total minutes.
|
||||
TOML_CONSTRAINED_TEMPLATE((impl::all_integral<H, M>), typename H, typename M)
|
||||
TOML_NODISCARD_CTOR
|
||||
constexpr time_offset(H h, M m) noexcept //
|
||||
: minutes{ static_cast<int16_t>(static_cast<impl::common_signed_type<H, M>>(h)
|
||||
* impl::common_signed_type<H, M>{ 60 }
|
||||
+ static_cast<impl::common_signed_type<H, M>>(m)) }
|
||||
{}
|
||||
|
||||
/// \brief Equality operator.
|
||||
TOML_PURE_INLINE_GETTER
|
||||
friend constexpr bool operator==(time_offset lhs, time_offset rhs) noexcept
|
||||
{
|
||||
return lhs.minutes == rhs.minutes;
|
||||
}
|
||||
|
||||
/// \brief Inequality operator.
|
||||
TOML_PURE_INLINE_GETTER
|
||||
friend constexpr bool operator!=(time_offset lhs, time_offset rhs) noexcept
|
||||
{
|
||||
return lhs.minutes != rhs.minutes;
|
||||
}
|
||||
|
||||
/// \brief Less-than operator.
|
||||
TOML_PURE_INLINE_GETTER
|
||||
friend constexpr bool operator<(time_offset lhs, time_offset rhs) noexcept
|
||||
{
|
||||
return lhs.minutes < rhs.minutes;
|
||||
}
|
||||
|
||||
/// \brief Less-than-or-equal-to operator.
|
||||
TOML_PURE_INLINE_GETTER
|
||||
friend constexpr bool operator<=(time_offset lhs, time_offset rhs) noexcept
|
||||
{
|
||||
return lhs.minutes <= rhs.minutes;
|
||||
}
|
||||
|
||||
/// \brief Greater-than operator.
|
||||
TOML_PURE_INLINE_GETTER
|
||||
friend constexpr bool operator>(time_offset lhs, time_offset rhs) noexcept
|
||||
{
|
||||
return lhs.minutes > rhs.minutes;
|
||||
}
|
||||
|
||||
/// \brief Greater-than-or-equal-to operator.
|
||||
TOML_PURE_INLINE_GETTER
|
||||
friend constexpr bool operator>=(time_offset lhs, time_offset rhs) noexcept
|
||||
{
|
||||
return lhs.minutes >= rhs.minutes;
|
||||
}
|
||||
|
||||
/// \brief Prints a time_offset out to a stream as `+-HH:MM or Z` (per RFC 3339).
|
||||
/// \detail \cpp
|
||||
/// std::cout << toml::time_offset{ 2, 30 } << "\n";
|
||||
/// std::cout << toml::time_offset{ 2, -30 } << "\n";
|
||||
/// std::cout << toml::time_offset{} << "\n";
|
||||
/// std::cout << toml::time_offset{ -2, 30 } << "\n";
|
||||
/// std::cout << toml::time_offset{ -2, -30 } << "\n";
|
||||
/// \ecpp
|
||||
///
|
||||
/// \out
|
||||
/// +02:30
|
||||
/// +01:30
|
||||
/// Z
|
||||
/// -01:30
|
||||
/// -02:30
|
||||
/// \eout
|
||||
friend std::ostream& operator<<(std::ostream& lhs, const time_offset& rhs)
|
||||
{
|
||||
impl::print_to_stream(lhs, rhs);
|
||||
return lhs;
|
||||
}
|
||||
};
|
||||
|
||||
TOML_ABI_NAMESPACE_BOOL(TOML_HAS_CUSTOM_OPTIONAL_TYPE, custopt, stdopt);
|
||||
|
||||
/// \brief A date-time.
|
||||
struct date_time
|
||||
{
|
||||
/// \brief The date component.
|
||||
toml::date date;
|
||||
|
||||
/// \brief The time component.
|
||||
toml::time time;
|
||||
|
||||
/// \brief The timezone offset component.
|
||||
///
|
||||
/// \remarks The date_time is said to be 'local' if the offset is empty.
|
||||
optional<toml::time_offset> offset;
|
||||
|
||||
/// \brief Default constructor. Does not initialize the members.
|
||||
TOML_NODISCARD_CTOR
|
||||
date_time() noexcept = default;
|
||||
|
||||
/// \brief Constructs a local date-time.
|
||||
///
|
||||
/// \param d The date component.
|
||||
/// \param t The time component.
|
||||
TOML_NODISCARD_CTOR
|
||||
constexpr date_time(const toml::date& d, const toml::time& t) noexcept //
|
||||
: date{ d },
|
||||
time{ t },
|
||||
offset{} // TINAE - icc bugfix
|
||||
{}
|
||||
|
||||
/// \brief Constructs a local date-time.
|
||||
///
|
||||
/// \param d The date component.
|
||||
TOML_NODISCARD_CTOR
|
||||
explicit constexpr date_time(const toml::date& d) noexcept //
|
||||
: date{ d },
|
||||
time{},
|
||||
offset{} // TINAE - icc bugfix
|
||||
{}
|
||||
|
||||
/// \brief Constructs a local date-time.
|
||||
///
|
||||
/// \param t The time component.
|
||||
TOML_NODISCARD_CTOR
|
||||
explicit constexpr date_time(const toml::time& t) noexcept //
|
||||
: date{},
|
||||
time{ t },
|
||||
offset{} // TINAE - icc bugfix
|
||||
{}
|
||||
|
||||
/// \brief Constructs an offset date-time.
|
||||
///
|
||||
/// \param d The date component.
|
||||
/// \param t The time component.
|
||||
/// \param off The timezone offset.
|
||||
TOML_NODISCARD_CTOR
|
||||
constexpr date_time(const toml::date& d, const toml::time& t, const toml::time_offset& off) noexcept
|
||||
: date{ d },
|
||||
time{ t },
|
||||
offset{ off }
|
||||
{}
|
||||
|
||||
/// \brief Returns true if this date_time does not contain timezone offset information.
|
||||
TOML_PURE_INLINE_GETTER
|
||||
constexpr bool is_local() const noexcept
|
||||
{
|
||||
return !offset.has_value();
|
||||
}
|
||||
|
||||
/// \brief Equality operator.
|
||||
TOML_PURE_GETTER
|
||||
friend constexpr bool operator==(const date_time& lhs, const date_time& rhs) noexcept
|
||||
{
|
||||
return lhs.date == rhs.date //
|
||||
&& lhs.time == rhs.time //
|
||||
&& lhs.offset == rhs.offset;
|
||||
}
|
||||
|
||||
/// \brief Inequality operator.
|
||||
TOML_PURE_INLINE_GETTER
|
||||
friend constexpr bool operator!=(const date_time& lhs, const date_time& rhs) noexcept
|
||||
{
|
||||
return !(lhs == rhs);
|
||||
}
|
||||
|
||||
/// \brief Less-than operator.
|
||||
TOML_PURE_GETTER
|
||||
friend constexpr bool operator<(const date_time& lhs, const date_time& rhs) noexcept
|
||||
{
|
||||
if (lhs.date != rhs.date)
|
||||
return lhs.date < rhs.date;
|
||||
if (lhs.time != rhs.time)
|
||||
return lhs.time < rhs.time;
|
||||
return lhs.offset < rhs.offset;
|
||||
}
|
||||
|
||||
/// \brief Less-than-or-equal-to operator.
|
||||
TOML_PURE_GETTER
|
||||
friend constexpr bool operator<=(const date_time& lhs, const date_time& rhs) noexcept
|
||||
{
|
||||
if (lhs.date != rhs.date)
|
||||
return lhs.date < rhs.date;
|
||||
if (lhs.time != rhs.time)
|
||||
return lhs.time < rhs.time;
|
||||
return lhs.offset <= rhs.offset;
|
||||
}
|
||||
|
||||
/// \brief Greater-than operator.
|
||||
TOML_PURE_INLINE_GETTER
|
||||
friend constexpr bool operator>(const date_time& lhs, const date_time& rhs) noexcept
|
||||
{
|
||||
return !(lhs <= rhs);
|
||||
}
|
||||
|
||||
/// \brief Greater-than-or-equal-to operator.
|
||||
TOML_PURE_INLINE_GETTER
|
||||
friend constexpr bool operator>=(const date_time& lhs, const date_time& rhs) noexcept
|
||||
{
|
||||
return !(lhs < rhs);
|
||||
}
|
||||
|
||||
/// \brief Prints a date_time out to a stream in RFC 3339 format.
|
||||
/// \detail \cpp
|
||||
/// std::cout << toml::date_time{ { 1987, 3, 16 }, { 10, 20, 34 } } << "\n";
|
||||
/// std::cout << toml::date_time{ { 1987, 3, 16 }, { 10, 20, 34 }, { -2, -30 } } << "\n";
|
||||
/// std::cout << toml::date_time{ { 1987, 3, 16 }, { 10, 20, 34 }, {} } << "\n";
|
||||
/// \ecpp
|
||||
///
|
||||
/// \out
|
||||
/// 1987-03-16T10:20:34
|
||||
/// 1987-03-16T10:20:34-02:30
|
||||
/// 1987-03-16T10:20:34Z
|
||||
/// \eout
|
||||
friend std::ostream& operator<<(std::ostream& lhs, const date_time& rhs)
|
||||
{
|
||||
impl::print_to_stream(lhs, rhs);
|
||||
return lhs;
|
||||
}
|
||||
};
|
||||
|
||||
TOML_ABI_NAMESPACE_END; // TOML_HAS_CUSTOM_OPTIONAL_TYPE
|
||||
}
|
||||
TOML_NAMESPACE_END;
|
||||
|
||||
#include "header_end.hpp"
|
||||
@@ -0,0 +1,194 @@
|
||||
//# This file is a part of toml++ and is subject to the the terms of the MIT license.
|
||||
//# Copyright (c) Mark Gillard <mark.gillard@outlook.com.au>
|
||||
//# See https://github.com/marzer/tomlplusplus/blob/master/LICENSE for the full license text.
|
||||
// SPDX-License-Identifier: MIT
|
||||
#pragma once
|
||||
|
||||
#include "preprocessor.hpp"
|
||||
#if TOML_ENABLE_FORMATTERS
|
||||
|
||||
#include "forward_declarations.hpp"
|
||||
#include "print_to_stream.hpp"
|
||||
#include "header_start.hpp"
|
||||
/// \cond
|
||||
|
||||
TOML_IMPL_NAMESPACE_START
|
||||
{
|
||||
struct formatter_constants
|
||||
{
|
||||
format_flags mandatory_flags;
|
||||
format_flags ignored_flags;
|
||||
|
||||
std::string_view float_pos_inf;
|
||||
std::string_view float_neg_inf;
|
||||
std::string_view float_nan;
|
||||
|
||||
std::string_view bool_true;
|
||||
std::string_view bool_false;
|
||||
};
|
||||
|
||||
struct formatter_config
|
||||
{
|
||||
format_flags flags;
|
||||
std::string_view indent;
|
||||
};
|
||||
|
||||
class TOML_EXPORTED_CLASS formatter
|
||||
{
|
||||
private:
|
||||
const node* source_;
|
||||
#if TOML_ENABLE_PARSER && !TOML_EXCEPTIONS
|
||||
const parse_result* result_;
|
||||
#endif
|
||||
const formatter_constants* constants_;
|
||||
formatter_config config_;
|
||||
size_t indent_columns_;
|
||||
format_flags int_format_mask_;
|
||||
std::ostream* stream_; //
|
||||
int indent_; // these are set in attach()
|
||||
bool naked_newline_; //
|
||||
|
||||
protected:
|
||||
TOML_PURE_INLINE_GETTER
|
||||
const node& source() const noexcept
|
||||
{
|
||||
return *source_;
|
||||
}
|
||||
|
||||
TOML_PURE_INLINE_GETTER
|
||||
std::ostream& stream() const noexcept
|
||||
{
|
||||
return *stream_;
|
||||
}
|
||||
|
||||
TOML_PURE_INLINE_GETTER
|
||||
int indent() const noexcept
|
||||
{
|
||||
return indent_;
|
||||
}
|
||||
|
||||
void indent(int level) noexcept
|
||||
{
|
||||
indent_ = level;
|
||||
}
|
||||
|
||||
void increase_indent() noexcept
|
||||
{
|
||||
indent_++;
|
||||
}
|
||||
|
||||
void decrease_indent() noexcept
|
||||
{
|
||||
indent_--;
|
||||
}
|
||||
|
||||
TOML_PURE_INLINE_GETTER
|
||||
size_t indent_columns() const noexcept
|
||||
{
|
||||
return indent_columns_;
|
||||
}
|
||||
|
||||
TOML_PURE_INLINE_GETTER
|
||||
bool indent_array_elements() const noexcept
|
||||
{
|
||||
return !!(config_.flags & format_flags::indent_array_elements);
|
||||
}
|
||||
|
||||
TOML_PURE_INLINE_GETTER
|
||||
bool indent_sub_tables() const noexcept
|
||||
{
|
||||
return !!(config_.flags & format_flags::indent_sub_tables);
|
||||
}
|
||||
|
||||
TOML_PURE_INLINE_GETTER
|
||||
bool literal_strings_allowed() const noexcept
|
||||
{
|
||||
return !!(config_.flags & format_flags::allow_literal_strings);
|
||||
}
|
||||
|
||||
TOML_PURE_INLINE_GETTER
|
||||
bool multi_line_strings_allowed() const noexcept
|
||||
{
|
||||
return !!(config_.flags & format_flags::allow_multi_line_strings);
|
||||
}
|
||||
|
||||
TOML_PURE_INLINE_GETTER
|
||||
bool real_tabs_in_strings_allowed() const noexcept
|
||||
{
|
||||
return !!(config_.flags & format_flags::allow_real_tabs_in_strings);
|
||||
}
|
||||
|
||||
TOML_PURE_INLINE_GETTER
|
||||
bool unicode_strings_allowed() const noexcept
|
||||
{
|
||||
return !!(config_.flags & format_flags::allow_unicode_strings);
|
||||
}
|
||||
|
||||
TOML_PURE_INLINE_GETTER
|
||||
bool terse_kvps() const noexcept
|
||||
{
|
||||
return !!(config_.flags & format_flags::terse_key_value_pairs);
|
||||
}
|
||||
|
||||
TOML_EXPORTED_MEMBER_FUNCTION
|
||||
void attach(std::ostream& stream) noexcept;
|
||||
|
||||
TOML_EXPORTED_MEMBER_FUNCTION
|
||||
void detach() noexcept;
|
||||
|
||||
TOML_EXPORTED_MEMBER_FUNCTION
|
||||
void print_newline(bool force = false);
|
||||
|
||||
TOML_EXPORTED_MEMBER_FUNCTION
|
||||
void print_indent();
|
||||
|
||||
TOML_EXPORTED_MEMBER_FUNCTION
|
||||
void print_unformatted(char);
|
||||
|
||||
TOML_EXPORTED_MEMBER_FUNCTION
|
||||
void print_unformatted(std::string_view);
|
||||
|
||||
TOML_EXPORTED_MEMBER_FUNCTION
|
||||
void print_string(std::string_view str,
|
||||
bool allow_multi_line = true,
|
||||
bool allow_bare = false,
|
||||
bool allow_literal_whitespace = true);
|
||||
|
||||
TOML_EXPORTED_MEMBER_FUNCTION
|
||||
void print(const value<std::string>&);
|
||||
|
||||
TOML_EXPORTED_MEMBER_FUNCTION
|
||||
void print(const value<int64_t>&);
|
||||
|
||||
TOML_EXPORTED_MEMBER_FUNCTION
|
||||
void print(const value<double>&);
|
||||
|
||||
TOML_EXPORTED_MEMBER_FUNCTION
|
||||
void print(const value<bool>&);
|
||||
|
||||
TOML_EXPORTED_MEMBER_FUNCTION
|
||||
void print(const value<date>&);
|
||||
|
||||
TOML_EXPORTED_MEMBER_FUNCTION
|
||||
void print(const value<time>&);
|
||||
|
||||
TOML_EXPORTED_MEMBER_FUNCTION
|
||||
void print(const value<date_time>&);
|
||||
|
||||
TOML_EXPORTED_MEMBER_FUNCTION
|
||||
void print_value(const node&, node_type);
|
||||
|
||||
TOML_NODISCARD
|
||||
TOML_EXPORTED_MEMBER_FUNCTION
|
||||
bool dump_failed_parse_result();
|
||||
|
||||
TOML_NODISCARD_CTOR
|
||||
TOML_EXPORTED_MEMBER_FUNCTION
|
||||
formatter(const node*, const parse_result*, const formatter_constants&, const formatter_config&) noexcept;
|
||||
};
|
||||
}
|
||||
TOML_IMPL_NAMESPACE_END;
|
||||
|
||||
/// \endcond
|
||||
#include "header_end.hpp"
|
||||
#endif // TOML_ENABLE_FORMATTERS
|
||||
@@ -0,0 +1,523 @@
|
||||
//# This file is a part of toml++ and is subject to the the terms of the MIT license.
|
||||
//# Copyright (c) Mark Gillard <mark.gillard@outlook.com.au>
|
||||
//# See https://github.com/marzer/tomlplusplus/blob/master/LICENSE for the full license text.
|
||||
// SPDX-License-Identifier: MIT
|
||||
#pragma once
|
||||
|
||||
#include "preprocessor.hpp"
|
||||
//# {{
|
||||
#if !TOML_IMPLEMENTATION
|
||||
#error This is an implementation-only header.
|
||||
#endif
|
||||
//# }}
|
||||
#if TOML_ENABLE_FORMATTERS
|
||||
|
||||
#include "formatter.hpp"
|
||||
#include "print_to_stream.hpp"
|
||||
#include "value.hpp"
|
||||
#include "table.hpp"
|
||||
#include "array.hpp"
|
||||
#include "unicode.hpp"
|
||||
#include "parse_result.hpp"
|
||||
#include "header_start.hpp"
|
||||
|
||||
TOML_IMPL_NAMESPACE_START
|
||||
{
|
||||
enum class TOML_CLOSED_FLAGS_ENUM formatted_string_traits : unsigned
|
||||
{
|
||||
none,
|
||||
line_breaks = 1u << 0, // \n
|
||||
tabs = 1u << 1, // \t
|
||||
control_chars = 1u << 2, // also includes non-ascii vertical whitespace
|
||||
single_quotes = 1u << 3,
|
||||
non_bare = 1u << 4, // anything not satisfying "is bare key character"
|
||||
non_ascii = 1u << 5, // any codepoint >= 128
|
||||
|
||||
all = (non_ascii << 1u) - 1u
|
||||
};
|
||||
TOML_MAKE_FLAGS(formatted_string_traits);
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
formatter::formatter(const node* source_node,
|
||||
const parse_result* source_pr,
|
||||
const formatter_constants& constants,
|
||||
const formatter_config& config) noexcept //
|
||||
#if TOML_ENABLE_PARSER && !TOML_EXCEPTIONS
|
||||
: source_{ source_pr && *source_pr ? &source_pr->table() : source_node },
|
||||
result_{ source_pr },
|
||||
#else
|
||||
: source_{ source_pr ? source_pr : source_node },
|
||||
#endif
|
||||
constants_{ &constants },
|
||||
config_{ config }
|
||||
{
|
||||
TOML_ASSERT_ASSUME(source_);
|
||||
|
||||
config_.flags = (config_.flags | constants_->mandatory_flags) & ~constants_->ignored_flags;
|
||||
|
||||
indent_columns_ = {};
|
||||
for (auto c : config_.indent)
|
||||
indent_columns_ += c == '\t' ? 4u : 1u;
|
||||
|
||||
int_format_mask_ = config_.flags
|
||||
& (format_flags::allow_binary_integers | format_flags::allow_octal_integers
|
||||
| format_flags::allow_hexadecimal_integers);
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
void formatter::attach(std::ostream & stream) noexcept
|
||||
{
|
||||
indent_ = {};
|
||||
naked_newline_ = true;
|
||||
stream_ = &stream;
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
void formatter::detach() noexcept
|
||||
{
|
||||
stream_ = nullptr;
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
void formatter::print_newline(bool force)
|
||||
{
|
||||
if (!naked_newline_ || force)
|
||||
{
|
||||
print_to_stream(*stream_, '\n');
|
||||
naked_newline_ = true;
|
||||
}
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
void formatter::print_indent()
|
||||
{
|
||||
for (int i = 0; i < indent_; i++)
|
||||
{
|
||||
print_to_stream(*stream_, config_.indent);
|
||||
naked_newline_ = false;
|
||||
}
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
void formatter::print_unformatted(char c)
|
||||
{
|
||||
print_to_stream(*stream_, c);
|
||||
naked_newline_ = false;
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
void formatter::print_unformatted(std::string_view str)
|
||||
{
|
||||
print_to_stream(*stream_, str);
|
||||
naked_newline_ = false;
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
void formatter::print_string(std::string_view str,
|
||||
bool allow_multi_line,
|
||||
bool allow_bare,
|
||||
bool allow_literal_whitespace)
|
||||
{
|
||||
if (str.empty())
|
||||
{
|
||||
print_unformatted(literal_strings_allowed() ? "''"sv : "\"\""sv);
|
||||
return;
|
||||
}
|
||||
|
||||
// pre-scan the string to determine how we should output it
|
||||
formatted_string_traits traits = {};
|
||||
|
||||
if (!allow_bare)
|
||||
traits |= formatted_string_traits::non_bare;
|
||||
bool unicode_allowed = unicode_strings_allowed();
|
||||
|
||||
// ascii fast path
|
||||
if (is_ascii(str.data(), str.length()))
|
||||
{
|
||||
for (auto c : str)
|
||||
{
|
||||
switch (c)
|
||||
{
|
||||
case '\n': traits |= formatted_string_traits::line_breaks; break;
|
||||
case '\t': traits |= formatted_string_traits::tabs; break;
|
||||
case '\'': traits |= formatted_string_traits::single_quotes; break;
|
||||
default:
|
||||
{
|
||||
if TOML_UNLIKELY(is_control_character(c))
|
||||
traits |= formatted_string_traits::control_chars;
|
||||
|
||||
if (!is_ascii_bare_key_character(static_cast<char32_t>(c)))
|
||||
traits |= formatted_string_traits::non_bare;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
static constexpr auto all_ascii_traits =
|
||||
formatted_string_traits::all & ~formatted_string_traits::non_ascii;
|
||||
if (traits == all_ascii_traits)
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// unicode slow path
|
||||
else
|
||||
{
|
||||
traits |= formatted_string_traits::non_ascii;
|
||||
utf8_decoder decoder;
|
||||
|
||||
// if the unicode is malformed just treat the string as a single-line non-literal and
|
||||
// escape all non-ascii characters (to ensure round-tripping and help with diagnostics)
|
||||
const auto bad_unicode = [&]() noexcept
|
||||
{
|
||||
traits &= ~formatted_string_traits::line_breaks;
|
||||
traits |= formatted_string_traits::control_chars | formatted_string_traits::non_bare;
|
||||
unicode_allowed = false;
|
||||
};
|
||||
|
||||
for (auto c : str)
|
||||
{
|
||||
decoder(c);
|
||||
|
||||
if TOML_UNLIKELY(decoder.error())
|
||||
{
|
||||
bad_unicode();
|
||||
break;
|
||||
}
|
||||
|
||||
if (!decoder.has_code_point())
|
||||
continue;
|
||||
|
||||
switch (decoder.codepoint)
|
||||
{
|
||||
case U'\n': traits |= formatted_string_traits::line_breaks; break;
|
||||
case U'\t': traits |= formatted_string_traits::tabs; break;
|
||||
case U'\'': traits |= formatted_string_traits::single_quotes; break;
|
||||
default:
|
||||
{
|
||||
if TOML_UNLIKELY(is_control_character(decoder.codepoint)
|
||||
|| is_non_ascii_vertical_whitespace(decoder.codepoint))
|
||||
traits |= formatted_string_traits::control_chars;
|
||||
|
||||
if (!is_bare_key_character(decoder.codepoint))
|
||||
traits |= formatted_string_traits::non_bare;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (decoder.needs_more_input())
|
||||
bad_unicode();
|
||||
}
|
||||
|
||||
// strings with line breaks, tabs, and single-quotes can't be bare
|
||||
if (!!(traits
|
||||
& (formatted_string_traits::line_breaks | formatted_string_traits::tabs
|
||||
| formatted_string_traits::single_quotes)))
|
||||
traits |= formatted_string_traits::non_bare;
|
||||
|
||||
// if the string meets the requirements of being 'bare' we can emit a bare string
|
||||
// (bare strings are composed of letters and numbers; no whitespace, control chars, quotes, etc)
|
||||
if (!(traits & formatted_string_traits::non_bare)
|
||||
&& (!(traits & formatted_string_traits::non_ascii) || unicode_allowed))
|
||||
{
|
||||
print_unformatted(str);
|
||||
return;
|
||||
}
|
||||
const auto real_tabs_allowed = allow_literal_whitespace && real_tabs_in_strings_allowed();
|
||||
|
||||
// determine if this should be a multi-line string (triple-quotes)
|
||||
const auto multi_line = allow_literal_whitespace //
|
||||
&& allow_multi_line //
|
||||
&& multi_line_strings_allowed() //
|
||||
&& !!(traits & formatted_string_traits::line_breaks);
|
||||
|
||||
// determine if this should be a literal string (single-quotes with no escaping)
|
||||
const auto literal = literal_strings_allowed() //
|
||||
&& !(traits & formatted_string_traits::control_chars) //
|
||||
&& (!(traits & formatted_string_traits::single_quotes) || multi_line) //
|
||||
&& (!(traits & formatted_string_traits::tabs) || real_tabs_allowed) //
|
||||
&& (!(traits & formatted_string_traits::line_breaks) || multi_line) //
|
||||
&& (!(traits & formatted_string_traits::non_ascii) || unicode_allowed);
|
||||
|
||||
// literal strings (single quotes, no escape codes)
|
||||
if (literal)
|
||||
{
|
||||
const auto quot = multi_line ? R"(''')"sv : R"(')"sv;
|
||||
print_unformatted(quot);
|
||||
print_unformatted(str);
|
||||
print_unformatted(quot);
|
||||
return;
|
||||
}
|
||||
|
||||
// anything from here down is a non-literal string, so requires iteration and escaping.
|
||||
print_unformatted(multi_line ? R"(""")"sv : R"(")"sv);
|
||||
|
||||
// ascii fast path
|
||||
if (!(traits & formatted_string_traits::non_ascii))
|
||||
{
|
||||
for (auto c : str)
|
||||
{
|
||||
switch (c)
|
||||
{
|
||||
case '"': print_to_stream(*stream_, R"(\")"sv); break;
|
||||
case '\\': print_to_stream(*stream_, R"(\\)"sv); break;
|
||||
case '\x7F': print_to_stream(*stream_, R"(\u007F)"sv); break;
|
||||
case '\t': print_to_stream(*stream_, real_tabs_allowed ? "\t"sv : R"(\t)"sv); break;
|
||||
case '\n': print_to_stream(*stream_, multi_line ? "\n"sv : R"(\n)"sv); break;
|
||||
default:
|
||||
{
|
||||
// control characters from lookup table
|
||||
if TOML_UNLIKELY(c >= '\x00' && c <= '\x1F')
|
||||
print_to_stream(*stream_, control_char_escapes[c]);
|
||||
|
||||
// regular characters
|
||||
else
|
||||
print_to_stream(*stream_, c);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// unicode slow path
|
||||
else
|
||||
{
|
||||
utf8_decoder decoder;
|
||||
const char* cp_start = str.data();
|
||||
const char* cp_end = cp_start;
|
||||
for (auto c : str)
|
||||
{
|
||||
decoder(c);
|
||||
cp_end++;
|
||||
|
||||
// if the decoder encounters malformed unicode just emit raw bytes and
|
||||
if (decoder.error())
|
||||
{
|
||||
while (cp_start != cp_end)
|
||||
{
|
||||
print_to_stream(*stream_, R"(\u00)"sv);
|
||||
print_to_stream(*stream_,
|
||||
static_cast<uint8_t>(*cp_start),
|
||||
value_flags::format_as_hexadecimal,
|
||||
2);
|
||||
cp_start++;
|
||||
}
|
||||
decoder.reset();
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!decoder.has_code_point())
|
||||
continue;
|
||||
|
||||
switch (decoder.codepoint)
|
||||
{
|
||||
case U'"': print_to_stream(*stream_, R"(\")"sv); break;
|
||||
case U'\\': print_to_stream(*stream_, R"(\\)"sv); break;
|
||||
case U'\x7F': print_to_stream(*stream_, R"(\u007F)"sv); break;
|
||||
case U'\t': print_to_stream(*stream_, real_tabs_allowed ? "\t"sv : R"(\t)"sv); break;
|
||||
case U'\n': print_to_stream(*stream_, multi_line ? "\n"sv : R"(\n)"sv); break;
|
||||
default:
|
||||
{
|
||||
// control characters from lookup table
|
||||
if TOML_UNLIKELY(decoder.codepoint <= U'\x1F')
|
||||
print_to_stream(*stream_,
|
||||
control_char_escapes[static_cast<uint_least32_t>(decoder.codepoint)]);
|
||||
|
||||
// escaped unicode characters
|
||||
else if (decoder.codepoint > U'\x7F'
|
||||
&& (!unicode_allowed || is_non_ascii_vertical_whitespace(decoder.codepoint)))
|
||||
{
|
||||
if (static_cast<uint_least32_t>(decoder.codepoint) > 0xFFFFu)
|
||||
{
|
||||
print_to_stream(*stream_, R"(\U)"sv);
|
||||
print_to_stream(*stream_,
|
||||
static_cast<uint_least32_t>(decoder.codepoint),
|
||||
value_flags::format_as_hexadecimal,
|
||||
8);
|
||||
}
|
||||
else
|
||||
{
|
||||
print_to_stream(*stream_, R"(\u)"sv);
|
||||
print_to_stream(*stream_,
|
||||
static_cast<uint_least32_t>(decoder.codepoint),
|
||||
value_flags::format_as_hexadecimal,
|
||||
4);
|
||||
}
|
||||
}
|
||||
|
||||
// regular characters
|
||||
else
|
||||
print_to_stream(*stream_, cp_start, static_cast<size_t>(cp_end - cp_start));
|
||||
}
|
||||
}
|
||||
|
||||
cp_start = cp_end;
|
||||
}
|
||||
}
|
||||
|
||||
print_unformatted(multi_line ? R"(""")"sv : R"(")"sv);
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
void formatter::print(const value<std::string>& val)
|
||||
{
|
||||
print_string(val.get());
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
void formatter::print(const value<int64_t>& val)
|
||||
{
|
||||
naked_newline_ = false;
|
||||
|
||||
if (*val >= 0 && !!int_format_mask_)
|
||||
{
|
||||
static constexpr auto value_flags_mask =
|
||||
value_flags::format_as_binary | value_flags::format_as_octal | value_flags::format_as_hexadecimal;
|
||||
|
||||
const auto fmt = val.flags() & value_flags_mask;
|
||||
switch (fmt)
|
||||
{
|
||||
case value_flags::format_as_binary:
|
||||
if (!!(int_format_mask_ & format_flags::allow_binary_integers))
|
||||
{
|
||||
print_to_stream(*stream_, "0b"sv);
|
||||
print_to_stream(*stream_, *val, fmt);
|
||||
return;
|
||||
}
|
||||
break;
|
||||
|
||||
case value_flags::format_as_octal:
|
||||
if (!!(int_format_mask_ & format_flags::allow_octal_integers))
|
||||
{
|
||||
print_to_stream(*stream_, "0o"sv);
|
||||
print_to_stream(*stream_, *val, fmt);
|
||||
return;
|
||||
}
|
||||
break;
|
||||
|
||||
case value_flags::format_as_hexadecimal:
|
||||
if (!!(int_format_mask_ & format_flags::allow_hexadecimal_integers))
|
||||
{
|
||||
print_to_stream(*stream_, "0x"sv);
|
||||
print_to_stream(*stream_, *val, fmt);
|
||||
return;
|
||||
}
|
||||
break;
|
||||
|
||||
default: break;
|
||||
}
|
||||
}
|
||||
|
||||
// fallback to decimal
|
||||
print_to_stream(*stream_, *val);
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
void formatter::print(const value<double>& val)
|
||||
{
|
||||
const std::string_view* inf_nan = nullptr;
|
||||
switch (fpclassify(*val))
|
||||
{
|
||||
case fp_class::neg_inf: inf_nan = &constants_->float_neg_inf; break;
|
||||
case fp_class::pos_inf: inf_nan = &constants_->float_pos_inf; break;
|
||||
case fp_class::nan: inf_nan = &constants_->float_nan; break;
|
||||
case fp_class::ok:
|
||||
print_to_stream(*stream_,
|
||||
*val,
|
||||
value_flags::none,
|
||||
!!(config_.flags & format_flags::relaxed_float_precision));
|
||||
break;
|
||||
default: TOML_UNREACHABLE;
|
||||
}
|
||||
|
||||
if (inf_nan)
|
||||
{
|
||||
if (!!(config_.flags & format_flags::quote_infinities_and_nans))
|
||||
print_to_stream_bookended(*stream_, *inf_nan, '"');
|
||||
else
|
||||
print_to_stream(*stream_, *inf_nan);
|
||||
}
|
||||
|
||||
naked_newline_ = false;
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
void formatter::print(const value<bool>& val)
|
||||
{
|
||||
print_unformatted(*val ? constants_->bool_true : constants_->bool_false);
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
void formatter::print(const value<date>& val)
|
||||
{
|
||||
if (!!(config_.flags & format_flags::quote_dates_and_times))
|
||||
print_to_stream_bookended(*stream_, *val, literal_strings_allowed() ? '\'' : '"');
|
||||
else
|
||||
print_to_stream(*stream_, *val);
|
||||
naked_newline_ = false;
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
void formatter::print(const value<time>& val)
|
||||
{
|
||||
if (!!(config_.flags & format_flags::quote_dates_and_times))
|
||||
print_to_stream_bookended(*stream_, *val, literal_strings_allowed() ? '\'' : '"');
|
||||
else
|
||||
print_to_stream(*stream_, *val);
|
||||
naked_newline_ = false;
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
void formatter::print(const value<date_time>& val)
|
||||
{
|
||||
if (!!(config_.flags & format_flags::quote_dates_and_times))
|
||||
print_to_stream_bookended(*stream_, *val, literal_strings_allowed() ? '\'' : '"');
|
||||
else
|
||||
print_to_stream(*stream_, *val);
|
||||
naked_newline_ = false;
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
void formatter::print_value(const node& val_node, node_type type)
|
||||
{
|
||||
TOML_ASSUME(type > node_type::array);
|
||||
switch (type)
|
||||
{
|
||||
case node_type::string: print(*reinterpret_cast<const value<std::string>*>(&val_node)); break;
|
||||
case node_type::integer: print(*reinterpret_cast<const value<int64_t>*>(&val_node)); break;
|
||||
case node_type::floating_point: print(*reinterpret_cast<const value<double>*>(&val_node)); break;
|
||||
case node_type::boolean: print(*reinterpret_cast<const value<bool>*>(&val_node)); break;
|
||||
case node_type::date: print(*reinterpret_cast<const value<date>*>(&val_node)); break;
|
||||
case node_type::time: print(*reinterpret_cast<const value<time>*>(&val_node)); break;
|
||||
case node_type::date_time: print(*reinterpret_cast<const value<date_time>*>(&val_node)); break;
|
||||
default: TOML_UNREACHABLE;
|
||||
}
|
||||
}
|
||||
|
||||
#if TOML_ENABLE_PARSER && !TOML_EXCEPTIONS
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
bool formatter::dump_failed_parse_result()
|
||||
{
|
||||
if (result_ && !(*result_))
|
||||
{
|
||||
stream() << result_->error();
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
#else
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
TOML_ATTR(const)
|
||||
bool formatter::dump_failed_parse_result()
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
#endif
|
||||
}
|
||||
TOML_IMPL_NAMESPACE_END;
|
||||
|
||||
#include "header_end.hpp"
|
||||
#endif // TOML_ENABLE_FORMATTERS
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,13 @@
|
||||
//# {{
|
||||
#ifdef __INTELLISENSE__
|
||||
#include "preprocessor.hpp"
|
||||
#endif
|
||||
//# }}
|
||||
#ifdef _MSC_VER
|
||||
#pragma pop_macro("min")
|
||||
#pragma pop_macro("max")
|
||||
#ifndef __clang__
|
||||
#pragma inline_recursion(off)
|
||||
#endif
|
||||
#endif
|
||||
TOML_POP_WARNINGS;
|
||||
@@ -0,0 +1,15 @@
|
||||
//# {{
|
||||
#ifdef __INTELLISENSE__
|
||||
#include "preprocessor.hpp"
|
||||
#endif
|
||||
//# }}
|
||||
TOML_PUSH_WARNINGS;
|
||||
#ifdef _MSC_VER
|
||||
#ifndef __clang__
|
||||
#pragma inline_recursion(on)
|
||||
#endif
|
||||
#pragma push_macro("min")
|
||||
#pragma push_macro("max")
|
||||
#undef min
|
||||
#undef max
|
||||
#endif
|
||||
@@ -0,0 +1,142 @@
|
||||
//# This file is a part of toml++ and is subject to the the terms of the MIT license.
|
||||
//# Copyright (c) Mark Gillard <mark.gillard@outlook.com.au>
|
||||
//# See https://github.com/marzer/tomlplusplus/blob/master/LICENSE for the full license text.
|
||||
// SPDX-License-Identifier: MIT
|
||||
#pragma once
|
||||
|
||||
#include "preprocessor.hpp"
|
||||
#if TOML_ENABLE_FORMATTERS
|
||||
|
||||
#include "formatter.hpp"
|
||||
#include "header_start.hpp"
|
||||
|
||||
TOML_NAMESPACE_START
|
||||
{
|
||||
/// \brief A wrapper for printing TOML objects out to a stream as formatted JSON.
|
||||
///
|
||||
/// \availability This class is only available when #TOML_ENABLE_FORMATTERS is enabled.
|
||||
///
|
||||
/// \detail \cpp
|
||||
/// auto some_toml = toml::parse(R"(
|
||||
/// [fruit]
|
||||
/// apple.color = "red"
|
||||
/// apple.taste.sweet = true
|
||||
///
|
||||
/// [fruit.apple.texture]
|
||||
/// smooth = true
|
||||
/// )"sv);
|
||||
/// std::cout << toml::json_formatter{ some_toml } << "\n";
|
||||
/// \ecpp
|
||||
///
|
||||
/// \out
|
||||
/// {
|
||||
/// "fruit" : {
|
||||
/// "apple" : {
|
||||
/// "color" : "red",
|
||||
/// "taste" : {
|
||||
/// "sweet" : true
|
||||
/// },
|
||||
/// "texture" : {
|
||||
/// "smooth" : true
|
||||
/// }
|
||||
/// }
|
||||
/// }
|
||||
/// }
|
||||
/// \eout
|
||||
class TOML_EXPORTED_CLASS json_formatter : impl::formatter
|
||||
{
|
||||
private:
|
||||
/// \cond
|
||||
|
||||
using base = impl::formatter;
|
||||
|
||||
TOML_EXPORTED_MEMBER_FUNCTION
|
||||
void print(const toml::table&);
|
||||
|
||||
TOML_EXPORTED_MEMBER_FUNCTION
|
||||
void print(const toml::array&);
|
||||
|
||||
TOML_EXPORTED_MEMBER_FUNCTION
|
||||
void print();
|
||||
|
||||
static constexpr impl::formatter_constants constants = {
|
||||
format_flags::quote_dates_and_times, // mandatory
|
||||
format_flags::allow_literal_strings | format_flags::allow_multi_line_strings, // ignored
|
||||
"Infinity"sv,
|
||||
"-Infinity"sv,
|
||||
"NaN"sv,
|
||||
"true"sv,
|
||||
"false"sv
|
||||
};
|
||||
|
||||
/// \endcond
|
||||
|
||||
public:
|
||||
/// \brief The default flags for a json_formatter.
|
||||
static constexpr format_flags default_flags = constants.mandatory_flags //
|
||||
| format_flags::quote_infinities_and_nans //
|
||||
| format_flags::allow_unicode_strings //
|
||||
| format_flags::indentation;
|
||||
|
||||
/// \brief Constructs a JSON formatter and binds it to a TOML object.
|
||||
///
|
||||
/// \param source The source TOML object.
|
||||
/// \param flags Format option flags.
|
||||
TOML_NODISCARD_CTOR
|
||||
explicit json_formatter(const toml::node& source, format_flags flags = default_flags) noexcept
|
||||
: base{ &source, nullptr, constants, { flags, " "sv } }
|
||||
{}
|
||||
|
||||
#if TOML_DOXYGEN || (TOML_ENABLE_PARSER && !TOML_EXCEPTIONS)
|
||||
|
||||
/// \brief Constructs a JSON formatter and binds it to a toml::parse_result.
|
||||
///
|
||||
/// \availability This constructor is only available when exceptions are disabled.
|
||||
///
|
||||
/// \attention Formatting a failed parse result will simply dump the error message out as-is.
|
||||
/// This will not be valid JSON, but at least gives you something to log or show up in diagnostics:
|
||||
/// \cpp
|
||||
/// std::cout << toml::json_formatter{ toml::parse("a = 'b'"sv) } // ok
|
||||
/// << "\n\n"
|
||||
/// << toml::json_formatter{ toml::parse("a = "sv) } // malformed
|
||||
/// << "\n";
|
||||
/// \ecpp
|
||||
/// \out
|
||||
/// {
|
||||
/// "a" : "b"
|
||||
/// }
|
||||
///
|
||||
/// Error while parsing key-value pair: encountered end-of-file
|
||||
/// (error occurred at line 1, column 5)
|
||||
/// \eout
|
||||
/// Use the library with exceptions if you want to avoid this scenario.
|
||||
///
|
||||
/// \param result The parse result.
|
||||
/// \param flags Format option flags.
|
||||
TOML_NODISCARD_CTOR
|
||||
explicit json_formatter(const toml::parse_result& result, format_flags flags = default_flags) noexcept
|
||||
: base{ nullptr, &result, constants, { flags, " "sv } }
|
||||
{}
|
||||
|
||||
#endif
|
||||
|
||||
/// \brief Prints the bound TOML object out to the stream as JSON.
|
||||
friend std::ostream& operator<<(std::ostream& lhs, json_formatter& rhs)
|
||||
{
|
||||
rhs.attach(lhs);
|
||||
rhs.print();
|
||||
rhs.detach();
|
||||
return lhs;
|
||||
}
|
||||
|
||||
/// \brief Prints the bound TOML object out to the stream as JSON (rvalue overload).
|
||||
friend std::ostream& operator<<(std::ostream& lhs, json_formatter&& rhs)
|
||||
{
|
||||
return lhs << rhs; // as lvalue
|
||||
}
|
||||
};
|
||||
}
|
||||
TOML_NAMESPACE_END;
|
||||
|
||||
#include "header_end.hpp"
|
||||
#endif // TOML_ENABLE_FORMATTERS
|
||||
@@ -0,0 +1,121 @@
|
||||
//# This file is a part of toml++ and is subject to the the terms of the MIT license.
|
||||
//# Copyright (c) Mark Gillard <mark.gillard@outlook.com.au>
|
||||
//# See https://github.com/marzer/tomlplusplus/blob/master/LICENSE for the full license text.
|
||||
// SPDX-License-Identifier: MIT
|
||||
#pragma once
|
||||
|
||||
#include "preprocessor.hpp"
|
||||
//# {{
|
||||
#if !TOML_IMPLEMENTATION
|
||||
#error This is an implementation-only header.
|
||||
#endif
|
||||
//# }}
|
||||
#if TOML_ENABLE_FORMATTERS
|
||||
|
||||
#include "json_formatter.hpp"
|
||||
#include "print_to_stream.hpp"
|
||||
#include "table.hpp"
|
||||
#include "array.hpp"
|
||||
#include "header_start.hpp"
|
||||
|
||||
TOML_NAMESPACE_START
|
||||
{
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
void json_formatter::print(const toml::table& tbl)
|
||||
{
|
||||
if (tbl.empty())
|
||||
{
|
||||
print_unformatted("{}"sv);
|
||||
return;
|
||||
}
|
||||
|
||||
print_unformatted('{');
|
||||
|
||||
if (indent_sub_tables())
|
||||
increase_indent();
|
||||
bool first = false;
|
||||
for (auto&& [k, v] : tbl)
|
||||
{
|
||||
if (first)
|
||||
print_unformatted(',');
|
||||
first = true;
|
||||
print_newline(true);
|
||||
print_indent();
|
||||
|
||||
print_string(k.str(), false);
|
||||
if (terse_kvps())
|
||||
print_unformatted(":"sv);
|
||||
else
|
||||
print_unformatted(" : "sv);
|
||||
|
||||
const auto type = v.type();
|
||||
TOML_ASSUME(type != node_type::none);
|
||||
switch (type)
|
||||
{
|
||||
case node_type::table: print(*reinterpret_cast<const table*>(&v)); break;
|
||||
case node_type::array: print(*reinterpret_cast<const array*>(&v)); break;
|
||||
default: print_value(v, type);
|
||||
}
|
||||
}
|
||||
if (indent_sub_tables())
|
||||
decrease_indent();
|
||||
print_newline(true);
|
||||
print_indent();
|
||||
|
||||
print_unformatted('}');
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
void json_formatter::print(const toml::array& arr)
|
||||
{
|
||||
if (arr.empty())
|
||||
{
|
||||
print_unformatted("[]"sv);
|
||||
return;
|
||||
}
|
||||
|
||||
print_unformatted('[');
|
||||
if (indent_array_elements())
|
||||
increase_indent();
|
||||
for (size_t i = 0; i < arr.size(); i++)
|
||||
{
|
||||
if (i > 0u)
|
||||
print_unformatted(',');
|
||||
print_newline(true);
|
||||
print_indent();
|
||||
|
||||
auto& v = arr[i];
|
||||
const auto type = v.type();
|
||||
TOML_ASSUME(type != node_type::none);
|
||||
switch (type)
|
||||
{
|
||||
case node_type::table: print(*reinterpret_cast<const table*>(&v)); break;
|
||||
case node_type::array: print(*reinterpret_cast<const array*>(&v)); break;
|
||||
default: print_value(v, type);
|
||||
}
|
||||
}
|
||||
if (indent_array_elements())
|
||||
decrease_indent();
|
||||
print_newline(true);
|
||||
print_indent();
|
||||
print_unformatted(']');
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
void json_formatter::print()
|
||||
{
|
||||
if (dump_failed_parse_result())
|
||||
return;
|
||||
|
||||
switch (auto source_type = source().type())
|
||||
{
|
||||
case node_type::table: print(*reinterpret_cast<const table*>(&source())); break;
|
||||
case node_type::array: print(*reinterpret_cast<const array*>(&source())); break;
|
||||
default: print_value(source(), source_type);
|
||||
}
|
||||
}
|
||||
}
|
||||
TOML_NAMESPACE_END;
|
||||
|
||||
#include "header_end.hpp"
|
||||
#endif // TOML_ENABLE_FORMATTERS
|
||||
@@ -0,0 +1,335 @@
|
||||
//# This file is a part of toml++ and is subject to the the terms of the MIT license.
|
||||
//# Copyright (c) Mark Gillard <mark.gillard@outlook.com.au>
|
||||
//# See https://github.com/marzer/tomlplusplus/blob/master/LICENSE for the full license text.
|
||||
// SPDX-License-Identifier: MIT
|
||||
#pragma once
|
||||
|
||||
#include "source_region.hpp"
|
||||
#include "std_utility.hpp"
|
||||
#include "print_to_stream.hpp"
|
||||
#include "header_start.hpp"
|
||||
|
||||
TOML_NAMESPACE_START
|
||||
{
|
||||
/// \brief A key parsed from a TOML document.
|
||||
///
|
||||
/// \detail These are used as the internal keys for a toml::table: \cpp
|
||||
/// const toml::table tbl = R"(
|
||||
/// a = 1
|
||||
/// b = 2
|
||||
/// c = 3
|
||||
/// )"_toml;
|
||||
///
|
||||
/// for (auto&& [k, v] : tbl)
|
||||
/// std::cout << "key '"sv << k << "' defined at "sv << k.source() << "\n";
|
||||
/// \ecpp
|
||||
/// \out
|
||||
/// key 'a' defined at line 2, column 5
|
||||
/// key 'b' defined at line 3, column 7
|
||||
/// key 'c' defined at line 4, column 9
|
||||
/// \eout
|
||||
class key
|
||||
{
|
||||
private:
|
||||
std::string key_;
|
||||
source_region source_;
|
||||
|
||||
public:
|
||||
/// \brief Default constructor.
|
||||
TOML_NODISCARD_CTOR
|
||||
key() noexcept = default;
|
||||
|
||||
/// \brief Constructs a key from a string view and source region.
|
||||
TOML_NODISCARD_CTOR
|
||||
explicit key(std::string_view k, source_region&& src = {}) //
|
||||
: key_{ k },
|
||||
source_{ std::move(src) }
|
||||
{}
|
||||
|
||||
/// \brief Constructs a key from a string view and source region.
|
||||
TOML_NODISCARD_CTOR
|
||||
explicit key(std::string_view k, const source_region& src) //
|
||||
: key_{ k },
|
||||
source_{ src }
|
||||
{}
|
||||
|
||||
/// \brief Constructs a key from a string and source region.
|
||||
TOML_NODISCARD_CTOR
|
||||
explicit key(std::string&& k, source_region&& src = {}) noexcept //
|
||||
: key_{ std::move(k) },
|
||||
source_{ std::move(src) }
|
||||
{}
|
||||
|
||||
/// \brief Constructs a key from a string and source region.
|
||||
TOML_NODISCARD_CTOR
|
||||
explicit key(std::string&& k, const source_region& src) noexcept //
|
||||
: key_{ std::move(k) },
|
||||
source_{ src }
|
||||
{}
|
||||
|
||||
/// \brief Constructs a key from a c-string and source region.
|
||||
TOML_NODISCARD_CTOR
|
||||
explicit key(const char* k, source_region&& src = {}) //
|
||||
: key_{ k },
|
||||
source_{ std::move(src) }
|
||||
{}
|
||||
|
||||
/// \brief Constructs a key from a c-string view and source region.
|
||||
TOML_NODISCARD_CTOR
|
||||
explicit key(const char* k, const source_region& src) //
|
||||
: key_{ k },
|
||||
source_{ src }
|
||||
{}
|
||||
|
||||
#if TOML_ENABLE_WINDOWS_COMPAT
|
||||
|
||||
/// \brief Constructs a key from a wide string view and source region.
|
||||
///
|
||||
/// \availability This constructor is only available when #TOML_ENABLE_WINDOWS_COMPAT is enabled.
|
||||
TOML_NODISCARD_CTOR
|
||||
explicit key(std::wstring_view k, source_region&& src = {}) //
|
||||
: key_{ impl::narrow(k) },
|
||||
source_{ std::move(src) }
|
||||
{}
|
||||
|
||||
/// \brief Constructs a key from a wide string and source region.
|
||||
///
|
||||
/// \availability This constructor is only available when #TOML_ENABLE_WINDOWS_COMPAT is enabled.
|
||||
TOML_NODISCARD_CTOR
|
||||
explicit key(std::wstring_view k, const source_region& src) //
|
||||
: key_{ impl::narrow(k) },
|
||||
source_{ src }
|
||||
{}
|
||||
|
||||
#endif
|
||||
|
||||
/// \name String operations
|
||||
/// @{
|
||||
|
||||
/// \brief Returns a view of the key's underlying string.
|
||||
TOML_PURE_INLINE_GETTER
|
||||
std::string_view str() const noexcept
|
||||
{
|
||||
return std::string_view{ key_ };
|
||||
}
|
||||
|
||||
/// \brief Returns a view of the key's underlying string.
|
||||
TOML_PURE_INLINE_GETTER
|
||||
/*implicit*/ operator std::string_view() const noexcept
|
||||
{
|
||||
return str();
|
||||
}
|
||||
|
||||
/// \brief Returns true if the key's underlying string is empty.
|
||||
TOML_PURE_INLINE_GETTER
|
||||
bool empty() const noexcept
|
||||
{
|
||||
return key_.empty();
|
||||
}
|
||||
|
||||
/// \brief Returns a pointer to the start of the key's underlying string.
|
||||
TOML_PURE_INLINE_GETTER
|
||||
const char* data() const noexcept
|
||||
{
|
||||
return key_.data();
|
||||
}
|
||||
|
||||
/// \brief Returns the length of the key's underlying string.
|
||||
TOML_PURE_INLINE_GETTER
|
||||
size_t length() const noexcept
|
||||
{
|
||||
return key_.length();
|
||||
}
|
||||
|
||||
/// @}
|
||||
|
||||
/// \name Metadata
|
||||
/// @{
|
||||
|
||||
/// \brief Returns the source region responsible for specifying this key during parsing.
|
||||
TOML_PURE_INLINE_GETTER
|
||||
const source_region& source() const noexcept
|
||||
{
|
||||
return source_;
|
||||
}
|
||||
|
||||
/// @}
|
||||
|
||||
/// \name Equality and Comparison
|
||||
/// \attention These operations only compare the underlying strings; source regions are ignored for the purposes of all comparison!
|
||||
/// @{
|
||||
|
||||
/// \brief Returns true if `lhs.str() == rhs.str()`.
|
||||
TOML_PURE_INLINE_GETTER
|
||||
friend bool operator==(const key& lhs, const key& rhs) noexcept
|
||||
{
|
||||
return lhs.key_ == rhs.key_;
|
||||
}
|
||||
|
||||
/// \brief Returns true if `lhs.str() != rhs.str()`.
|
||||
TOML_PURE_INLINE_GETTER
|
||||
friend bool operator!=(const key& lhs, const key& rhs) noexcept
|
||||
{
|
||||
return lhs.key_ != rhs.key_;
|
||||
}
|
||||
|
||||
/// \brief Returns true if `lhs.str() < rhs.str()`.
|
||||
TOML_PURE_INLINE_GETTER
|
||||
friend bool operator<(const key& lhs, const key& rhs) noexcept
|
||||
{
|
||||
return lhs.key_ < rhs.key_;
|
||||
}
|
||||
|
||||
/// \brief Returns true if `lhs.str() <= rhs.str()`.
|
||||
TOML_PURE_INLINE_GETTER
|
||||
friend bool operator<=(const key& lhs, const key& rhs) noexcept
|
||||
{
|
||||
return lhs.key_ <= rhs.key_;
|
||||
}
|
||||
|
||||
/// \brief Returns true if `lhs.str() > rhs.str()`.
|
||||
TOML_PURE_INLINE_GETTER
|
||||
friend bool operator>(const key& lhs, const key& rhs) noexcept
|
||||
{
|
||||
return lhs.key_ > rhs.key_;
|
||||
}
|
||||
|
||||
/// \brief Returns true if `lhs.str() >= rhs.str()`.
|
||||
TOML_PURE_INLINE_GETTER
|
||||
friend bool operator>=(const key& lhs, const key& rhs) noexcept
|
||||
{
|
||||
return lhs.key_ >= rhs.key_;
|
||||
}
|
||||
|
||||
/// \brief Returns true if `lhs.str() == rhs`.
|
||||
TOML_PURE_INLINE_GETTER
|
||||
friend bool operator==(const key& lhs, std::string_view rhs) noexcept
|
||||
{
|
||||
return lhs.key_ == rhs;
|
||||
}
|
||||
|
||||
/// \brief Returns true if `lhs.str() != rhs`.
|
||||
TOML_PURE_INLINE_GETTER
|
||||
friend bool operator!=(const key& lhs, std::string_view rhs) noexcept
|
||||
{
|
||||
return lhs.key_ != rhs;
|
||||
}
|
||||
|
||||
/// \brief Returns true if `lhs.str() < rhs`.
|
||||
TOML_PURE_INLINE_GETTER
|
||||
friend bool operator<(const key& lhs, std::string_view rhs) noexcept
|
||||
{
|
||||
return lhs.key_ < rhs;
|
||||
}
|
||||
|
||||
/// \brief Returns true if `lhs.str() <= rhs`.
|
||||
TOML_PURE_INLINE_GETTER
|
||||
friend bool operator<=(const key& lhs, std::string_view rhs) noexcept
|
||||
{
|
||||
return lhs.key_ <= rhs;
|
||||
}
|
||||
|
||||
/// \brief Returns true if `lhs.str() > rhs`.
|
||||
TOML_PURE_INLINE_GETTER
|
||||
friend bool operator>(const key& lhs, std::string_view rhs) noexcept
|
||||
{
|
||||
return lhs.key_ > rhs;
|
||||
}
|
||||
|
||||
/// \brief Returns true if `lhs.str() >= rhs`.
|
||||
TOML_PURE_INLINE_GETTER
|
||||
friend bool operator>=(const key& lhs, std::string_view rhs) noexcept
|
||||
{
|
||||
return lhs.key_ >= rhs;
|
||||
}
|
||||
|
||||
/// \brief Returns true if `lhs == rhs.str()`.
|
||||
TOML_PURE_INLINE_GETTER
|
||||
friend bool operator==(std::string_view lhs, const key& rhs) noexcept
|
||||
{
|
||||
return lhs == rhs.key_;
|
||||
}
|
||||
|
||||
/// \brief Returns true if `lhs != rhs.str()`.
|
||||
TOML_PURE_INLINE_GETTER
|
||||
friend bool operator!=(std::string_view lhs, const key& rhs) noexcept
|
||||
{
|
||||
return lhs != rhs.key_;
|
||||
}
|
||||
|
||||
/// \brief Returns true if `lhs < rhs.str()`.
|
||||
TOML_PURE_INLINE_GETTER
|
||||
friend bool operator<(std::string_view lhs, const key& rhs) noexcept
|
||||
{
|
||||
return lhs < rhs.key_;
|
||||
}
|
||||
|
||||
/// \brief Returns true if `lhs <= rhs.str()`.
|
||||
TOML_PURE_INLINE_GETTER
|
||||
friend bool operator<=(std::string_view lhs, const key& rhs) noexcept
|
||||
{
|
||||
return lhs <= rhs.key_;
|
||||
}
|
||||
|
||||
/// \brief Returns true if `lhs > rhs.str()`.
|
||||
TOML_PURE_INLINE_GETTER
|
||||
friend bool operator>(std::string_view lhs, const key& rhs) noexcept
|
||||
{
|
||||
return lhs > rhs.key_;
|
||||
}
|
||||
|
||||
/// \brief Returns true if `lhs >= rhs.str()`.
|
||||
TOML_PURE_INLINE_GETTER
|
||||
friend bool operator>=(std::string_view lhs, const key& rhs) noexcept
|
||||
{
|
||||
return lhs >= rhs.key_;
|
||||
}
|
||||
|
||||
/// @}
|
||||
|
||||
/// \name Iteration
|
||||
/// @{
|
||||
|
||||
/// \brief A const iterator for iterating over the characters in the key.
|
||||
using const_iterator = const char*;
|
||||
|
||||
/// \brief A const iterator for iterating over the characters in the key.
|
||||
using iterator = const_iterator;
|
||||
|
||||
/// \brief Returns an iterator to the first character in the key's backing string.
|
||||
TOML_PURE_INLINE_GETTER
|
||||
const_iterator begin() const noexcept
|
||||
{
|
||||
return key_.data();
|
||||
}
|
||||
|
||||
/// \brief Returns an iterator to one-past-the-last character in the key's backing string.
|
||||
TOML_PURE_INLINE_GETTER
|
||||
const_iterator end() const noexcept
|
||||
{
|
||||
return key_.data() + key_.length();
|
||||
}
|
||||
|
||||
/// @}
|
||||
|
||||
/// \brief Prints the key's underlying string out to the stream.
|
||||
friend std::ostream& operator<<(std::ostream& lhs, const key& rhs)
|
||||
{
|
||||
impl::print_to_stream(lhs, rhs.key_);
|
||||
return lhs;
|
||||
}
|
||||
};
|
||||
|
||||
/// \brief Metafunction for determining if a type is, or is a reference to, a toml::key.
|
||||
template <typename T>
|
||||
inline constexpr bool is_key = std::is_same_v<impl::remove_cvref<T>, toml::key>;
|
||||
|
||||
/// \brief Metafunction for determining if a type is, or is a reference to, a toml::key,
|
||||
/// or is implicitly or explicitly convertible to one.
|
||||
template <typename T>
|
||||
inline constexpr bool is_key_or_convertible = is_key<T> //
|
||||
|| impl::is_constructible_or_convertible<toml::key, T>;
|
||||
}
|
||||
TOML_NAMESPACE_END;
|
||||
|
||||
#include "header_end.hpp"
|
||||
@@ -0,0 +1,182 @@
|
||||
//# This file is a part of toml++ and is subject to the the terms of the MIT license.
|
||||
//# Copyright (c) Mark Gillard <mark.gillard@outlook.com.au>
|
||||
//# See https://github.com/marzer/tomlplusplus/blob/master/LICENSE for the full license text.
|
||||
// SPDX-License-Identifier: MIT
|
||||
#pragma once
|
||||
|
||||
#include "forward_declarations.hpp"
|
||||
#include "header_start.hpp"
|
||||
|
||||
/// \cond
|
||||
TOML_IMPL_NAMESPACE_START
|
||||
{
|
||||
template <typename T>
|
||||
TOML_NODISCARD
|
||||
TOML_ATTR(returns_nonnull)
|
||||
auto* make_node_impl_specialized(T && val, [[maybe_unused]] value_flags flags)
|
||||
{
|
||||
using unwrapped_type = unwrap_node<remove_cvref<T>>;
|
||||
static_assert(!std::is_same_v<unwrapped_type, node>);
|
||||
static_assert(!is_node_view<unwrapped_type>);
|
||||
|
||||
// arrays + tables - invoke copy/move ctor
|
||||
if constexpr (is_one_of<unwrapped_type, array, table>)
|
||||
{
|
||||
return new unwrapped_type(static_cast<T&&>(val));
|
||||
}
|
||||
|
||||
// values
|
||||
else
|
||||
{
|
||||
using native_type = native_type_of<unwrapped_type>;
|
||||
using value_type = value<native_type>;
|
||||
|
||||
value_type* out;
|
||||
|
||||
// copy/move ctor
|
||||
if constexpr (std::is_same_v<remove_cvref<T>, value_type>)
|
||||
{
|
||||
out = new value_type{ static_cast<T&&>(val), flags };
|
||||
}
|
||||
|
||||
// creating from raw value
|
||||
else
|
||||
{
|
||||
static_assert(!is_wide_string<T> || TOML_ENABLE_WINDOWS_COMPAT,
|
||||
"Instantiating values from wide-character strings is only "
|
||||
"supported on Windows with TOML_ENABLE_WINDOWS_COMPAT enabled.");
|
||||
|
||||
if constexpr (!is_losslessly_convertible_to_native<unwrapped_type>)
|
||||
{
|
||||
if constexpr (std::is_same_v<native_type, int64_t>)
|
||||
static_assert(always_false<T>,
|
||||
"Integral value initializers must be losslessly convertible to int64_t");
|
||||
else if constexpr (std::is_same_v<native_type, double>)
|
||||
static_assert(always_false<T>,
|
||||
"Floating-point value initializers must be losslessly convertible to double");
|
||||
else
|
||||
static_assert(
|
||||
always_false<T>,
|
||||
"Value initializers must be losslessly convertible to one of the TOML value types");
|
||||
}
|
||||
|
||||
if constexpr (is_wide_string<T>)
|
||||
{
|
||||
#if TOML_ENABLE_WINDOWS_COMPAT
|
||||
out = new value_type{ narrow(static_cast<T&&>(val)) };
|
||||
#else
|
||||
static_assert(always_false<T>, "Evaluated unreachable branch!");
|
||||
#endif
|
||||
}
|
||||
else
|
||||
out = new value_type{ static_cast<T&&>(val) };
|
||||
|
||||
if (flags != preserve_source_value_flags)
|
||||
out->flags(flags);
|
||||
}
|
||||
|
||||
return out;
|
||||
}
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
TOML_NODISCARD
|
||||
auto* make_node_impl(T && val, value_flags flags = preserve_source_value_flags)
|
||||
{
|
||||
using unwrapped_type = unwrap_node<remove_cvref<T>>;
|
||||
if constexpr (std::is_same_v<unwrapped_type, node> || is_node_view<unwrapped_type>)
|
||||
{
|
||||
if constexpr (is_node_view<unwrapped_type>)
|
||||
{
|
||||
if (!val)
|
||||
return static_cast<toml::node*>(nullptr);
|
||||
}
|
||||
|
||||
return static_cast<T&&>(val).visit(
|
||||
[flags](auto&& concrete) {
|
||||
return static_cast<toml::node*>(
|
||||
make_node_impl_specialized(static_cast<decltype(concrete)&&>(concrete), flags));
|
||||
});
|
||||
}
|
||||
else
|
||||
return make_node_impl_specialized(static_cast<T&&>(val), flags);
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
TOML_NODISCARD
|
||||
auto* make_node_impl(inserter<T> && val, value_flags flags = preserve_source_value_flags)
|
||||
{
|
||||
return make_node_impl(static_cast<T&&>(val.value), flags);
|
||||
}
|
||||
|
||||
template <typename T, bool = (is_node<T> || is_node_view<T> || is_value<T> || can_partially_represent_native<T>)>
|
||||
struct inserted_type_of_
|
||||
{
|
||||
using type = std::remove_pointer_t<decltype(make_node_impl(std::declval<T>()))>;
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
struct inserted_type_of_<inserter<T>, false>
|
||||
{
|
||||
using type = typename inserted_type_of_<remove_cvref<T>>::type;
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
struct inserted_type_of_<T, false>
|
||||
{
|
||||
using type = void;
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
TOML_NODISCARD
|
||||
node_ptr make_node(T && val, value_flags flags = preserve_source_value_flags)
|
||||
{
|
||||
return node_ptr{ make_node_impl(static_cast<T&&>(val), flags) };
|
||||
}
|
||||
|
||||
template <typename... T>
|
||||
struct emplaced_type_of_
|
||||
{
|
||||
using type = void;
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
struct emplaced_type_of_<T>
|
||||
{
|
||||
using type = std::conditional_t<is_one_of<T, node, node_view<node>, node_view<const node>>,
|
||||
void,
|
||||
typename inserted_type_of_<T>::type>;
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
struct emplaced_type_of_<inserter<T>>
|
||||
{
|
||||
using type = typename emplaced_type_of_<remove_cvref<T>>::type;
|
||||
};
|
||||
|
||||
template <typename... T>
|
||||
using emplaced_type_of = typename emplaced_type_of_<remove_cvref<T>...>::type;
|
||||
}
|
||||
TOML_IMPL_NAMESPACE_END;
|
||||
/// \endcond
|
||||
|
||||
TOML_NAMESPACE_START
|
||||
{
|
||||
/// \brief Metafunction for determining which node type would be constructed
|
||||
/// if an object of this type was inserted into a toml::table or toml::array.
|
||||
///
|
||||
/// \detail \cpp
|
||||
/// static_assert(std::is_same_v<toml::inserted_type_of<const char*>, toml::value<std::string>);
|
||||
/// static_assert(std::is_same_v<toml::inserted_type_of<int>, toml::value<int64_t>);
|
||||
/// static_assert(std::is_same_v<toml::inserted_type_of<float>, toml::value<double>);
|
||||
/// static_assert(std::is_same_v<toml::inserted_type_of<bool>, toml::value<bool>);
|
||||
/// \ecpp
|
||||
///
|
||||
/// \note This will return toml::node for nodes and node_views, even though a more specific node subclass
|
||||
/// would actually be inserted. There is no way around this in a compile-time metafunction.
|
||||
template <typename T>
|
||||
using inserted_type_of = POXY_IMPLEMENTATION_DETAIL(typename impl::inserted_type_of_<impl::remove_cvref<T>>::type);
|
||||
}
|
||||
TOML_NAMESPACE_END;
|
||||
|
||||
#include "header_end.hpp"
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,141 @@
|
||||
//# This file is a part of toml++ and is subject to the the terms of the MIT license.
|
||||
//# Copyright (c) Mark Gillard <mark.gillard@outlook.com.au>
|
||||
//# See https://github.com/marzer/tomlplusplus/blob/master/LICENSE for the full license text.
|
||||
// SPDX-License-Identifier: MIT
|
||||
#pragma once
|
||||
|
||||
//# {{
|
||||
#include "preprocessor.hpp"
|
||||
#if !TOML_IMPLEMENTATION
|
||||
#error This is an implementation-only header.
|
||||
#endif
|
||||
//# }}
|
||||
|
||||
#include "node.hpp"
|
||||
#include "node_view.hpp"
|
||||
#include "at_path.hpp"
|
||||
#include "table.hpp"
|
||||
#include "array.hpp"
|
||||
#include "value.hpp"
|
||||
#include "header_start.hpp"
|
||||
|
||||
TOML_NAMESPACE_START
|
||||
{
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
node::node() noexcept = default;
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
node::~node() noexcept = default;
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
node::node(node && other) noexcept //
|
||||
: source_{ std::exchange(other.source_, {}) }
|
||||
{}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
node::node(const node& /*other*/) noexcept
|
||||
{
|
||||
// does not copy source information - this is not an error
|
||||
//
|
||||
// see https://github.com/marzer/tomlplusplus/issues/49#issuecomment-665089577
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
node& node::operator=(const node& /*rhs*/) noexcept
|
||||
{
|
||||
// does not copy source information - this is not an error
|
||||
//
|
||||
// see https://github.com/marzer/tomlplusplus/issues/49#issuecomment-665089577
|
||||
|
||||
source_ = {};
|
||||
return *this;
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
node& node::operator=(node&& rhs) noexcept
|
||||
{
|
||||
if (&rhs != this)
|
||||
source_ = std::exchange(rhs.source_, {});
|
||||
return *this;
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
node_view<node> node::at_path(std::string_view path) noexcept
|
||||
{
|
||||
return toml::at_path(*this, path);
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
node_view<const node> node::at_path(std::string_view path) const noexcept
|
||||
{
|
||||
return toml::at_path(*this, path);
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
node_view<node> node::at_path(const path& p) noexcept
|
||||
{
|
||||
return toml::at_path(*this, p);
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
node_view<const node> node::at_path(const path& p) const noexcept
|
||||
{
|
||||
return toml::at_path(*this, p);
|
||||
}
|
||||
|
||||
#if TOML_ENABLE_WINDOWS_COMPAT
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
node_view<node> node::at_path(std::wstring_view path)
|
||||
{
|
||||
return toml::at_path(*this, path);
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
node_view<const node> node::at_path(std::wstring_view path) const
|
||||
{
|
||||
return toml::at_path(*this, path);
|
||||
}
|
||||
|
||||
#endif // TOML_ENABLE_WINDOWS_COMPAT
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
node_view<node> node::operator[](const path& p) noexcept
|
||||
{
|
||||
return toml::at_path(*this, p);
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
node_view<const node> node::operator[](const path& p) const noexcept
|
||||
{
|
||||
return toml::at_path(*this, p);
|
||||
}
|
||||
}
|
||||
TOML_NAMESPACE_END;
|
||||
|
||||
TOML_IMPL_NAMESPACE_START
|
||||
{
|
||||
TOML_PURE_GETTER
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
bool TOML_CALLCONV node_deep_equality(const node* lhs, const node* rhs) noexcept
|
||||
{
|
||||
// both same or both null
|
||||
if (lhs == rhs)
|
||||
return true;
|
||||
|
||||
// lhs null != rhs null or different types
|
||||
if ((!lhs != !rhs) || lhs->type() != rhs->type())
|
||||
return false;
|
||||
|
||||
return lhs->visit(
|
||||
[=](auto& l) noexcept
|
||||
{
|
||||
using concrete_type = remove_cvref<decltype(l)>;
|
||||
|
||||
return l == *(rhs->as<concrete_type>());
|
||||
});
|
||||
}
|
||||
}
|
||||
TOML_IMPL_NAMESPACE_END;
|
||||
|
||||
#include "header_end.hpp"
|
||||
@@ -0,0 +1,839 @@
|
||||
//# This file is a part of toml++ and is subject to the the terms of the MIT license.
|
||||
//# Copyright (c) Mark Gillard <mark.gillard@outlook.com.au>
|
||||
//# See https://github.com/marzer/tomlplusplus/blob/master/LICENSE for the full license text.
|
||||
// SPDX-License-Identifier: MIT
|
||||
#pragma once
|
||||
|
||||
#include "std_vector.hpp"
|
||||
#include "std_initializer_list.hpp"
|
||||
#include "print_to_stream.hpp"
|
||||
#include "node.hpp"
|
||||
#include "header_start.hpp"
|
||||
TOML_DISABLE_ARITHMETIC_WARNINGS;
|
||||
|
||||
TOML_NAMESPACE_START
|
||||
{
|
||||
/// \brief A view of a node.
|
||||
///
|
||||
/// \detail A node_view is like a std::optional<toml::node&> (if such a construct were legal), with lots of
|
||||
/// toml-specific stuff built-in. It _may_ represent a node, and allows you to do many of the
|
||||
/// same operations that you'd do on nodes directly, as well as easily traversing the node tree by creating
|
||||
/// subviews (via node_view::operator[]). \cpp
|
||||
///
|
||||
/// auto tbl = toml::parse(R"(
|
||||
///
|
||||
/// title = "my hardware store"
|
||||
///
|
||||
/// [[products]]
|
||||
/// name = "Hammer"
|
||||
/// sku = 738594937
|
||||
/// keywords = [ "hammer", "construction", "build" ]
|
||||
///
|
||||
/// [[products]]
|
||||
/// name = "Nail"
|
||||
/// sku = 284758393
|
||||
/// color = "gray"
|
||||
///
|
||||
/// )"sv);
|
||||
///
|
||||
/// std::cout << tbl["title"] << "\n";
|
||||
/// std::cout << tbl["products"][0]["name"] << "\n";
|
||||
/// std::cout << tbl["products"][0]["keywords"] << "\n";
|
||||
/// std::cout << tbl["products"][0]["keywords"][2] << "\n";
|
||||
///
|
||||
/// tbl["products"][0]["keywords"].as_array()->push_back("heavy");
|
||||
/// std::cout << tbl["products"][0]["keywords"] << "\n";
|
||||
/// std::cout << "has product[2]: "sv << !!tbl["products"][2] << "\n";
|
||||
/// std::cout << "product[2]: "sv << tbl["products"][2] << "\n";
|
||||
/// \ecpp
|
||||
///
|
||||
/// \out
|
||||
/// "my hardware store"
|
||||
/// "Hammer"
|
||||
/// [ "hammer", "construction", "build" ]
|
||||
/// "build"
|
||||
/// [ "hammer", "construction", "build", "heavy" ]
|
||||
/// has product[2]: false
|
||||
/// product[2]:
|
||||
/// \eout
|
||||
template <typename ViewedType>
|
||||
class TOML_TRIVIAL_ABI node_view
|
||||
{
|
||||
static_assert(impl::is_one_of<ViewedType, toml::node, const toml::node>,
|
||||
"A toml::node_view<> must wrap toml::node or const toml::node.");
|
||||
|
||||
public:
|
||||
/// \brief The node type being viewed - either `node` or `const node`.
|
||||
using viewed_type = ViewedType;
|
||||
|
||||
private:
|
||||
template <typename T>
|
||||
friend class node_view;
|
||||
|
||||
mutable viewed_type* node_ = nullptr;
|
||||
|
||||
public:
|
||||
/// \brief Constructs an empty node view.
|
||||
TOML_NODISCARD_CTOR
|
||||
node_view() noexcept = default;
|
||||
|
||||
/// \brief Constructs node_view of a specific node.
|
||||
TOML_NODISCARD_CTOR
|
||||
explicit node_view(viewed_type* node) noexcept //
|
||||
: node_{ node }
|
||||
{}
|
||||
|
||||
/// \brief Constructs node_view of a specific node.
|
||||
TOML_NODISCARD_CTOR
|
||||
explicit node_view(viewed_type& node) noexcept //
|
||||
: node_{ &node }
|
||||
{}
|
||||
|
||||
/// \brief Copy constructor.
|
||||
TOML_NODISCARD_CTOR
|
||||
node_view(const node_view&) noexcept = default;
|
||||
|
||||
/// \brief Move constructor.
|
||||
TOML_NODISCARD_CTOR
|
||||
node_view(node_view&&) noexcept = default;
|
||||
|
||||
/// \brief Copy-assignment operator.
|
||||
node_view& operator=(const node_view&) & noexcept = default;
|
||||
|
||||
/// \brief Move-assignment operator.
|
||||
node_view& operator=(node_view&&) & noexcept = default;
|
||||
|
||||
/// \brief Returns true if the view references a node.
|
||||
TOML_PURE_INLINE_GETTER
|
||||
explicit operator bool() const noexcept
|
||||
{
|
||||
return node_ != nullptr;
|
||||
}
|
||||
|
||||
/// \brief Returns the node that's being referenced by the view.
|
||||
TOML_PURE_INLINE_GETTER
|
||||
viewed_type* node() const noexcept
|
||||
{
|
||||
return node_;
|
||||
}
|
||||
|
||||
/// \name Type checks
|
||||
/// @{
|
||||
|
||||
/// \brief Returns the type identifier for the viewed node.
|
||||
TOML_PURE_GETTER
|
||||
node_type type() const noexcept
|
||||
{
|
||||
return node_ ? node_->type() : node_type::none;
|
||||
}
|
||||
|
||||
/// \brief Returns true if the viewed node is a toml::table.
|
||||
TOML_PURE_GETTER
|
||||
bool is_table() const noexcept
|
||||
{
|
||||
return node_ && node_->is_table();
|
||||
}
|
||||
|
||||
/// \brief Returns true if the viewed node is a toml::array.
|
||||
TOML_PURE_GETTER
|
||||
bool is_array() const noexcept
|
||||
{
|
||||
return node_ && node_->is_array();
|
||||
}
|
||||
|
||||
/// \brief Returns true if the viewed node is a toml::value<>.
|
||||
TOML_PURE_GETTER
|
||||
bool is_value() const noexcept
|
||||
{
|
||||
return node_ && node_->is_value();
|
||||
}
|
||||
|
||||
/// \brief Returns true if the viewed node is a toml::value<string>.
|
||||
TOML_PURE_GETTER
|
||||
bool is_string() const noexcept
|
||||
{
|
||||
return node_ && node_->is_string();
|
||||
}
|
||||
|
||||
/// \brief Returns true if the viewed node is a toml::value<int64_t>.
|
||||
TOML_PURE_GETTER
|
||||
bool is_integer() const noexcept
|
||||
{
|
||||
return node_ && node_->is_integer();
|
||||
}
|
||||
|
||||
/// \brief Returns true if the viewed node is a toml::value<double>.
|
||||
TOML_PURE_GETTER
|
||||
bool is_floating_point() const noexcept
|
||||
{
|
||||
return node_ && node_->is_floating_point();
|
||||
}
|
||||
|
||||
/// \brief Returns true if the viewed node is a toml::value<int64_t> or toml::value<double>.
|
||||
TOML_PURE_GETTER
|
||||
bool is_number() const noexcept
|
||||
{
|
||||
return node_ && node_->is_number();
|
||||
}
|
||||
|
||||
/// \brief Returns true if the viewed node is a toml::value<bool>.
|
||||
TOML_PURE_GETTER
|
||||
bool is_boolean() const noexcept
|
||||
{
|
||||
return node_ && node_->is_boolean();
|
||||
}
|
||||
|
||||
/// \brief Returns true if the viewed node is a toml::value<date>.
|
||||
TOML_PURE_GETTER
|
||||
bool is_date() const noexcept
|
||||
{
|
||||
return node_ && node_->is_date();
|
||||
}
|
||||
|
||||
/// \brief Returns true if the viewed node is a toml::value<time>.
|
||||
TOML_PURE_GETTER
|
||||
bool is_time() const noexcept
|
||||
{
|
||||
return node_ && node_->is_time();
|
||||
}
|
||||
|
||||
/// \brief Returns true if the viewed node is a toml::value<date_time>.
|
||||
TOML_PURE_GETTER
|
||||
bool is_date_time() const noexcept
|
||||
{
|
||||
return node_ && node_->is_date_time();
|
||||
}
|
||||
|
||||
/// \brief Returns true if the viewed node is a toml::array that contains only tables.
|
||||
TOML_PURE_GETTER
|
||||
bool is_array_of_tables() const noexcept
|
||||
{
|
||||
return node_ && node_->is_array_of_tables();
|
||||
}
|
||||
|
||||
/// \brief Checks if this view references a node of a specific type.
|
||||
///
|
||||
/// \tparam T A TOML node or value type.
|
||||
///
|
||||
/// \returns Returns true if the viewed node is an instance of the specified type.
|
||||
///
|
||||
/// \see toml::node::is()
|
||||
template <typename T>
|
||||
TOML_PURE_GETTER
|
||||
bool is() const noexcept
|
||||
{
|
||||
return node_ ? node_->template is<impl::unwrap_node<impl::remove_cvref<T>>>() : false;
|
||||
}
|
||||
|
||||
/// \brief Checks if the viewed node contains values/elements of only one type.
|
||||
///
|
||||
/// \detail \cpp
|
||||
/// auto cfg = toml::parse("arr = [ 1, 2, 3, 4.0 ]");
|
||||
///
|
||||
/// toml::node* nonmatch{};
|
||||
/// if (cfg["arr"].is_homogeneous(toml::node_type::integer, nonmatch))
|
||||
/// std::cout << "array was homogeneous"sv << "\n";
|
||||
/// else
|
||||
/// std::cout << "array was not homogeneous!\n"
|
||||
/// << "first non-match was a "sv << nonmatch->type() << " at " << nonmatch->source() << "\n";
|
||||
/// \ecpp
|
||||
///
|
||||
/// \out
|
||||
/// array was not homogeneous!
|
||||
/// first non-match was a floating-point at line 1, column 18
|
||||
/// \eout
|
||||
///
|
||||
/// \param ntype A TOML node type. <br>
|
||||
/// \conditional_return{toml::node_type::none} "is every element the same type?"
|
||||
/// \conditional_return{Anything else} "is every element one of these?"
|
||||
///
|
||||
/// \param first_nonmatch Reference to a pointer in which the address of the first non-matching element
|
||||
/// will be stored if the return value is false.
|
||||
///
|
||||
/// \returns True if the viewed node was homogeneous.
|
||||
///
|
||||
/// \remarks Always returns `false` if the view does not reference a node, or if the viewed node is
|
||||
/// an empty table or array.
|
||||
TOML_NODISCARD
|
||||
bool is_homogeneous(node_type ntype, viewed_type*& first_nonmatch) const noexcept
|
||||
{
|
||||
if (!node_)
|
||||
{
|
||||
first_nonmatch = {};
|
||||
return false;
|
||||
}
|
||||
return node_->is_homogeneous(ntype, first_nonmatch);
|
||||
}
|
||||
|
||||
/// \brief Checks if the viewed node contains values/elements of only one type.
|
||||
///
|
||||
/// \detail \cpp
|
||||
/// auto cfg = toml::parse("arr = [ 1, 2, 3 ]");
|
||||
/// std::cout << "homogenous: "sv << cfg["arr"].is_homogeneous(toml::node_type::none) << "\n";
|
||||
/// std::cout << "all floats: "sv << cfg["arr"].is_homogeneous(toml::node_type::floating_point) << "\n";
|
||||
/// std::cout << "all arrays: "sv << cfg["arr"].is_homogeneous(toml::node_type::array) << "\n";
|
||||
/// std::cout << "all ints: "sv << cfg["arr"].is_homogeneous(toml::node_type::integer) << "\n";
|
||||
/// \ecpp
|
||||
///
|
||||
/// \out
|
||||
/// homogeneous: true
|
||||
/// all floats: false
|
||||
/// all arrays: false
|
||||
/// all ints: true
|
||||
/// \eout
|
||||
///
|
||||
/// \param ntype A TOML node type. <br>
|
||||
/// \conditional_return{toml::node_type::none} "is every element the same type?"
|
||||
/// \conditional_return{Anything else} "is every element one of these?"
|
||||
///
|
||||
/// \returns True if the viewed node was homogeneous.
|
||||
///
|
||||
/// \remarks Always returns `false` if the view does not reference a node, or if the viewed node is
|
||||
/// an empty table or array.
|
||||
TOML_NODISCARD
|
||||
bool is_homogeneous(node_type ntype) const noexcept
|
||||
{
|
||||
return node_ ? node_->is_homogeneous(ntype) : false;
|
||||
}
|
||||
|
||||
/// \brief Checks if the viewed node contains values/elements of only one type.
|
||||
///
|
||||
/// \detail \cpp
|
||||
/// auto cfg = toml::parse("arr = [ 1, 2, 3 ]");
|
||||
/// std::cout << "homogenous: "sv << cfg["arr"].is_homogeneous() << "\n";
|
||||
/// std::cout << "all doubles: "sv << cfg["arr"].is_homogeneous<double>() << "\n";
|
||||
/// std::cout << "all arrays: "sv << cfg["arr"].is_homogeneous<toml::array>() << "\n";
|
||||
/// std::cout << "all integers: "sv << cfg["arr"].is_homogeneous<int64_t>() << "\n";
|
||||
/// \ecpp
|
||||
///
|
||||
/// \out
|
||||
/// homogeneous: true
|
||||
/// all floats: false
|
||||
/// all arrays: false
|
||||
/// all ints: true
|
||||
/// \eout
|
||||
///
|
||||
/// \tparam ElemType A TOML node or value type. <br>
|
||||
/// \conditional_return{Left as `void`} "is every element the same type?" <br>
|
||||
/// \conditional_return{Explicitly specified} "is every element a T?"
|
||||
///
|
||||
/// \returns True if the viewed node was homogeneous.
|
||||
///
|
||||
/// \remarks Always returns `false` if the view does not reference a node, or if the viewed node is
|
||||
/// an empty table or array.
|
||||
template <typename ElemType = void>
|
||||
TOML_PURE_GETTER
|
||||
bool is_homogeneous() const noexcept
|
||||
{
|
||||
return node_ ? node_->template is_homogeneous<impl::unwrap_node<impl::remove_cvref<ElemType>>>() : false;
|
||||
}
|
||||
|
||||
/// @}
|
||||
|
||||
/// \name Type casts
|
||||
/// @{
|
||||
|
||||
/// \brief Gets a pointer to the viewed node as a more specific node type.
|
||||
///
|
||||
/// \tparam T The node type or TOML value type to cast to.
|
||||
///
|
||||
/// \returns A pointer to the node as the given type, or nullptr if it was a different type.
|
||||
///
|
||||
/// \see toml::node::as()
|
||||
template <typename T>
|
||||
TOML_PURE_GETTER
|
||||
auto* as() const noexcept
|
||||
{
|
||||
return node_ ? node_->template as<T>() : nullptr;
|
||||
}
|
||||
|
||||
/// \brief Returns a pointer to the viewed node as a toml::table, if it is one.
|
||||
TOML_PURE_GETTER
|
||||
auto* as_table() const noexcept
|
||||
{
|
||||
return as<table>();
|
||||
}
|
||||
|
||||
/// \brief Returns a pointer to the viewed node as a toml::array, if it is one.
|
||||
TOML_PURE_GETTER
|
||||
auto* as_array() const noexcept
|
||||
{
|
||||
return as<array>();
|
||||
}
|
||||
|
||||
/// \brief Returns a pointer to the viewed node as a toml::value<string>, if it is one.
|
||||
TOML_PURE_GETTER
|
||||
auto* as_string() const noexcept
|
||||
{
|
||||
return as<std::string>();
|
||||
}
|
||||
|
||||
/// \brief Returns a pointer to the viewed node as a toml::value<int64_t>, if it is one.
|
||||
TOML_PURE_GETTER
|
||||
auto* as_integer() const noexcept
|
||||
{
|
||||
return as<int64_t>();
|
||||
}
|
||||
|
||||
/// \brief Returns a pointer to the viewed node as a toml::value<double>, if it is one.
|
||||
TOML_PURE_GETTER
|
||||
auto* as_floating_point() const noexcept
|
||||
{
|
||||
return as<double>();
|
||||
}
|
||||
|
||||
/// \brief Returns a pointer to the viewed node as a toml::value<bool>, if it is one.
|
||||
TOML_PURE_GETTER
|
||||
auto* as_boolean() const noexcept
|
||||
{
|
||||
return as<bool>();
|
||||
}
|
||||
|
||||
/// \brief Returns a pointer to the viewed node as a toml::value<date>, if it is one.
|
||||
TOML_PURE_GETTER
|
||||
auto* as_date() const noexcept
|
||||
{
|
||||
return as<date>();
|
||||
}
|
||||
|
||||
/// \brief Returns a pointer to the viewed node as a toml::value<time>, if it is one.
|
||||
TOML_PURE_GETTER
|
||||
auto* as_time() const noexcept
|
||||
{
|
||||
return as<time>();
|
||||
}
|
||||
|
||||
/// \brief Returns a pointer to the viewed node as a toml::value<date_time>, if it is one.
|
||||
TOML_PURE_GETTER
|
||||
auto* as_date_time() const noexcept
|
||||
{
|
||||
return as<date_time>();
|
||||
}
|
||||
|
||||
/// @}
|
||||
|
||||
/// \name Value retrieval
|
||||
/// @{
|
||||
|
||||
/// \brief Gets the value contained by the referenced node.
|
||||
///
|
||||
/// \detail This function has 'exact' retrieval semantics; the only return value types allowed are the
|
||||
/// TOML native value types, or types that can losslessly represent a native value type (e.g.
|
||||
/// std::wstring on Windows).
|
||||
///
|
||||
/// \tparam T One of the native TOML value types, or a type capable of losslessly representing one.
|
||||
///
|
||||
/// \returns The underlying value if the node was a value of the
|
||||
/// matching type (or losslessly convertible to it), or an empty optional.
|
||||
///
|
||||
/// \see node_view::value()
|
||||
template <typename T>
|
||||
TOML_NODISCARD
|
||||
optional<T> value_exact() const noexcept(impl::value_retrieval_is_nothrow<T>)
|
||||
{
|
||||
if (node_)
|
||||
return node_->template value_exact<T>();
|
||||
return {};
|
||||
}
|
||||
|
||||
/// \brief Gets the value contained by the referenced node.
|
||||
///
|
||||
/// \detail This function has 'permissive' retrieval semantics; some value types are allowed
|
||||
/// to convert to others (e.g. retrieving a boolean as an integer), and the specified return value
|
||||
/// type can be any type where a reasonable conversion from a native TOML value exists
|
||||
/// (e.g. std::wstring on Windows). If the source value cannot be represented by
|
||||
/// the destination type, an empty optional is returned. See node::value() for examples.
|
||||
///
|
||||
/// \tparam T One of the native TOML value types, or a type capable of convertible to one.
|
||||
///
|
||||
/// \returns The underlying value if the node was a value of the matching type (or convertible to it)
|
||||
/// and within the range of the output type, or an empty optional.
|
||||
///
|
||||
/// \note If you want strict value retrieval semantics that do not allow for any type conversions,
|
||||
/// use node_view::value_exact() instead.
|
||||
///
|
||||
/// \see
|
||||
/// - node_view::value()
|
||||
/// - node_view::value_exact()
|
||||
template <typename T>
|
||||
TOML_NODISCARD
|
||||
optional<T> value() const noexcept(impl::value_retrieval_is_nothrow<T>)
|
||||
{
|
||||
if (node_)
|
||||
return node_->template value<T>();
|
||||
return {};
|
||||
}
|
||||
|
||||
/// \brief Gets the raw value contained by the referenced node, or a default.
|
||||
///
|
||||
/// \tparam T Default value type. Must be one of the native TOML value types,
|
||||
/// or convertible to it.
|
||||
/// \param default_value The default value to return if the node wasn't a value, wasn't the
|
||||
/// correct type, or no conversion was possible.
|
||||
///
|
||||
/// \returns The underlying value if the node was a value of the matching type (or convertible to it)
|
||||
/// and within the range of the output type, or the provided default.
|
||||
///
|
||||
/// \note This function has the same permissive retrieval semantics as node::value(). If you want strict
|
||||
/// value retrieval semantics that do not allow for any type conversions, use node_view::value_exact()
|
||||
/// instead.
|
||||
///
|
||||
/// \see
|
||||
/// - node_view::value()
|
||||
/// - node_view::value_exact()
|
||||
template <typename T>
|
||||
TOML_NODISCARD
|
||||
auto value_or(T&& default_value) const noexcept(impl::value_retrieval_is_nothrow<T>)
|
||||
{
|
||||
using namespace ::toml::impl;
|
||||
|
||||
static_assert(!is_wide_string<T> || TOML_ENABLE_WINDOWS_COMPAT,
|
||||
"Retrieving values as wide-character strings is only "
|
||||
"supported on Windows with TOML_ENABLE_WINDOWS_COMPAT enabled.");
|
||||
|
||||
if constexpr (is_wide_string<T>)
|
||||
{
|
||||
#if TOML_ENABLE_WINDOWS_COMPAT
|
||||
|
||||
if (node_)
|
||||
return node_->value_or(static_cast<T&&>(default_value));
|
||||
return std::wstring{ static_cast<T&&>(default_value) };
|
||||
|
||||
#else
|
||||
|
||||
static_assert(impl::always_false<T>, "Evaluated unreachable branch!");
|
||||
|
||||
#endif
|
||||
}
|
||||
else
|
||||
{
|
||||
using value_type =
|
||||
std::conditional_t<std::is_pointer_v<std::decay_t<T>>,
|
||||
std::add_pointer_t<std::add_const_t<std::remove_pointer_t<std::decay_t<T>>>>,
|
||||
std::decay_t<T>>;
|
||||
|
||||
if (node_)
|
||||
return node_->value_or(static_cast<T&&>(default_value));
|
||||
if constexpr (std::is_pointer_v<value_type>)
|
||||
return value_type{ default_value };
|
||||
else
|
||||
return static_cast<T&&>(default_value);
|
||||
}
|
||||
}
|
||||
|
||||
/// \brief Gets a raw reference to the viewed node's underlying data.
|
||||
///
|
||||
/// \warning This function is dangerous if used carelessly and **WILL** break your code if the
|
||||
/// node_view didn't reference a node, or the chosen value type doesn't match the node's
|
||||
/// actual type. In debug builds an assertion will fire when invalid accesses are attempted: \cpp
|
||||
///
|
||||
/// auto tbl = toml::parse(R"(
|
||||
/// min = 32
|
||||
/// max = 45
|
||||
/// )"sv);
|
||||
///
|
||||
/// int64_t& min_ref = tbl["min"].ref<int64_t>(); // matching type
|
||||
/// double& max_ref = tbl["max"].ref<double>(); // mismatched type, hits assert()
|
||||
/// int64_t& foo_ref = tbl["foo"].ref<int64_t>(); // nonexistent key, hits assert()
|
||||
/// \ecpp
|
||||
///
|
||||
/// \note Specifying explicit ref qualifiers acts as an explicit ref-category cast,
|
||||
/// whereas specifying explicit cv-ref qualifiers merges them with whatever
|
||||
/// the cv qualification of the viewed node is (to ensure cv-correctness is propagated), e.g.:
|
||||
/// | node_view | T | return type |
|
||||
/// |-----------------------|------------------------|------------------------------|
|
||||
/// | node_view<node> | std::string | std::string& |
|
||||
/// | node_view<node> | std::string&& | std::string&& |
|
||||
/// | node_view<const node> | volatile std::string | const volatile std::string& |
|
||||
/// | node_view<const node> | volatile std::string&& | const volatile std::string&& |
|
||||
///
|
||||
///
|
||||
/// \tparam T One of the TOML value types.
|
||||
///
|
||||
/// \returns A reference to the underlying data.
|
||||
template <typename T>
|
||||
TOML_PURE_INLINE_GETTER
|
||||
decltype(auto) ref() const noexcept
|
||||
{
|
||||
TOML_ASSERT_ASSUME(node_ && "toml::node_view::ref() called on a node_view that did not reference a node");
|
||||
return node_->template ref<T>();
|
||||
}
|
||||
|
||||
/// @}
|
||||
|
||||
/// \name Visitation
|
||||
/// @{
|
||||
|
||||
private:
|
||||
/// \cond
|
||||
template <typename Func>
|
||||
static constexpr bool visit_is_nothrow = noexcept(std::declval<viewed_type*>()->visit(std::declval<Func>()));
|
||||
/// \endcond
|
||||
|
||||
public:
|
||||
/// \brief Invokes a visitor on the viewed node based on its concrete type.
|
||||
///
|
||||
/// \remarks Has no effect if the view does not reference a node.
|
||||
///
|
||||
/// \see node::visit()
|
||||
template <typename Func>
|
||||
decltype(auto) visit(Func&& visitor) const noexcept(visit_is_nothrow<Func&&>)
|
||||
{
|
||||
using return_type = decltype(node_->visit(static_cast<Func&&>(visitor)));
|
||||
if (node_)
|
||||
return node_->visit(static_cast<Func&&>(visitor));
|
||||
if constexpr (!std::is_void_v<return_type>)
|
||||
return return_type{};
|
||||
}
|
||||
|
||||
/// @}
|
||||
|
||||
/// \name Equality
|
||||
/// @{
|
||||
|
||||
public:
|
||||
/// \brief Returns true if the two views refer to nodes of the same type and value.
|
||||
template <typename T>
|
||||
TOML_PURE_GETTER
|
||||
friend bool operator==(const node_view& lhs, const node_view<T>& rhs) noexcept
|
||||
{
|
||||
return impl::node_deep_equality(lhs.node_, rhs.node_);
|
||||
}
|
||||
|
||||
/// \brief Returns true if the two views do not refer to nodes of the same type and value.
|
||||
template <typename T>
|
||||
TOML_PURE_GETTER
|
||||
friend bool operator!=(const node_view& lhs, const node_view<T>& rhs) noexcept
|
||||
{
|
||||
return !impl::node_deep_equality(lhs.node_, rhs.node_);
|
||||
}
|
||||
|
||||
/// \brief Returns true if the viewed node is a table with the same contents as RHS.
|
||||
TOML_NODISCARD
|
||||
friend bool operator==(const node_view& lhs, const table& rhs) noexcept
|
||||
{
|
||||
if (lhs.node_ == &rhs)
|
||||
return true;
|
||||
const auto tbl = lhs.as<table>();
|
||||
return tbl && *tbl == rhs;
|
||||
}
|
||||
TOML_ASYMMETRICAL_EQUALITY_OPS(const node_view&, const table&, );
|
||||
|
||||
/// \brief Returns true if the viewed node is an array with the same contents as RHS.
|
||||
TOML_NODISCARD
|
||||
friend bool operator==(const node_view& lhs, const array& rhs) noexcept
|
||||
{
|
||||
if (lhs.node_ == &rhs)
|
||||
return true;
|
||||
const auto arr = lhs.as<array>();
|
||||
return arr && *arr == rhs;
|
||||
}
|
||||
TOML_ASYMMETRICAL_EQUALITY_OPS(const node_view&, const array&, );
|
||||
|
||||
/// \brief Returns true if the viewed node is a value with the same value as RHS.
|
||||
template <typename T>
|
||||
TOML_NODISCARD
|
||||
friend bool operator==(const node_view& lhs, const toml::value<T>& rhs) noexcept
|
||||
{
|
||||
if (lhs.node_ == &rhs)
|
||||
return true;
|
||||
const auto val = lhs.as<T>();
|
||||
return val && *val == rhs;
|
||||
}
|
||||
TOML_ASYMMETRICAL_EQUALITY_OPS(const node_view&, const toml::value<T>&, template <typename T>);
|
||||
|
||||
/// \brief Returns true if the viewed node is a value with the same value as RHS.
|
||||
TOML_CONSTRAINED_TEMPLATE(impl::is_losslessly_convertible_to_native<T>, typename T)
|
||||
TOML_NODISCARD
|
||||
friend bool operator==(const node_view& lhs, const T& rhs) noexcept(!impl::is_wide_string<T>)
|
||||
{
|
||||
static_assert(!impl::is_wide_string<T> || TOML_ENABLE_WINDOWS_COMPAT,
|
||||
"Comparison with wide-character strings is only "
|
||||
"supported on Windows with TOML_ENABLE_WINDOWS_COMPAT enabled.");
|
||||
|
||||
if constexpr (impl::is_wide_string<T>)
|
||||
{
|
||||
#if TOML_ENABLE_WINDOWS_COMPAT
|
||||
return lhs == impl::narrow(rhs);
|
||||
#else
|
||||
static_assert(impl::always_false<T>, "Evaluated unreachable branch!");
|
||||
#endif
|
||||
}
|
||||
else
|
||||
{
|
||||
const auto val = lhs.as<impl::native_type_of<T>>();
|
||||
return val && *val == rhs;
|
||||
}
|
||||
}
|
||||
TOML_ASYMMETRICAL_EQUALITY_OPS(const node_view&,
|
||||
const T&,
|
||||
TOML_CONSTRAINED_TEMPLATE(impl::is_losslessly_convertible_to_native<T>,
|
||||
typename T));
|
||||
|
||||
/// \brief Returns true if the viewed node is an array with the same contents as the RHS initializer list.
|
||||
template <typename T>
|
||||
TOML_NODISCARD
|
||||
friend bool operator==(const node_view& lhs,
|
||||
const std::initializer_list<T>& rhs) noexcept(!impl::is_wide_string<T>)
|
||||
{
|
||||
const auto arr = lhs.as<array>();
|
||||
return arr && *arr == rhs;
|
||||
}
|
||||
TOML_ASYMMETRICAL_EQUALITY_OPS(const node_view&, const std::initializer_list<T>&, template <typename T>);
|
||||
|
||||
/// \brief Returns true if the viewed node is an array with the same contents as the RHS vector.
|
||||
template <typename T>
|
||||
TOML_NODISCARD
|
||||
friend bool operator==(const node_view& lhs, const std::vector<T>& rhs) noexcept(!impl::is_wide_string<T>)
|
||||
{
|
||||
const auto arr = lhs.as<array>();
|
||||
return arr && *arr == rhs;
|
||||
}
|
||||
TOML_ASYMMETRICAL_EQUALITY_OPS(const node_view&, const std::vector<T>&, template <typename T>);
|
||||
|
||||
/// @}
|
||||
|
||||
/// \name Subviews
|
||||
/// @{
|
||||
|
||||
/// \brief Returns a view of the selected subnode.
|
||||
///
|
||||
/// \param key The key of the node to retrieve
|
||||
///
|
||||
/// \returns A view of the selected node if this node represented a table and it contained a
|
||||
/// value at the given key, or an empty view.
|
||||
TOML_NODISCARD
|
||||
node_view operator[](std::string_view key) const noexcept
|
||||
{
|
||||
if (auto tbl = this->as_table())
|
||||
return node_view{ tbl->get(key) };
|
||||
return {};
|
||||
}
|
||||
|
||||
/// \brief Returns a view of the selected subnode.
|
||||
///
|
||||
/// \param path A "TOML path" to the desired subnode
|
||||
///
|
||||
/// \returns A view of the selected node if this node represented a table and it contained a
|
||||
/// value at the given key, or an empty view.
|
||||
TOML_NODISCARD
|
||||
node_view operator[](const toml::path& path) const noexcept
|
||||
{
|
||||
return node_ ? node_->at_path(path) : node_view{};
|
||||
}
|
||||
|
||||
/// \brief Returns a view of the subnode matching a fully-qualified "TOML path".
|
||||
///
|
||||
/// \see #toml::node::at_path(std::string_view)
|
||||
TOML_NODISCARD
|
||||
node_view at_path(std::string_view path) const noexcept
|
||||
{
|
||||
return node_ ? node_->at_path(path) : node_view{};
|
||||
}
|
||||
|
||||
/// \brief Returns a view of the subnode matching a fully-qualified "TOML path".
|
||||
///
|
||||
/// \see #toml::node::at_path(const toml::path&)
|
||||
TOML_NODISCARD
|
||||
node_view at_path(const toml::path& path) const noexcept
|
||||
{
|
||||
return node_ ? node_->at_path(path) : node_view{};
|
||||
}
|
||||
|
||||
#if TOML_ENABLE_WINDOWS_COMPAT
|
||||
|
||||
/// \brief Returns a view of the selected subnode.
|
||||
///
|
||||
/// \availability This overload is only available when #TOML_ENABLE_WINDOWS_COMPAT is enabled.
|
||||
///
|
||||
/// \param key The key of the node to retrieve
|
||||
///
|
||||
/// \returns A view of the selected node if this node represented a table and it contained a
|
||||
/// value at the given key, or an empty view.
|
||||
TOML_NODISCARD
|
||||
node_view operator[](std::wstring_view key) const
|
||||
{
|
||||
if (auto tbl = this->as_table())
|
||||
return node_view{ tbl->get(key) };
|
||||
return {};
|
||||
}
|
||||
|
||||
/// \brief Returns a view of the subnode matching a fully-qualified "TOML path".
|
||||
///
|
||||
/// \availability This overload is only available when #TOML_ENABLE_WINDOWS_COMPAT is enabled.
|
||||
///
|
||||
/// \see #toml::node::at_path(std::string_view)
|
||||
TOML_NODISCARD
|
||||
node_view at_path(std::wstring_view path) const
|
||||
{
|
||||
return node_ ? node_->at_path(path) : node_view{};
|
||||
}
|
||||
|
||||
#endif // TOML_ENABLE_WINDOWS_COMPAT
|
||||
|
||||
/// \brief Returns a view of the selected subnode.
|
||||
///
|
||||
/// \param index The index of the node to retrieve
|
||||
///
|
||||
/// \returns A view of the selected node if this node represented an array and it contained a
|
||||
/// value at the given index, or an empty view.
|
||||
TOML_NODISCARD
|
||||
node_view operator[](size_t index) const noexcept
|
||||
{
|
||||
if (auto arr = this->as_array())
|
||||
return node_view{ arr->get(index) };
|
||||
return {};
|
||||
}
|
||||
|
||||
/// @}
|
||||
|
||||
#if TOML_ENABLE_FORMATTERS
|
||||
|
||||
/// \brief Prints the viewed node out to a stream.
|
||||
///
|
||||
/// \availability This operator is only available when #TOML_ENABLE_FORMATTERS is enabled.
|
||||
friend std::ostream& operator<<(std::ostream& os, const node_view& nv)
|
||||
{
|
||||
if (nv.node_)
|
||||
nv.node_->visit([&os](const auto& n) { os << n; });
|
||||
return os;
|
||||
}
|
||||
|
||||
#endif
|
||||
};
|
||||
|
||||
/// \cond
|
||||
|
||||
template <typename T>
|
||||
node_view(const T&) -> node_view<const node>;
|
||||
|
||||
template <typename T>
|
||||
node_view(const T*) -> node_view<const node>;
|
||||
|
||||
template <typename T>
|
||||
node_view(T&) -> node_view<node>;
|
||||
|
||||
template <typename T>
|
||||
node_view(T*) -> node_view<node>;
|
||||
|
||||
/// \endcond
|
||||
}
|
||||
TOML_NAMESPACE_END;
|
||||
|
||||
/// \cond
|
||||
TOML_NAMESPACE_START
|
||||
{
|
||||
inline node::operator node_view<node>() noexcept
|
||||
{
|
||||
return node_view<node>{ this };
|
||||
}
|
||||
|
||||
inline node::operator node_view<const node>() const noexcept
|
||||
{
|
||||
return node_view<const node>{ this };
|
||||
}
|
||||
}
|
||||
TOML_NAMESPACE_END;
|
||||
/// \endcond
|
||||
|
||||
#include "header_end.hpp"
|
||||
@@ -0,0 +1,139 @@
|
||||
//# This file is a part of toml++ and is subject to the the terms of the MIT license.
|
||||
//# Copyright (c) Mark Gillard <mark.gillard@outlook.com.au>
|
||||
//# See https://github.com/marzer/tomlplusplus/blob/master/LICENSE for the full license text.
|
||||
// SPDX-License-Identifier: MIT
|
||||
#pragma once
|
||||
|
||||
#include "preprocessor.hpp"
|
||||
#if TOML_ENABLE_PARSER
|
||||
|
||||
#include "std_except.hpp"
|
||||
#include "source_region.hpp"
|
||||
#include "print_to_stream.hpp"
|
||||
#include "header_start.hpp"
|
||||
|
||||
#if TOML_DOXYGEN || !TOML_EXCEPTIONS
|
||||
#define TOML_PARSE_ERROR_BASE
|
||||
#else
|
||||
#define TOML_PARSE_ERROR_BASE : public std::runtime_error
|
||||
#endif
|
||||
|
||||
TOML_NAMESPACE_START
|
||||
{
|
||||
TOML_ABI_NAMESPACE_BOOL(TOML_EXCEPTIONS, ex, noex);
|
||||
|
||||
/// \brief An error generated when parsing fails.
|
||||
///
|
||||
/// \remarks This class inherits from std::runtime_error when exceptions are enabled.
|
||||
/// The public interface is the same regardless of exception mode.
|
||||
class parse_error TOML_PARSE_ERROR_BASE
|
||||
{
|
||||
private:
|
||||
#if !TOML_EXCEPTIONS
|
||||
std::string description_;
|
||||
#endif
|
||||
source_region source_;
|
||||
|
||||
public:
|
||||
#if TOML_EXCEPTIONS
|
||||
|
||||
TOML_NODISCARD_CTOR
|
||||
TOML_ATTR(nonnull)
|
||||
parse_error(const char* desc, source_region&& src) noexcept //
|
||||
: std::runtime_error{ desc },
|
||||
source_{ std::move(src) }
|
||||
{}
|
||||
|
||||
TOML_NODISCARD_CTOR
|
||||
TOML_ATTR(nonnull)
|
||||
parse_error(const char* desc, const source_region& src) noexcept //
|
||||
: parse_error{ desc, source_region{ src } }
|
||||
{}
|
||||
|
||||
TOML_NODISCARD_CTOR
|
||||
TOML_ATTR(nonnull)
|
||||
parse_error(const char* desc, const source_position& position, const source_path_ptr& path = {}) noexcept
|
||||
: parse_error{ desc, source_region{ position, position, path } }
|
||||
{}
|
||||
|
||||
#else
|
||||
|
||||
TOML_NODISCARD_CTOR
|
||||
parse_error(std::string&& desc, source_region&& src) noexcept //
|
||||
: description_{ std::move(desc) },
|
||||
source_{ std::move(src) }
|
||||
{}
|
||||
|
||||
TOML_NODISCARD_CTOR
|
||||
parse_error(std::string&& desc, const source_region& src) noexcept //
|
||||
: parse_error{ std::move(desc), source_region{ src } }
|
||||
{}
|
||||
|
||||
TOML_NODISCARD_CTOR
|
||||
parse_error(std::string&& desc, const source_position& position, const source_path_ptr& path = {}) noexcept
|
||||
: parse_error{ std::move(desc), source_region{ position, position, path } }
|
||||
{}
|
||||
|
||||
#endif
|
||||
|
||||
/// \brief Returns a textual description of the error.
|
||||
/// \remark The backing string is guaranteed to be null-terminated.
|
||||
TOML_NODISCARD
|
||||
std::string_view description() const noexcept
|
||||
{
|
||||
#if TOML_EXCEPTIONS
|
||||
return std::string_view{ what() };
|
||||
#else
|
||||
return description_;
|
||||
#endif
|
||||
}
|
||||
|
||||
/// \brief Returns the region of the source document responsible for the error.
|
||||
TOML_NODISCARD
|
||||
const source_region& source() const noexcept
|
||||
{
|
||||
return source_;
|
||||
}
|
||||
|
||||
/// \brief Prints a parse_error to a stream.
|
||||
///
|
||||
/// \detail \cpp
|
||||
/// try
|
||||
/// {
|
||||
/// auto tbl = toml::parse("enabled = trUe"sv);
|
||||
/// }
|
||||
/// catch (const toml::parse_error & err)
|
||||
/// {
|
||||
/// std::cerr << "Parsing failed:\n"sv << err << "\n";
|
||||
/// }
|
||||
/// \ecpp
|
||||
///
|
||||
/// \out
|
||||
/// Parsing failed:
|
||||
/// Encountered unexpected character while parsing boolean; expected 'true', saw 'trU'
|
||||
/// (error occurred at line 1, column 13)
|
||||
/// \eout
|
||||
///
|
||||
/// \tparam Char The output stream's underlying character type. Must be 1 byte in size.
|
||||
/// \param lhs The stream.
|
||||
/// \param rhs The parse_error.
|
||||
///
|
||||
/// \returns The input stream.
|
||||
friend std::ostream& operator<<(std::ostream& lhs, const parse_error& rhs)
|
||||
{
|
||||
impl::print_to_stream(lhs, rhs.description());
|
||||
impl::print_to_stream(lhs, "\n\t(error occurred at "sv);
|
||||
impl::print_to_stream(lhs, rhs.source());
|
||||
impl::print_to_stream(lhs, ")"sv);
|
||||
return lhs;
|
||||
}
|
||||
};
|
||||
|
||||
TOML_ABI_NAMESPACE_END; // TOML_EXCEPTIONS
|
||||
}
|
||||
TOML_NAMESPACE_END;
|
||||
|
||||
#undef TOML_PARSE_ERROR_BASE
|
||||
|
||||
#include "header_end.hpp"
|
||||
#endif // TOML_ENABLE_PARSER
|
||||
@@ -0,0 +1,499 @@
|
||||
//# This file is a part of toml++ and is subject to the the terms of the MIT license.
|
||||
//# Copyright (c) Mark Gillard <mark.gillard@outlook.com.au>
|
||||
//# See https://github.com/marzer/tomlplusplus/blob/master/LICENSE for the full license text.
|
||||
// SPDX-License-Identifier: MIT
|
||||
#pragma once
|
||||
|
||||
#include "preprocessor.hpp"
|
||||
#if TOML_DOXYGEN || (TOML_ENABLE_PARSER && !TOML_EXCEPTIONS)
|
||||
|
||||
#include "table.hpp"
|
||||
#include "parse_error.hpp"
|
||||
#include "header_start.hpp"
|
||||
|
||||
TOML_NAMESPACE_START
|
||||
{
|
||||
TOML_ABI_NAMESPACE_START(noex);
|
||||
|
||||
/// \brief The result of a parsing operation.
|
||||
///
|
||||
/// \availability <strong>This type only exists when exceptions are disabled.</strong>
|
||||
/// Otherwise parse_result is just an alias for toml::table: \cpp
|
||||
/// #if TOML_EXCEPTIONS
|
||||
/// using parse_result = table;
|
||||
/// #else
|
||||
/// class parse_result { // ...
|
||||
/// #endif
|
||||
/// \ecpp
|
||||
///
|
||||
/// \detail A parse_result is effectively a discriminated union containing either a toml::table
|
||||
/// or a toml::parse_error. Most member functions assume a particular one of these two states,
|
||||
/// and calling them when in the wrong state will cause errors (e.g. attempting to access the
|
||||
/// error object when parsing was successful). \cpp
|
||||
/// toml::parse_result result = toml::parse_file("config.toml");
|
||||
/// if (result)
|
||||
/// do_stuff_with_a_table(result); //implicitly converts to table&
|
||||
/// else
|
||||
/// std::cerr << "Parse failed:\n"sv << result.error() << "\n";
|
||||
/// \ecpp
|
||||
///
|
||||
/// \out
|
||||
/// example output:
|
||||
///
|
||||
/// Parse failed:
|
||||
/// Encountered unexpected character while parsing boolean; expected 'true', saw 'trU'
|
||||
/// (error occurred at line 1, column 13 of 'config.toml')
|
||||
/// \eout
|
||||
///
|
||||
/// Getting node_views (`operator[]`, `at_path()`) and using the iterator accessor functions (`begin()`, `end()` etc.) are
|
||||
/// unconditionally safe; when parsing fails these just return 'empty' values. A ranged-for loop on a failed
|
||||
/// parse_result is also safe since `begin()` and `end()` return the same iterator and will not lead to any
|
||||
/// dereferences and iterations.
|
||||
class parse_result
|
||||
{
|
||||
private:
|
||||
struct storage_t
|
||||
{
|
||||
static constexpr size_t size =
|
||||
(sizeof(toml::table) < sizeof(parse_error) ? sizeof(parse_error) : sizeof(toml::table));
|
||||
static constexpr size_t align =
|
||||
(alignof(toml::table) < alignof(parse_error) ? alignof(parse_error) : alignof(toml::table));
|
||||
|
||||
alignas(align) unsigned char bytes[size];
|
||||
};
|
||||
|
||||
alignas(storage_t::align) mutable storage_t storage_;
|
||||
bool err_;
|
||||
|
||||
template <typename Type>
|
||||
TOML_NODISCARD
|
||||
TOML_ALWAYS_INLINE
|
||||
static Type* get_as(storage_t& s) noexcept
|
||||
{
|
||||
return TOML_LAUNDER(reinterpret_cast<Type*>(s.bytes));
|
||||
}
|
||||
|
||||
void destroy() noexcept
|
||||
{
|
||||
if (err_)
|
||||
get_as<parse_error>(storage_)->~parse_error();
|
||||
else
|
||||
get_as<toml::table>(storage_)->~table();
|
||||
}
|
||||
|
||||
public:
|
||||
/// \brief Default constructs an 'error' result.
|
||||
TOML_NODISCARD_CTOR
|
||||
parse_result() noexcept //
|
||||
: err_{ true }
|
||||
{
|
||||
::new (static_cast<void*>(storage_.bytes)) parse_error{ std::string{}, source_region{} };
|
||||
}
|
||||
|
||||
TOML_NODISCARD_CTOR
|
||||
explicit parse_result(toml::table&& tbl) noexcept //
|
||||
: err_{ false }
|
||||
{
|
||||
::new (static_cast<void*>(storage_.bytes)) toml::table{ std::move(tbl) };
|
||||
}
|
||||
|
||||
TOML_NODISCARD_CTOR
|
||||
explicit parse_result(parse_error&& err) noexcept //
|
||||
: err_{ true }
|
||||
{
|
||||
::new (static_cast<void*>(storage_.bytes)) parse_error{ std::move(err) };
|
||||
}
|
||||
|
||||
/// \brief Move constructor.
|
||||
TOML_NODISCARD_CTOR
|
||||
parse_result(parse_result&& res) noexcept //
|
||||
: err_{ res.err_ }
|
||||
{
|
||||
if (err_)
|
||||
::new (static_cast<void*>(storage_.bytes)) parse_error{ std::move(res).error() };
|
||||
else
|
||||
::new (static_cast<void*>(storage_.bytes)) toml::table{ std::move(res).table() };
|
||||
}
|
||||
|
||||
/// \brief Move-assignment operator.
|
||||
parse_result& operator=(parse_result&& rhs) noexcept
|
||||
{
|
||||
if (err_ != rhs.err_)
|
||||
{
|
||||
destroy();
|
||||
err_ = rhs.err_;
|
||||
if (err_)
|
||||
::new (static_cast<void*>(storage_.bytes)) parse_error{ std::move(rhs).error() };
|
||||
else
|
||||
::new (static_cast<void*>(storage_.bytes)) toml::table{ std::move(rhs).table() };
|
||||
}
|
||||
else
|
||||
{
|
||||
if (err_)
|
||||
error() = std::move(rhs).error();
|
||||
else
|
||||
table() = std::move(rhs).table();
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
/// \brief Destructor.
|
||||
~parse_result() noexcept
|
||||
{
|
||||
destroy();
|
||||
}
|
||||
|
||||
/// \name Result state
|
||||
/// @{
|
||||
|
||||
/// \brief Returns true if parsing succeeeded.
|
||||
TOML_NODISCARD
|
||||
bool succeeded() const noexcept
|
||||
{
|
||||
return !err_;
|
||||
}
|
||||
|
||||
/// \brief Returns true if parsing failed.
|
||||
TOML_NODISCARD
|
||||
bool failed() const noexcept
|
||||
{
|
||||
return err_;
|
||||
}
|
||||
|
||||
/// \brief Returns true if parsing succeeded.
|
||||
TOML_NODISCARD
|
||||
explicit operator bool() const noexcept
|
||||
{
|
||||
return !err_;
|
||||
}
|
||||
|
||||
/// @}
|
||||
|
||||
/// \name Successful parses
|
||||
/// \warning It is undefined behaviour to call these functions when the result respresents a failed parse.
|
||||
/// Check #failed(), #succeeded or #operator bool() to determine the result's state.
|
||||
/// @{
|
||||
|
||||
/// \brief Returns the internal toml::table.
|
||||
TOML_NODISCARD
|
||||
toml::table& table() & noexcept
|
||||
{
|
||||
TOML_ASSERT_ASSUME(!err_);
|
||||
return *get_as<toml::table>(storage_);
|
||||
}
|
||||
|
||||
/// \brief Returns the internal toml::table (rvalue overload).
|
||||
TOML_NODISCARD
|
||||
toml::table&& table() && noexcept
|
||||
{
|
||||
TOML_ASSERT_ASSUME(!err_);
|
||||
return static_cast<toml::table&&>(*get_as<toml::table>(storage_));
|
||||
}
|
||||
|
||||
/// \brief Returns the internal toml::table (const lvalue overload).
|
||||
TOML_NODISCARD
|
||||
const toml::table& table() const& noexcept
|
||||
{
|
||||
TOML_ASSERT_ASSUME(!err_);
|
||||
return *get_as<const toml::table>(storage_);
|
||||
}
|
||||
|
||||
/// \brief Returns the internal toml::table.
|
||||
TOML_NODISCARD
|
||||
/* implicit */ operator toml::table&() noexcept
|
||||
{
|
||||
return table();
|
||||
}
|
||||
|
||||
/// \brief Returns the internal toml::table (rvalue overload).
|
||||
TOML_NODISCARD
|
||||
/* implicit */ operator toml::table&&() noexcept
|
||||
{
|
||||
return std::move(table());
|
||||
}
|
||||
|
||||
/// \brief Returns the internal toml::table (const lvalue overload).
|
||||
TOML_NODISCARD
|
||||
/* implicit */ operator const toml::table&() const noexcept
|
||||
{
|
||||
return table();
|
||||
}
|
||||
|
||||
/// @}
|
||||
|
||||
/// \name Failed parses
|
||||
/// \warning It is undefined behaviour to call these functions when the result respresents a successful parse.
|
||||
/// Check #failed(), #succeeded or #operator bool() to determine the result's state.
|
||||
/// @{
|
||||
|
||||
/// \brief Returns the internal toml::parse_error.
|
||||
TOML_NODISCARD
|
||||
parse_error& error() & noexcept
|
||||
{
|
||||
TOML_ASSERT_ASSUME(err_);
|
||||
return *get_as<parse_error>(storage_);
|
||||
}
|
||||
|
||||
/// \brief Returns the internal toml::parse_error (rvalue overload).
|
||||
TOML_NODISCARD
|
||||
parse_error&& error() && noexcept
|
||||
{
|
||||
TOML_ASSERT_ASSUME(err_);
|
||||
return static_cast<parse_error&&>(*get_as<parse_error>(storage_));
|
||||
}
|
||||
|
||||
/// \brief Returns the internal toml::parse_error (const lvalue overload).
|
||||
TOML_NODISCARD
|
||||
const parse_error& error() const& noexcept
|
||||
{
|
||||
TOML_ASSERT_ASSUME(err_);
|
||||
return *get_as<const parse_error>(storage_);
|
||||
}
|
||||
|
||||
/// \brief Returns the internal toml::parse_error.
|
||||
TOML_NODISCARD
|
||||
explicit operator parse_error&() noexcept
|
||||
{
|
||||
return error();
|
||||
}
|
||||
|
||||
/// \brief Returns the internal toml::parse_error (rvalue overload).
|
||||
TOML_NODISCARD
|
||||
explicit operator parse_error&&() noexcept
|
||||
{
|
||||
return std::move(error());
|
||||
}
|
||||
|
||||
/// \brief Returns the internal toml::parse_error (const lvalue overload).
|
||||
TOML_NODISCARD
|
||||
explicit operator const parse_error&() const noexcept
|
||||
{
|
||||
return error();
|
||||
}
|
||||
|
||||
/// @}
|
||||
|
||||
/// \name Iteration
|
||||
/// @{
|
||||
|
||||
/// \brief A BidirectionalIterator for iterating over key-value pairs in a wrapped toml::table.
|
||||
using iterator = table_iterator;
|
||||
|
||||
/// \brief A BidirectionalIterator for iterating over const key-value pairs in a wrapped toml::table.
|
||||
using const_iterator = const_table_iterator;
|
||||
|
||||
/// \brief Returns an iterator to the first key-value pair in the wrapped table.
|
||||
/// \remarks Always returns the same value as #end() if parsing failed.
|
||||
TOML_NODISCARD
|
||||
table_iterator begin() noexcept
|
||||
{
|
||||
return err_ ? table_iterator{} : table().begin();
|
||||
}
|
||||
|
||||
/// \brief Returns an iterator to the first key-value pair in the wrapped table.
|
||||
/// \remarks Always returns the same value as #end() if parsing failed.
|
||||
TOML_NODISCARD
|
||||
const_table_iterator begin() const noexcept
|
||||
{
|
||||
return err_ ? const_table_iterator{} : table().begin();
|
||||
}
|
||||
|
||||
/// \brief Returns an iterator to the first key-value pair in the wrapped table.
|
||||
/// \remarks Always returns the same value as #cend() if parsing failed.
|
||||
TOML_NODISCARD
|
||||
const_table_iterator cbegin() const noexcept
|
||||
{
|
||||
return err_ ? const_table_iterator{} : table().cbegin();
|
||||
}
|
||||
|
||||
/// \brief Returns an iterator to one-past-the-last key-value pair in the wrapped table.
|
||||
TOML_NODISCARD
|
||||
table_iterator end() noexcept
|
||||
{
|
||||
return err_ ? table_iterator{} : table().end();
|
||||
}
|
||||
|
||||
/// \brief Returns an iterator to one-past-the-last key-value pair in the wrapped table.
|
||||
TOML_NODISCARD
|
||||
const_table_iterator end() const noexcept
|
||||
{
|
||||
return err_ ? const_table_iterator{} : table().end();
|
||||
}
|
||||
|
||||
/// \brief Returns an iterator to one-past-the-last key-value pair in the wrapped table.
|
||||
TOML_NODISCARD
|
||||
const_table_iterator cend() const noexcept
|
||||
{
|
||||
return err_ ? const_table_iterator{} : table().cend();
|
||||
}
|
||||
|
||||
/// @}
|
||||
|
||||
/// \name Node views
|
||||
/// @{
|
||||
|
||||
/// \brief Returns a view of the subnode matching a fully-qualified "TOML path".
|
||||
///
|
||||
/// \see #toml::node::at_path(std::string_view)
|
||||
TOML_NODISCARD
|
||||
node_view<node> at_path(std::string_view path) noexcept
|
||||
{
|
||||
return err_ ? node_view<node>{} : table().at_path(path);
|
||||
}
|
||||
|
||||
/// \brief Returns a const view of the subnode matching a fully-qualified "TOML path".
|
||||
///
|
||||
/// \see #toml::node::at_path(std::string_view)
|
||||
TOML_NODISCARD
|
||||
node_view<const node> at_path(std::string_view path) const noexcept
|
||||
{
|
||||
return err_ ? node_view<const node>{} : table().at_path(path);
|
||||
}
|
||||
|
||||
/// \brief Returns a view of the subnode matching a fully-qualified "TOML path".
|
||||
///
|
||||
/// \see #toml::node::at_path(const toml::path&)
|
||||
TOML_NODISCARD
|
||||
node_view<node> at_path(const toml::path& path) noexcept
|
||||
{
|
||||
return err_ ? node_view<node>{} : table().at_path(path);
|
||||
}
|
||||
|
||||
/// \brief Returns a const view of the subnode matching a fully-qualified "TOML path".
|
||||
///
|
||||
/// \see #toml::node::at_path(const toml::path&)
|
||||
TOML_NODISCARD
|
||||
node_view<const node> at_path(const toml::path& path) const noexcept
|
||||
{
|
||||
return err_ ? node_view<const node>{} : table().at_path(path);
|
||||
}
|
||||
|
||||
#if TOML_ENABLE_WINDOWS_COMPAT
|
||||
|
||||
/// \brief Returns a view of the subnode matching a fully-qualified "TOML path".
|
||||
///
|
||||
/// \availability This overload is only available when #TOML_ENABLE_WINDOWS_COMPAT is enabled.
|
||||
///
|
||||
/// \see #toml::node::at_path(std::string_view)
|
||||
TOML_NODISCARD
|
||||
node_view<node> at_path(std::wstring_view path)
|
||||
{
|
||||
return err_ ? node_view<node>{} : table().at_path(path);
|
||||
}
|
||||
|
||||
/// \brief Returns a const view of the subnode matching a fully-qualified "TOML path".
|
||||
///
|
||||
/// \availability This overload is only available when #TOML_ENABLE_WINDOWS_COMPAT is enabled.
|
||||
///
|
||||
/// \see #toml::node::at_path(std::string_view)
|
||||
TOML_NODISCARD
|
||||
node_view<const node> at_path(std::wstring_view path) const
|
||||
{
|
||||
return err_ ? node_view<const node>{} : table().at_path(path);
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
/// \brief Returns a view of the subnode matching a fully-qualified "TOML path".
|
||||
///
|
||||
/// \see #toml::node::operator[](const toml::path&)
|
||||
TOML_NODISCARD
|
||||
node_view<node> operator[](const toml::path& path) noexcept
|
||||
{
|
||||
return err_ ? node_view<node>{} : table()[path];
|
||||
}
|
||||
|
||||
/// \brief Returns a const view of the subnode matching a fully-qualified "TOML path".
|
||||
///
|
||||
/// \see #toml::node::operator[](const toml::path&)
|
||||
TOML_NODISCARD
|
||||
node_view<const node> operator[](const toml::path& path) const noexcept
|
||||
{
|
||||
return err_ ? node_view<const node>{} : table()[path];
|
||||
}
|
||||
|
||||
/// \brief Gets a node_view for the selected key-value pair in the wrapped table.
|
||||
///
|
||||
/// \param key The key used for the lookup.
|
||||
///
|
||||
/// \returns A view of the value at the given key if parsing was successful and a matching key existed,
|
||||
/// or an empty node view.
|
||||
///
|
||||
/// \see toml::node_view
|
||||
TOML_NODISCARD
|
||||
node_view<node> operator[](std::string_view key) noexcept
|
||||
{
|
||||
return err_ ? node_view<node>{} : table()[key];
|
||||
}
|
||||
|
||||
/// \brief Gets a node_view for the selected key-value pair in the wrapped table (const overload).
|
||||
///
|
||||
/// \param key The key used for the lookup.
|
||||
///
|
||||
/// \returns A view of the value at the given key if parsing was successful and a matching key existed,
|
||||
/// or an empty node view.
|
||||
///
|
||||
/// \see toml::node_view
|
||||
TOML_NODISCARD
|
||||
node_view<const node> operator[](std::string_view key) const noexcept
|
||||
{
|
||||
return err_ ? node_view<const node>{} : table()[key];
|
||||
}
|
||||
|
||||
#if TOML_ENABLE_WINDOWS_COMPAT
|
||||
|
||||
/// \brief Gets a node_view for the selected key-value pair in the wrapped table.
|
||||
///
|
||||
/// \availability This overload is only available when #TOML_ENABLE_WINDOWS_COMPAT is enabled.
|
||||
///
|
||||
/// \param key The key used for the lookup.
|
||||
///
|
||||
/// \returns A view of the value at the given key if parsing was successful and a matching key existed,
|
||||
/// or an empty node view.
|
||||
///
|
||||
/// \see toml::node_view
|
||||
TOML_NODISCARD
|
||||
node_view<node> operator[](std::wstring_view key)
|
||||
{
|
||||
return err_ ? node_view<node>{} : table()[key];
|
||||
}
|
||||
|
||||
/// \brief Gets a node_view for the selected key-value pair in the wrapped table (const overload).
|
||||
///
|
||||
/// \availability This overload is only available when #TOML_ENABLE_WINDOWS_COMPAT is enabled.
|
||||
///
|
||||
/// \param key The key used for the lookup.
|
||||
///
|
||||
/// \returns A view of the value at the given key if parsing was successful and a matching key existed,
|
||||
/// or an empty node view.
|
||||
///
|
||||
/// \see toml::node_view
|
||||
TOML_NODISCARD
|
||||
node_view<const node> operator[](std::wstring_view key) const
|
||||
{
|
||||
return err_ ? node_view<const node>{} : table()[key];
|
||||
}
|
||||
|
||||
#endif // TOML_ENABLE_WINDOWS_COMPAT
|
||||
|
||||
/// @}
|
||||
|
||||
#if TOML_ENABLE_FORMATTERS
|
||||
|
||||
/// \brief Prints the held error or table object out to a text stream.
|
||||
///
|
||||
/// \availability This operator is only available when #TOML_ENABLE_FORMATTERS is enabled.
|
||||
friend std::ostream& operator<<(std::ostream& os, const parse_result& result)
|
||||
{
|
||||
return result.err_ ? (os << result.error()) : (os << result.table());
|
||||
}
|
||||
|
||||
#endif
|
||||
};
|
||||
|
||||
TOML_ABI_NAMESPACE_END;
|
||||
}
|
||||
TOML_NAMESPACE_END;
|
||||
|
||||
#include "header_end.hpp"
|
||||
#endif // TOML_ENABLE_PARSER && !TOML_EXCEPTIONS
|
||||
@@ -0,0 +1,390 @@
|
||||
//# This file is a part of toml++ and is subject to the the terms of the MIT license.
|
||||
//# Copyright (c) Mark Gillard <mark.gillard@outlook.com.au>
|
||||
//# See https://github.com/marzer/tomlplusplus/blob/master/LICENSE for the full license text.
|
||||
// SPDX-License-Identifier: MIT
|
||||
#pragma once
|
||||
|
||||
#include "preprocessor.hpp"
|
||||
#if TOML_ENABLE_PARSER
|
||||
|
||||
#include "table.hpp"
|
||||
#include "parse_result.hpp"
|
||||
#include "header_start.hpp"
|
||||
|
||||
TOML_NAMESPACE_START
|
||||
{
|
||||
TOML_ABI_NAMESPACE_BOOL(TOML_EXCEPTIONS, ex, noex);
|
||||
|
||||
/// \brief Parses a TOML document from a string view.
|
||||
///
|
||||
/// \detail \cpp
|
||||
/// auto tbl = toml::parse("a = 3"sv);
|
||||
/// std::cout << tbl["a"] << "\n";
|
||||
/// \ecpp
|
||||
///
|
||||
/// \out
|
||||
/// 3
|
||||
/// \eout
|
||||
///
|
||||
/// \param doc The TOML document to parse. Must be valid UTF-8.
|
||||
/// \param source_path The path used to initialize each node's `source().path`.
|
||||
/// If you don't have a path (or you have no intention of using paths in diagnostics)
|
||||
/// then this parameter can safely be left blank.
|
||||
///
|
||||
/// \returns \conditional_return{With exceptions}
|
||||
/// A toml::table.
|
||||
/// \conditional_return{Without exceptions}
|
||||
/// A toml::parse_result.
|
||||
TOML_NODISCARD
|
||||
TOML_EXPORTED_FREE_FUNCTION
|
||||
parse_result TOML_CALLCONV parse(std::string_view doc, std::string_view source_path = {});
|
||||
|
||||
/// \brief Parses a TOML document from a string view.
|
||||
///
|
||||
/// \detail \cpp
|
||||
/// auto tbl = toml::parse("a = 3"sv, "foo.toml");
|
||||
/// std::cout << tbl["a"] << "\n";
|
||||
/// \ecpp
|
||||
///
|
||||
/// \out
|
||||
/// 3
|
||||
/// \eout
|
||||
///
|
||||
/// \param doc The TOML document to parse. Must be valid UTF-8.
|
||||
/// \param source_path The path used to initialize each node's `source().path`.
|
||||
/// If you don't have a path (or you have no intention of using paths in diagnostics)
|
||||
/// then this parameter can safely be left blank.
|
||||
///
|
||||
/// \returns \conditional_return{With exceptions}
|
||||
/// A toml::table.
|
||||
/// \conditional_return{Without exceptions}
|
||||
/// A toml::parse_result.
|
||||
TOML_NODISCARD
|
||||
TOML_EXPORTED_FREE_FUNCTION
|
||||
parse_result TOML_CALLCONV parse(std::string_view doc, std::string && source_path);
|
||||
|
||||
/// \brief Parses a TOML document from a file.
|
||||
///
|
||||
/// \detail \cpp
|
||||
/// toml::parse_result get_foo_toml()
|
||||
/// {
|
||||
/// return toml::parse_file("foo.toml");
|
||||
/// }
|
||||
/// \ecpp
|
||||
///
|
||||
/// \param file_path The TOML document to parse. Must be valid UTF-8.
|
||||
///
|
||||
/// \returns \conditional_return{With exceptions}
|
||||
/// A toml::table.
|
||||
/// \conditional_return{Without exceptions}
|
||||
/// A toml::parse_result.
|
||||
TOML_NODISCARD
|
||||
TOML_EXPORTED_FREE_FUNCTION
|
||||
parse_result TOML_CALLCONV parse_file(std::string_view file_path);
|
||||
|
||||
#if TOML_HAS_CHAR8
|
||||
|
||||
/// \brief Parses a TOML document from a char8_t string view.
|
||||
///
|
||||
/// \detail \cpp
|
||||
/// auto tbl = toml::parse(u8"a = 3"sv);
|
||||
/// std::cout << tbl["a"] << "\n";
|
||||
/// \ecpp
|
||||
///
|
||||
/// \out
|
||||
/// 3
|
||||
/// \eout
|
||||
///
|
||||
/// \param doc The TOML document to parse. Must be valid UTF-8.
|
||||
/// \param source_path The path used to initialize each node's `source().path`.
|
||||
/// If you don't have a path (or you have no intention of using paths in diagnostics)
|
||||
/// then this parameter can safely be left blank.
|
||||
///
|
||||
/// \returns \conditional_return{With exceptions}
|
||||
/// A toml::table.
|
||||
/// \conditional_return{Without exceptions}
|
||||
/// A toml::parse_result.
|
||||
TOML_NODISCARD
|
||||
TOML_EXPORTED_FREE_FUNCTION
|
||||
parse_result TOML_CALLCONV parse(std::u8string_view doc, std::string_view source_path = {});
|
||||
|
||||
/// \brief Parses a TOML document from a char8_t string view.
|
||||
///
|
||||
/// \detail \cpp
|
||||
/// auto tbl = toml::parse(u8"a = 3"sv, "foo.toml");
|
||||
/// std::cout << tbl["a"] << "\n";
|
||||
/// \ecpp
|
||||
///
|
||||
/// \out
|
||||
/// 3
|
||||
/// \eout
|
||||
///
|
||||
/// \param doc The TOML document to parse. Must be valid UTF-8.
|
||||
/// \param source_path The path used to initialize each node's `source().path`.
|
||||
/// If you don't have a path (or you have no intention of using paths in diagnostics)
|
||||
/// then this parameter can safely be left blank.
|
||||
///
|
||||
/// \returns \conditional_return{With exceptions}
|
||||
/// A toml::table.
|
||||
/// \conditional_return{Without exceptions}
|
||||
/// A toml::parse_result.
|
||||
TOML_NODISCARD
|
||||
TOML_EXPORTED_FREE_FUNCTION
|
||||
parse_result TOML_CALLCONV parse(std::u8string_view doc, std::string && source_path);
|
||||
|
||||
/// \brief Parses a TOML document from a file.
|
||||
///
|
||||
/// \detail \cpp
|
||||
/// toml::parse_result get_foo_toml()
|
||||
/// {
|
||||
/// return toml::parse_file(u8"foo.toml");
|
||||
/// }
|
||||
/// \ecpp
|
||||
///
|
||||
/// \param file_path The TOML document to parse. Must be valid UTF-8.
|
||||
///
|
||||
/// \returns \conditional_return{With exceptions}
|
||||
/// A toml::table.
|
||||
/// \conditional_return{Without exceptions}
|
||||
/// A toml::parse_result.
|
||||
TOML_NODISCARD
|
||||
TOML_EXPORTED_FREE_FUNCTION
|
||||
parse_result TOML_CALLCONV parse_file(std::u8string_view file_path);
|
||||
|
||||
#endif // TOML_HAS_CHAR8
|
||||
|
||||
#if TOML_ENABLE_WINDOWS_COMPAT
|
||||
|
||||
/// \brief Parses a TOML document from a string view.
|
||||
///
|
||||
/// \availability This overload is only available when #TOML_ENABLE_WINDOWS_COMPAT is enabled.
|
||||
///
|
||||
/// \detail \cpp
|
||||
/// auto tbl = toml::parse("a = 3"sv, L"foo.toml");
|
||||
/// std::cout << tbl["a"] << "\n";
|
||||
/// \ecpp
|
||||
///
|
||||
/// \out
|
||||
/// 3
|
||||
/// \eout
|
||||
///
|
||||
/// \param doc The TOML document to parse. Must be valid UTF-8.
|
||||
/// \param source_path The path used to initialize each node's `source().path`.
|
||||
/// If you don't have a path (or you have no intention of using paths in diagnostics)
|
||||
/// then this parameter can safely be left blank.
|
||||
///
|
||||
/// \returns \conditional_return{With exceptions}
|
||||
/// A toml::table.
|
||||
/// \conditional_return{Without exceptions}
|
||||
/// A toml::parse_result.
|
||||
TOML_NODISCARD
|
||||
TOML_EXPORTED_FREE_FUNCTION
|
||||
parse_result TOML_CALLCONV parse(std::string_view doc, std::wstring_view source_path);
|
||||
|
||||
/// \brief Parses a TOML document from a stream.
|
||||
///
|
||||
/// \availability This overload is only available when #TOML_ENABLE_WINDOWS_COMPAT is enabled.
|
||||
///
|
||||
/// \detail \cpp
|
||||
/// std::stringstream ss;
|
||||
/// ss << "a = 3"sv;
|
||||
///
|
||||
/// auto tbl = toml::parse(ss);
|
||||
/// std::cout << tbl["a"] << "\n";
|
||||
/// \ecpp
|
||||
///
|
||||
/// \out
|
||||
/// 3
|
||||
/// \eout
|
||||
///
|
||||
/// \param doc The TOML document to parse. Must be valid UTF-8.
|
||||
/// \param source_path The path used to initialize each node's `source().path`.
|
||||
/// If you don't have a path (or you have no intention of using paths in diagnostics)
|
||||
/// then this parameter can safely be left blank.
|
||||
///
|
||||
/// \returns \conditional_return{With exceptions}
|
||||
/// A toml::table.
|
||||
/// \conditional_return{Without exceptions}
|
||||
/// A toml::parse_result.
|
||||
TOML_NODISCARD
|
||||
TOML_EXPORTED_FREE_FUNCTION
|
||||
parse_result TOML_CALLCONV parse(std::istream & doc, std::wstring_view source_path);
|
||||
|
||||
/// \brief Parses a TOML document from a file.
|
||||
///
|
||||
/// \availability This overload is only available when #TOML_ENABLE_WINDOWS_COMPAT is enabled.
|
||||
///
|
||||
/// \detail \cpp
|
||||
/// toml::parse_result get_foo_toml()
|
||||
/// {
|
||||
/// return toml::parse_file(L"foo.toml");
|
||||
/// }
|
||||
/// \ecpp
|
||||
///
|
||||
/// \param file_path The TOML document to parse. Must be valid UTF-8.
|
||||
///
|
||||
/// \returns \conditional_return{With exceptions}
|
||||
/// A toml::table.
|
||||
/// \conditional_return{Without exceptions}
|
||||
/// A toml::parse_result.
|
||||
TOML_NODISCARD
|
||||
TOML_EXPORTED_FREE_FUNCTION
|
||||
parse_result TOML_CALLCONV parse_file(std::wstring_view file_path);
|
||||
|
||||
#endif // TOML_ENABLE_WINDOWS_COMPAT
|
||||
|
||||
#if TOML_HAS_CHAR8 && TOML_ENABLE_WINDOWS_COMPAT
|
||||
|
||||
/// \brief Parses a TOML document from a char8_t string view.
|
||||
///
|
||||
/// \availability This overload is only available when #TOML_ENABLE_WINDOWS_COMPAT is enabled.
|
||||
///
|
||||
/// \detail \cpp
|
||||
/// auto tbl = toml::parse(u8"a = 3"sv, L"foo.toml");
|
||||
/// std::cout << tbl["a"] << "\n";
|
||||
/// \ecpp
|
||||
///
|
||||
/// \out
|
||||
/// 3
|
||||
/// \eout
|
||||
///
|
||||
/// \param doc The TOML document to parse. Must be valid UTF-8.
|
||||
/// \param source_path The path used to initialize each node's `source().path`.
|
||||
/// If you don't have a path (or you have no intention of using paths in diagnostics)
|
||||
/// then this parameter can safely be left blank.
|
||||
///
|
||||
/// \returns \conditional_return{With exceptions}
|
||||
/// A toml::table.
|
||||
/// \conditional_return{Without exceptions}
|
||||
/// A toml::parse_result.
|
||||
TOML_NODISCARD
|
||||
TOML_EXPORTED_FREE_FUNCTION
|
||||
parse_result TOML_CALLCONV parse(std::u8string_view doc, std::wstring_view source_path);
|
||||
|
||||
#endif // TOML_HAS_CHAR8 && TOML_ENABLE_WINDOWS_COMPAT
|
||||
|
||||
/// \brief Parses a TOML document from a stream.
|
||||
///
|
||||
/// \detail \cpp
|
||||
/// std::stringstream ss;
|
||||
/// ss << "a = 3"sv;
|
||||
///
|
||||
/// auto tbl = toml::parse(ss);
|
||||
/// std::cout << tbl["a"] << "\n";
|
||||
/// \ecpp
|
||||
///
|
||||
/// \out
|
||||
/// 3
|
||||
/// \eout
|
||||
///
|
||||
/// \param doc The TOML document to parse. Must be valid UTF-8.
|
||||
/// \param source_path The path used to initialize each node's `source().path`.
|
||||
/// If you don't have a path (or you have no intention of using paths in diagnostics)
|
||||
/// then this parameter can safely be left blank.
|
||||
///
|
||||
/// \returns \conditional_return{With exceptions}
|
||||
/// A toml::table.
|
||||
/// \conditional_return{Without exceptions}
|
||||
/// A toml::parse_result.
|
||||
TOML_NODISCARD
|
||||
TOML_EXPORTED_FREE_FUNCTION
|
||||
parse_result TOML_CALLCONV parse(std::istream & doc, std::string_view source_path = {});
|
||||
|
||||
/// \brief Parses a TOML document from a stream.
|
||||
///
|
||||
/// \detail \cpp
|
||||
/// std::stringstream ss;
|
||||
/// ss << "a = 3"sv;
|
||||
///
|
||||
/// auto tbl = toml::parse(ss, "foo.toml");
|
||||
/// std::cout << tbl["a"] << "\n";
|
||||
/// \ecpp
|
||||
///
|
||||
/// \out
|
||||
/// 3
|
||||
/// \eout
|
||||
///
|
||||
/// \param doc The TOML document to parse. Must be valid UTF-8.
|
||||
/// \param source_path The path used to initialize each node's `source().path`.
|
||||
/// If you don't have a path (or you have no intention of using paths in diagnostics)
|
||||
/// then this parameter can safely be left blank.
|
||||
///
|
||||
/// \returns \conditional_return{With exceptions}
|
||||
/// A toml::table.
|
||||
/// \conditional_return{Without exceptions}
|
||||
/// A toml::parse_result.
|
||||
TOML_NODISCARD
|
||||
TOML_EXPORTED_FREE_FUNCTION
|
||||
parse_result TOML_CALLCONV parse(std::istream & doc, std::string && source_path);
|
||||
|
||||
TOML_ABI_NAMESPACE_END; // TOML_EXCEPTIONS
|
||||
|
||||
inline namespace literals
|
||||
{
|
||||
TOML_ABI_NAMESPACE_BOOL(TOML_EXCEPTIONS, lit_ex, lit_noex);
|
||||
|
||||
/// \brief Parses TOML data from a string literal.
|
||||
///
|
||||
/// \detail \cpp
|
||||
/// using namespace toml::literals;
|
||||
///
|
||||
/// auto tbl = "a = 3"_toml;
|
||||
/// std::cout << tbl["a"] << "\n";
|
||||
/// \ecpp
|
||||
///
|
||||
/// \out
|
||||
/// 3
|
||||
/// \eout
|
||||
///
|
||||
/// \param str The string data. Must be valid UTF-8.
|
||||
/// \param len The string length.
|
||||
///
|
||||
/// \returns \conditional_return{With exceptions}
|
||||
/// A toml::table.
|
||||
/// \conditional_return{Without exceptions}
|
||||
/// A toml::parse_result.
|
||||
TOML_NODISCARD
|
||||
TOML_ALWAYS_INLINE
|
||||
parse_result operator"" _toml(const char* str, size_t len)
|
||||
{
|
||||
return parse(std::string_view{ str, len });
|
||||
}
|
||||
|
||||
#if TOML_HAS_CHAR8
|
||||
|
||||
/// \brief Parses TOML data from a UTF-8 string literal.
|
||||
///
|
||||
/// \detail \cpp
|
||||
/// using namespace toml::literals;
|
||||
///
|
||||
/// auto tbl = u8"a = 3"_toml;
|
||||
/// std::cout << tbl["a"] << "\n";
|
||||
/// \ecpp
|
||||
///
|
||||
/// \out
|
||||
/// 3
|
||||
/// \eout
|
||||
///
|
||||
/// \param str The string data. Must be valid UTF-8.
|
||||
/// \param len The string length.
|
||||
///
|
||||
/// \returns \conditional_return{With exceptions}
|
||||
/// A toml::table.
|
||||
/// \conditional_return{Without exceptions}
|
||||
/// A toml::parse_result.
|
||||
TOML_NODISCARD
|
||||
TOML_ALWAYS_INLINE
|
||||
parse_result operator"" _toml(const char8_t* str, size_t len)
|
||||
{
|
||||
return parse(std::u8string_view{ str, len });
|
||||
}
|
||||
|
||||
#endif // TOML_HAS_CHAR8
|
||||
|
||||
TOML_ABI_NAMESPACE_END; // TOML_EXCEPTIONS
|
||||
}
|
||||
}
|
||||
TOML_NAMESPACE_END;
|
||||
|
||||
#include "header_end.hpp"
|
||||
#endif // TOML_ENABLE_PARSER
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,851 @@
|
||||
//# This file is a part of toml++ and is subject to the the terms of the MIT license.
|
||||
//# Copyright (c) Mark Gillard <mark.gillard@outlook.com.au>
|
||||
//# See https://github.com/marzer/tomlplusplus/blob/master/LICENSE for the full license text.
|
||||
// SPDX-License-Identifier: MIT
|
||||
#pragma once
|
||||
|
||||
#include "forward_declarations.hpp"
|
||||
#include "std_vector.hpp"
|
||||
#include "header_start.hpp"
|
||||
|
||||
TOML_NAMESPACE_START
|
||||
{
|
||||
/// \brief Indicates type of path component, either a key, an index in an array, or invalid
|
||||
enum class TOML_CLOSED_ENUM path_component_type : uint8_t
|
||||
{
|
||||
key = 0x1,
|
||||
array_index = 0x2
|
||||
};
|
||||
|
||||
/// \brief Represents a single component of a complete 'TOML-path': either a key or an array index
|
||||
class TOML_EXPORTED_CLASS path_component
|
||||
{
|
||||
/// \cond
|
||||
struct storage_t
|
||||
{
|
||||
static constexpr size_t size =
|
||||
(sizeof(size_t) < sizeof(std::string) ? sizeof(std::string) : sizeof(size_t));
|
||||
static constexpr size_t align =
|
||||
(alignof(size_t) < alignof(std::string) ? alignof(std::string) : alignof(size_t));
|
||||
|
||||
alignas(align) unsigned char bytes[size];
|
||||
};
|
||||
alignas(storage_t::align) mutable storage_t value_storage_;
|
||||
|
||||
path_component_type type_;
|
||||
|
||||
TOML_PURE_GETTER
|
||||
TOML_EXPORTED_STATIC_FUNCTION
|
||||
static bool TOML_CALLCONV equal(const path_component&, const path_component&) noexcept;
|
||||
|
||||
template <typename Type>
|
||||
TOML_PURE_INLINE_GETTER
|
||||
static Type* get_as(storage_t& s) noexcept
|
||||
{
|
||||
return TOML_LAUNDER(reinterpret_cast<Type*>(s.bytes));
|
||||
}
|
||||
|
||||
static void store_key(std::string_view key, storage_t& storage_)
|
||||
{
|
||||
::new (static_cast<void*>(storage_.bytes)) std::string{ key };
|
||||
}
|
||||
|
||||
static void store_index(size_t index, storage_t& storage_) noexcept
|
||||
{
|
||||
::new (static_cast<void*>(storage_.bytes)) std::size_t{ index };
|
||||
}
|
||||
|
||||
void destroy() noexcept
|
||||
{
|
||||
if (type_ == path_component_type::key)
|
||||
get_as<std::string>(value_storage_)->~basic_string();
|
||||
}
|
||||
|
||||
TOML_NODISCARD
|
||||
size_t& index_ref() noexcept
|
||||
{
|
||||
TOML_ASSERT_ASSUME(type_ == path_component_type::array_index);
|
||||
return *get_as<size_t>(value_storage_);
|
||||
}
|
||||
|
||||
TOML_NODISCARD
|
||||
std::string& key_ref() noexcept
|
||||
{
|
||||
TOML_ASSERT_ASSUME(type_ == path_component_type::key);
|
||||
return *get_as<std::string>(value_storage_);
|
||||
}
|
||||
/// \endcond
|
||||
|
||||
public:
|
||||
/// \brief Default constructor (creates an empty key).
|
||||
TOML_NODISCARD_CTOR
|
||||
TOML_EXPORTED_MEMBER_FUNCTION
|
||||
path_component();
|
||||
|
||||
/// \brief Constructor for a path component that is an array index
|
||||
TOML_NODISCARD_CTOR
|
||||
TOML_EXPORTED_MEMBER_FUNCTION
|
||||
path_component(size_t index) noexcept;
|
||||
|
||||
/// \brief Constructor for a path component that is a key string
|
||||
TOML_NODISCARD_CTOR
|
||||
TOML_EXPORTED_MEMBER_FUNCTION
|
||||
path_component(std::string_view key);
|
||||
|
||||
#if TOML_ENABLE_WINDOWS_COMPAT
|
||||
|
||||
/// \brief Constructor for a path component that is a key string
|
||||
///
|
||||
/// \availability This constructor is only available when #TOML_ENABLE_WINDOWS_COMPAT is enabled.
|
||||
TOML_NODISCARD_CTOR
|
||||
TOML_EXPORTED_MEMBER_FUNCTION
|
||||
path_component(std::wstring_view key);
|
||||
|
||||
#endif
|
||||
|
||||
/// \brief Copy constructor.
|
||||
TOML_NODISCARD_CTOR
|
||||
TOML_EXPORTED_MEMBER_FUNCTION
|
||||
path_component(const path_component& pc);
|
||||
|
||||
/// \brief Move constructor.
|
||||
TOML_NODISCARD_CTOR
|
||||
TOML_EXPORTED_MEMBER_FUNCTION
|
||||
path_component(path_component&& pc) noexcept;
|
||||
|
||||
/// \brief Copy-assignment operator.
|
||||
TOML_EXPORTED_MEMBER_FUNCTION
|
||||
path_component& operator=(const path_component& rhs);
|
||||
|
||||
/// \brief Move-assignment operator.
|
||||
TOML_EXPORTED_MEMBER_FUNCTION
|
||||
path_component& operator=(path_component&& rhs) noexcept;
|
||||
|
||||
/// \brief Assigns an array index to this path component.
|
||||
TOML_EXPORTED_MEMBER_FUNCTION
|
||||
path_component& operator=(size_t new_index) noexcept;
|
||||
|
||||
/// \brief Assigns a path key to this path component.
|
||||
TOML_EXPORTED_MEMBER_FUNCTION
|
||||
path_component& operator=(std::string_view new_key);
|
||||
|
||||
#if TOML_ENABLE_WINDOWS_COMPAT
|
||||
|
||||
/// \brief Assigns a path key to this path component.
|
||||
///
|
||||
/// \availability This overload is only available when #TOML_ENABLE_WINDOWS_COMPAT is enabled.
|
||||
TOML_EXPORTED_MEMBER_FUNCTION
|
||||
path_component& operator=(std::wstring_view new_key);
|
||||
|
||||
#endif
|
||||
|
||||
/// \brief Destructor.
|
||||
~path_component() noexcept
|
||||
{
|
||||
destroy();
|
||||
}
|
||||
|
||||
/// \name Array index accessors
|
||||
/// \warning It is undefined behaviour to call these functions when the path component does not represent an array index.
|
||||
/// Check #type() to determine the component's value type.
|
||||
/// @{
|
||||
|
||||
/// \brief Returns the array index (const lvalue overload).
|
||||
TOML_PURE_GETTER
|
||||
size_t index() const noexcept
|
||||
{
|
||||
TOML_ASSERT_ASSUME(type_ == path_component_type::array_index);
|
||||
return *get_as<const size_t>(value_storage_);
|
||||
}
|
||||
|
||||
/// \brief Returns the array index (const lvalue).
|
||||
TOML_PURE_INLINE_GETTER
|
||||
explicit operator size_t() const noexcept
|
||||
{
|
||||
return index();
|
||||
}
|
||||
|
||||
/// @}
|
||||
|
||||
/// \name Key accessors
|
||||
/// \warning It is undefined behaviour to call these functions when the path component does not represent a key.
|
||||
/// Check #type() to determine the component's value type.
|
||||
/// @{
|
||||
|
||||
/// \brief Returns the key string.
|
||||
TOML_PURE_GETTER
|
||||
const std::string& key() const noexcept
|
||||
{
|
||||
TOML_ASSERT_ASSUME(type_ == path_component_type::key);
|
||||
return *get_as<const std::string>(value_storage_);
|
||||
}
|
||||
|
||||
/// \brief Returns the key string.
|
||||
TOML_PURE_INLINE_GETTER
|
||||
explicit operator const std::string&() const noexcept
|
||||
{
|
||||
return key();
|
||||
}
|
||||
|
||||
/// @}
|
||||
|
||||
/// \brief Retrieve the type of this path component, either path_component::key or path_component::array_index
|
||||
TOML_PURE_INLINE_GETTER
|
||||
path_component_type type() const noexcept
|
||||
{
|
||||
return type_;
|
||||
}
|
||||
|
||||
/// \name Equality
|
||||
/// @{
|
||||
|
||||
/// \brief Returns true if two path components represent the same key or array index.
|
||||
TOML_PURE_INLINE_GETTER
|
||||
friend bool operator==(const path_component& lhs, const path_component& rhs) noexcept
|
||||
{
|
||||
return equal(lhs, rhs);
|
||||
}
|
||||
|
||||
/// \brief Returns true if two path components do not represent the same key or array index.
|
||||
TOML_PURE_INLINE_GETTER
|
||||
friend bool operator!=(const path_component& lhs, const path_component& rhs) noexcept
|
||||
{
|
||||
return !equal(lhs, rhs);
|
||||
}
|
||||
|
||||
/// @}
|
||||
};
|
||||
|
||||
/// \brief A TOML path.
|
||||
///
|
||||
/// \detail This type parses and represents a path to a TOML node. It validates
|
||||
/// the syntax of the path but does not ensure that the path refers to
|
||||
/// a valid node in any particular TOML document. If parsing fails,
|
||||
/// the object will evaluate as 'falsy', and will be empty.
|
||||
///
|
||||
/// \cpp
|
||||
/// toml::path the_path("animals.cats[1]");
|
||||
///
|
||||
/// // can use with tbl.at_path or operator[]
|
||||
/// std::cout << "second cat: " << tbl[the_path] << "\n";
|
||||
/// std::cout << "cats: " << tbl.at_path(the_path.parent_path()) << "\n";
|
||||
/// \ecpp
|
||||
///
|
||||
/// \out
|
||||
/// second cat: lion
|
||||
/// cats: ['tiger', 'lion', 'puma']
|
||||
/// \eout
|
||||
class TOML_EXPORTED_CLASS path
|
||||
{
|
||||
private:
|
||||
/// \cond
|
||||
|
||||
std::vector<path_component> components_;
|
||||
|
||||
TOML_EXPORTED_MEMBER_FUNCTION
|
||||
void print_to(std::ostream&) const;
|
||||
|
||||
TOML_PURE_GETTER
|
||||
TOML_EXPORTED_STATIC_FUNCTION
|
||||
static bool TOML_CALLCONV equal(const path&, const path&) noexcept;
|
||||
|
||||
/// \endcond
|
||||
|
||||
public:
|
||||
/// \brief Default constructor.
|
||||
TOML_NODISCARD_CTOR
|
||||
path() noexcept = default;
|
||||
|
||||
/// \brief Construct a path by parsing from a string.
|
||||
TOML_NODISCARD_CTOR
|
||||
TOML_EXPORTED_MEMBER_FUNCTION
|
||||
explicit path(std::string_view);
|
||||
|
||||
#if TOML_ENABLE_WINDOWS_COMPAT
|
||||
|
||||
/// \brief Construct a path by parsing from a string.
|
||||
///
|
||||
/// \availability This constructor is only available when #TOML_ENABLE_WINDOWS_COMPAT is enabled.
|
||||
TOML_NODISCARD_CTOR
|
||||
TOML_EXPORTED_MEMBER_FUNCTION
|
||||
explicit path(std::wstring_view);
|
||||
|
||||
#endif
|
||||
|
||||
/// \brief Default destructor.
|
||||
~path() noexcept = default;
|
||||
|
||||
/// \brief Copy constructor.
|
||||
TOML_NODISCARD_CTOR
|
||||
path(const path&) = default;
|
||||
|
||||
/// \brief Move constructor.
|
||||
TOML_NODISCARD_CTOR
|
||||
path(path&&) noexcept = default;
|
||||
|
||||
/// \brief Returns the number of components in the path.
|
||||
TOML_PURE_INLINE_GETTER
|
||||
size_t size() const noexcept
|
||||
{
|
||||
return components_.size();
|
||||
}
|
||||
|
||||
/// \brief Returns true if the path has one or more components.
|
||||
TOML_PURE_INLINE_GETTER
|
||||
explicit operator bool() const noexcept
|
||||
{
|
||||
return !components_.empty();
|
||||
}
|
||||
|
||||
/// \brief Whether (true) or not (false) the path is empty
|
||||
TOML_PURE_INLINE_GETTER
|
||||
bool empty() const noexcept
|
||||
{
|
||||
return components_.empty();
|
||||
}
|
||||
|
||||
/// \brief Fetch a path component by index.
|
||||
TOML_PURE_INLINE_GETTER
|
||||
path_component& operator[](size_t index) noexcept
|
||||
{
|
||||
TOML_ASSERT(index < size());
|
||||
return components_[index];
|
||||
}
|
||||
|
||||
/// \brief Fetch a path component by index (const overload).
|
||||
TOML_PURE_INLINE_GETTER
|
||||
const path_component& operator[](size_t index) const noexcept
|
||||
{
|
||||
TOML_ASSERT(index < size());
|
||||
return components_[index];
|
||||
}
|
||||
|
||||
/// \name Assignment
|
||||
/// @{
|
||||
|
||||
/// \brief Copy-assignment operator.
|
||||
path& operator=(const path&) = default;
|
||||
|
||||
/// \brief Move-assignment operator.
|
||||
path& operator=(path&&) noexcept = default;
|
||||
|
||||
/// \brief Replaces the contents of the path by parsing from a string.
|
||||
TOML_EXPORTED_MEMBER_FUNCTION
|
||||
path& operator=(std::string_view);
|
||||
|
||||
#if TOML_ENABLE_WINDOWS_COMPAT
|
||||
|
||||
/// \brief Replaces the contents of the path by parsing from a string.
|
||||
///
|
||||
/// \availability This overload is only available when #TOML_ENABLE_WINDOWS_COMPAT is enabled.
|
||||
TOML_EXPORTED_MEMBER_FUNCTION
|
||||
path& operator=(std::wstring_view);
|
||||
|
||||
#endif
|
||||
|
||||
/// \brief Replaces the contents of the path with that of another.
|
||||
TOML_ALWAYS_INLINE
|
||||
path& assign(const path& p)
|
||||
{
|
||||
return *this = p;
|
||||
}
|
||||
|
||||
/// \brief Replaces the contents of the path with that of another.
|
||||
TOML_ALWAYS_INLINE
|
||||
path& assign(path&& p) noexcept
|
||||
{
|
||||
return *this = std::move(p);
|
||||
}
|
||||
|
||||
/// \brief Replaces the contents of the path object by a new path
|
||||
TOML_ALWAYS_INLINE
|
||||
path& assign(std::string_view str)
|
||||
{
|
||||
return *this = str;
|
||||
}
|
||||
|
||||
#if TOML_ENABLE_WINDOWS_COMPAT
|
||||
|
||||
/// \brief Replaces the contents of the path object by a new path
|
||||
///
|
||||
/// \availability This overload is only available when #TOML_ENABLE_WINDOWS_COMPAT is enabled.
|
||||
TOML_ALWAYS_INLINE
|
||||
path& assign(std::wstring_view str)
|
||||
{
|
||||
return *this = str;
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
/// @}
|
||||
|
||||
/// \name Appending
|
||||
/// @{
|
||||
|
||||
/// \brief Appends another path onto the end of this one.
|
||||
TOML_EXPORTED_MEMBER_FUNCTION
|
||||
path& operator+=(const path&);
|
||||
|
||||
/// \brief Appends another path onto the end of this one.
|
||||
TOML_EXPORTED_MEMBER_FUNCTION
|
||||
path& operator+=(path&&);
|
||||
|
||||
/// \brief Parses a path and appends it onto the end of this one.
|
||||
TOML_EXPORTED_MEMBER_FUNCTION
|
||||
path& operator+=(std::string_view);
|
||||
|
||||
#if TOML_ENABLE_WINDOWS_COMPAT
|
||||
|
||||
/// \brief Parses a path and appends it onto the end of this one.
|
||||
///
|
||||
/// \availability This overload is only available when #TOML_ENABLE_WINDOWS_COMPAT is enabled.
|
||||
TOML_EXPORTED_MEMBER_FUNCTION
|
||||
path& operator+=(std::wstring_view);
|
||||
|
||||
#endif
|
||||
|
||||
/// \brief Appends another path onto the end of this one.
|
||||
TOML_ALWAYS_INLINE
|
||||
path& append(const path& p)
|
||||
{
|
||||
return *this += p;
|
||||
}
|
||||
|
||||
/// \brief Appends another path onto the end of this one.
|
||||
TOML_ALWAYS_INLINE
|
||||
path& append(path&& p)
|
||||
{
|
||||
return *this += std::move(p);
|
||||
}
|
||||
|
||||
/// \brief Parses a path and appends it onto the end of this one.
|
||||
TOML_ALWAYS_INLINE
|
||||
path& append(std::string_view str)
|
||||
{
|
||||
return *this += str;
|
||||
}
|
||||
|
||||
#if TOML_ENABLE_WINDOWS_COMPAT
|
||||
|
||||
/// \brief Parses a path and appends it onto the end of this one.
|
||||
///
|
||||
/// \availability This overload is only available when #TOML_ENABLE_WINDOWS_COMPAT is enabled.
|
||||
TOML_ALWAYS_INLINE
|
||||
path& append(std::wstring_view str)
|
||||
{
|
||||
return *this += str;
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
/// @}
|
||||
|
||||
/// \name Prepending
|
||||
/// @{
|
||||
|
||||
/// \brief Prepends another path onto the beginning of this one.
|
||||
TOML_EXPORTED_MEMBER_FUNCTION
|
||||
path& prepend(const path&);
|
||||
|
||||
/// \brief Prepends another path onto the beginning of this one.
|
||||
TOML_EXPORTED_MEMBER_FUNCTION
|
||||
path& prepend(path&&);
|
||||
|
||||
/// \brief Parses a path and prepends it onto the beginning of this one.
|
||||
TOML_EXPORTED_MEMBER_FUNCTION
|
||||
path& prepend(std::string_view);
|
||||
|
||||
#if TOML_ENABLE_WINDOWS_COMPAT
|
||||
|
||||
/// \brief Parses a path and prepends it onto the beginning of this one.
|
||||
///
|
||||
/// \availability This overload is only available when #TOML_ENABLE_WINDOWS_COMPAT is enabled.
|
||||
TOML_EXPORTED_MEMBER_FUNCTION
|
||||
path& prepend(std::wstring_view);
|
||||
|
||||
#endif
|
||||
|
||||
/// @}
|
||||
|
||||
/// \name Concatenation
|
||||
/// @{
|
||||
|
||||
/// \brief Concatenates two paths.
|
||||
TOML_NODISCARD
|
||||
friend path operator+(const path& lhs, const path& rhs)
|
||||
{
|
||||
path result = lhs;
|
||||
result += rhs;
|
||||
return result;
|
||||
}
|
||||
|
||||
/// \brief Concatenates two paths.
|
||||
TOML_NODISCARD
|
||||
friend path operator+(const path& lhs, std::string_view rhs)
|
||||
{
|
||||
path result = lhs;
|
||||
result += rhs;
|
||||
return result;
|
||||
}
|
||||
|
||||
/// \brief Concatenates two paths.
|
||||
TOML_NODISCARD
|
||||
friend path operator+(std::string_view lhs, const path& rhs)
|
||||
{
|
||||
path result = rhs;
|
||||
result.prepend(lhs);
|
||||
return result;
|
||||
}
|
||||
|
||||
#if TOML_ENABLE_WINDOWS_COMPAT
|
||||
|
||||
/// \brief Concatenates two paths.
|
||||
///
|
||||
/// \availability This overload is only available when #TOML_ENABLE_WINDOWS_COMPAT is enabled.
|
||||
TOML_NODISCARD
|
||||
friend path operator+(const path& lhs, std::wstring_view rhs)
|
||||
{
|
||||
path result = lhs;
|
||||
result += rhs;
|
||||
return result;
|
||||
}
|
||||
|
||||
/// \brief Concatenates two paths.
|
||||
///
|
||||
/// \availability This overload is only available when #TOML_ENABLE_WINDOWS_COMPAT is enabled.
|
||||
TOML_NODISCARD
|
||||
friend path operator+(std::wstring_view lhs, const path& rhs)
|
||||
{
|
||||
path result = rhs;
|
||||
result.prepend(lhs);
|
||||
return result;
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
/// @}
|
||||
|
||||
/// \name String conversion
|
||||
/// @{
|
||||
|
||||
/// \brief Prints the string representation of a #toml::path out to a stream.
|
||||
TOML_ALWAYS_INLINE
|
||||
friend std::ostream& operator<<(std::ostream& os, const path& rhs)
|
||||
{
|
||||
rhs.print_to(os);
|
||||
return os;
|
||||
}
|
||||
|
||||
/// \brief Returns a string representation of this path.
|
||||
TOML_NODISCARD
|
||||
TOML_EXPORTED_MEMBER_FUNCTION
|
||||
std::string str() const;
|
||||
|
||||
/// \brief Returns a string representation of this path.
|
||||
TOML_NODISCARD
|
||||
TOML_ALWAYS_INLINE
|
||||
explicit operator std::string() const
|
||||
{
|
||||
return str();
|
||||
}
|
||||
|
||||
#if TOML_ENABLE_WINDOWS_COMPAT
|
||||
|
||||
/// \brief Returns a string representation of this path.
|
||||
///
|
||||
/// \availability This overload is only available when #TOML_ENABLE_WINDOWS_COMPAT is enabled.
|
||||
TOML_NODISCARD
|
||||
TOML_EXPORTED_MEMBER_FUNCTION
|
||||
std::wstring wide_str() const;
|
||||
|
||||
/// \brief Returns a string representation of this path.
|
||||
///
|
||||
/// \availability This overload is only available when #TOML_ENABLE_WINDOWS_COMPAT is enabled.
|
||||
TOML_NODISCARD
|
||||
TOML_ALWAYS_INLINE
|
||||
explicit operator std::wstring() const
|
||||
{
|
||||
return wide_str();
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
/// @}
|
||||
|
||||
/// \name Equality
|
||||
/// @{
|
||||
|
||||
/// \brief Returns whether two paths are the same.
|
||||
TOML_PURE_INLINE_GETTER
|
||||
friend bool operator==(const path& lhs, const path& rhs) noexcept
|
||||
{
|
||||
return equal(lhs, rhs);
|
||||
}
|
||||
|
||||
/// \brief Returns whether two paths are not the same.
|
||||
TOML_PURE_INLINE_GETTER
|
||||
friend bool operator!=(const path& lhs, const path& rhs) noexcept
|
||||
{
|
||||
return !equal(lhs, rhs);
|
||||
}
|
||||
|
||||
/// \brief Returns whether two paths are the same.
|
||||
TOML_NODISCARD
|
||||
TOML_ALWAYS_INLINE
|
||||
friend bool operator==(const path& lhs, std::string_view rhs)
|
||||
{
|
||||
return lhs == path{ rhs };
|
||||
}
|
||||
|
||||
/// \brief Returns whether two paths are the same.
|
||||
TOML_NODISCARD
|
||||
TOML_ALWAYS_INLINE
|
||||
friend bool operator==(std::string_view lhs, const path& rhs)
|
||||
{
|
||||
return rhs == lhs;
|
||||
}
|
||||
|
||||
/// \brief Returns whether two paths are not the same.
|
||||
TOML_NODISCARD
|
||||
TOML_ALWAYS_INLINE
|
||||
friend bool operator!=(const path& lhs, std::string_view rhs)
|
||||
{
|
||||
return lhs != path{ rhs };
|
||||
}
|
||||
|
||||
/// \brief Returns whether two paths are not the same.
|
||||
TOML_NODISCARD
|
||||
TOML_ALWAYS_INLINE
|
||||
friend bool operator!=(std::string_view lhs, const path& rhs)
|
||||
{
|
||||
return rhs != lhs;
|
||||
}
|
||||
|
||||
#if TOML_ENABLE_WINDOWS_COMPAT
|
||||
|
||||
/// \brief Returns whether two paths are the same.
|
||||
///
|
||||
/// \availability This overload is only available when #TOML_ENABLE_WINDOWS_COMPAT is enabled.
|
||||
TOML_NODISCARD
|
||||
TOML_ALWAYS_INLINE
|
||||
friend bool operator==(const path& lhs, std::wstring_view rhs)
|
||||
{
|
||||
return lhs == path{ rhs };
|
||||
}
|
||||
|
||||
/// \brief Returns whether two paths are the same.
|
||||
///
|
||||
/// \availability This overload is only available when #TOML_ENABLE_WINDOWS_COMPAT is enabled.
|
||||
TOML_NODISCARD
|
||||
TOML_ALWAYS_INLINE
|
||||
friend bool operator==(std::wstring_view lhs, const path& rhs)
|
||||
{
|
||||
return rhs == lhs;
|
||||
}
|
||||
|
||||
/// \brief Returns whether two paths are not the same.
|
||||
///
|
||||
/// \availability This overload is only available when #TOML_ENABLE_WINDOWS_COMPAT is enabled.
|
||||
TOML_NODISCARD
|
||||
TOML_ALWAYS_INLINE
|
||||
friend bool operator!=(const path& lhs, std::wstring_view rhs)
|
||||
{
|
||||
return lhs != path{ rhs };
|
||||
}
|
||||
|
||||
/// \brief Returns whether two paths are not the same.
|
||||
///
|
||||
/// \availability This overload is only available when #TOML_ENABLE_WINDOWS_COMPAT is enabled.
|
||||
TOML_NODISCARD
|
||||
TOML_ALWAYS_INLINE
|
||||
friend bool operator!=(std::wstring_view lhs, const path& rhs)
|
||||
{
|
||||
return rhs != lhs;
|
||||
}
|
||||
|
||||
#endif // TOML_ENABLE_WINDOWS_COMPAT
|
||||
|
||||
/// @}
|
||||
|
||||
/// \name Iteration
|
||||
/// @{
|
||||
|
||||
/// An iterator for iterating over the components in the path.
|
||||
/// \see #toml::path_component
|
||||
using iterator = std::vector<path_component>::iterator;
|
||||
|
||||
/// A const iterator for iterating over the components in the path.
|
||||
/// \see #toml::path_component
|
||||
using const_iterator = std::vector<path_component>::const_iterator;
|
||||
|
||||
/// \brief Returns an iterator to the first component in the path.
|
||||
/// \see #toml::path_component
|
||||
TOML_PURE_INLINE_GETTER
|
||||
iterator begin() noexcept
|
||||
{
|
||||
return components_.begin();
|
||||
}
|
||||
|
||||
/// \brief Returns an iterator to one-past-the-last component in the path.
|
||||
/// \see #toml::path_component
|
||||
TOML_PURE_INLINE_GETTER
|
||||
iterator end() noexcept
|
||||
{
|
||||
return components_.end();
|
||||
}
|
||||
|
||||
/// \brief Returns a const iterator to the first component in the path.
|
||||
/// \see #toml::path_component
|
||||
TOML_PURE_INLINE_GETTER
|
||||
const_iterator begin() const noexcept
|
||||
{
|
||||
return components_.begin();
|
||||
}
|
||||
|
||||
/// \brief Returns a const iterator to one-past-the-last component in the path.
|
||||
/// \see #toml::path_component
|
||||
TOML_PURE_INLINE_GETTER
|
||||
const_iterator end() const noexcept
|
||||
{
|
||||
return components_.end();
|
||||
}
|
||||
|
||||
/// \brief Returns a const iterator to the first component in the path.
|
||||
/// \see #toml::path_component
|
||||
TOML_PURE_INLINE_GETTER
|
||||
const_iterator cbegin() const noexcept
|
||||
{
|
||||
return components_.begin();
|
||||
}
|
||||
|
||||
/// \brief Returns a const iterator to one-past-the-last component in the path.
|
||||
/// \see #toml::path_component
|
||||
TOML_PURE_INLINE_GETTER
|
||||
const_iterator cend() const noexcept
|
||||
{
|
||||
return components_.end();
|
||||
}
|
||||
|
||||
/// @}
|
||||
|
||||
/// \name Subpaths and Truncation
|
||||
/// @{
|
||||
|
||||
/// \brief Erases the contents of the path.
|
||||
TOML_EXPORTED_MEMBER_FUNCTION
|
||||
void clear() noexcept;
|
||||
|
||||
/// \brief Removes the number of terminal path components specified by n
|
||||
TOML_EXPORTED_MEMBER_FUNCTION
|
||||
path& truncate(size_t n);
|
||||
|
||||
/// \brief Returns a toml::path object which has had n terminal path components removed
|
||||
TOML_NODISCARD
|
||||
TOML_EXPORTED_MEMBER_FUNCTION
|
||||
path truncated(size_t n) const;
|
||||
|
||||
/// \brief Returns a toml::path object representing the path of the parent node
|
||||
TOML_NODISCARD
|
||||
TOML_EXPORTED_MEMBER_FUNCTION
|
||||
path parent() const;
|
||||
|
||||
/// \brief Returns a toml::path object representing terminal n-parts of a TOML path
|
||||
TOML_NODISCARD
|
||||
TOML_EXPORTED_MEMBER_FUNCTION
|
||||
path leaf(size_t n = 1) const;
|
||||
|
||||
/// \brief Returns a toml::path object that is a specified subpath of the current path, representing the
|
||||
/// range of path components from [start, end).
|
||||
TOML_NODISCARD
|
||||
TOML_EXPORTED_MEMBER_FUNCTION
|
||||
path subpath(const_iterator start, const_iterator end) const;
|
||||
|
||||
/// \brief Returns a toml::path object that is a specified subpath of the current path, representing the
|
||||
/// range of path components with indexes from [start, start + length].
|
||||
TOML_NODISCARD
|
||||
TOML_EXPORTED_MEMBER_FUNCTION
|
||||
path subpath(size_t start, size_t length) const;
|
||||
|
||||
/// @}
|
||||
};
|
||||
|
||||
inline namespace literals
|
||||
{
|
||||
/// \brief Parses a TOML path from a string literal.
|
||||
///
|
||||
/// \detail \cpp
|
||||
/// using namespace toml::literals;
|
||||
///
|
||||
/// auto path = "main.settings.devices[2]"_tpath;
|
||||
/// std::cout << path.parent_path() << "\n";
|
||||
/// \ecpp
|
||||
///
|
||||
/// \out
|
||||
/// main.settings.devices
|
||||
/// \eout
|
||||
///
|
||||
/// \param str The string data.
|
||||
/// \param len The string length.
|
||||
///
|
||||
/// \returns A #toml::path generated from the string literal.
|
||||
TOML_NODISCARD
|
||||
TOML_ALWAYS_INLINE
|
||||
path operator"" _tpath(const char* str, size_t len)
|
||||
{
|
||||
return path(std::string_view{ str, len });
|
||||
}
|
||||
}
|
||||
|
||||
/// \brief Returns a view of the node matching a fully-qualified "TOML path".
|
||||
///
|
||||
/// \detail \cpp
|
||||
/// auto config = toml::parse(R"(
|
||||
///
|
||||
/// [foo]
|
||||
/// bar = [ 0, 1, 2, [ 3 ], { kek = 4 } ]
|
||||
///
|
||||
/// )"sv);
|
||||
///
|
||||
/// toml::path path1("foo.bar[2]");
|
||||
/// toml::path path2("foo.bar[4].kek");
|
||||
/// std::cout << toml::at_path(config, path1) << "\n";
|
||||
/// std::cout << toml::at_path(config, path1.parent_path()) << "\n";
|
||||
/// std::cout << toml::at_path(config, path2) << "\n";
|
||||
/// std::cout << toml::at_path(config, path2.parent_path()) << "\n";
|
||||
/// \ecpp
|
||||
///
|
||||
/// \out
|
||||
/// 2
|
||||
/// [ 0, 1, 2, [ 3 ], { kek = 4 } ]
|
||||
/// 4
|
||||
/// { kek = 4 }
|
||||
/// \eout
|
||||
///
|
||||
///
|
||||
/// \note Keys in paths are interpreted literally, so whitespace (or lack thereof) matters:
|
||||
/// \cpp
|
||||
/// toml::at_path(config, toml::path("foo.bar")) // same as config["foo"]["bar"]
|
||||
/// toml::at_path(config, toml::path("foo. bar")) // same as config["foo"][" bar"]
|
||||
/// toml::at_path(config, toml::path("foo..bar")) // same as config["foo"][""]["bar"]
|
||||
/// toml::at_path(config, toml::path(".foo.bar")) // same as config[""]["foo"]["bar"]
|
||||
/// \ecpp
|
||||
/// <br>
|
||||
/// Additionally, TOML allows '.' (period) characters to appear in keys if they are quoted strings.
|
||||
/// This function makes no allowance for this, instead treating all period characters as sub-table delimiters.
|
||||
///
|
||||
/// \param root The root node from which the path will be traversed.
|
||||
/// \param path The "TOML path" to traverse.
|
||||
TOML_NODISCARD
|
||||
TOML_EXPORTED_FREE_FUNCTION
|
||||
node_view<node> TOML_CALLCONV at_path(node & root, const toml::path& path) noexcept;
|
||||
|
||||
/// \brief Returns a const view of the node matching a fully-qualified "TOML path".
|
||||
///
|
||||
/// \see #toml::at_path(node&, const toml::path& path)
|
||||
TOML_NODISCARD
|
||||
TOML_EXPORTED_FREE_FUNCTION
|
||||
node_view<const node> TOML_CALLCONV at_path(const node& root, const toml::path& path) noexcept;
|
||||
}
|
||||
TOML_NAMESPACE_END;
|
||||
|
||||
#include "header_end.hpp"
|
||||
@@ -0,0 +1,523 @@
|
||||
//# This file is a part of toml++ and is subject to the the terms of the MIT license.
|
||||
//# Copyright (c) Mark Gillard <mark.gillard@outlook.com.au>
|
||||
//# See https://github.com/marzer/tomlplusplus/blob/master/LICENSE for the full license text.
|
||||
// SPDX-License-Identifier: MIT
|
||||
#pragma once
|
||||
|
||||
//# {{
|
||||
#include "preprocessor.hpp"
|
||||
#if !TOML_IMPLEMENTATION
|
||||
#error This is an implementation-only header.
|
||||
#endif
|
||||
//# }}
|
||||
|
||||
#include "path.hpp"
|
||||
#include "at_path.hpp"
|
||||
#include "print_to_stream.hpp"
|
||||
TOML_DISABLE_WARNINGS;
|
||||
#if TOML_INT_CHARCONV
|
||||
#include <charconv>
|
||||
#endif
|
||||
#include <sstream>
|
||||
TOML_ENABLE_WARNINGS;
|
||||
#include "header_start.hpp"
|
||||
|
||||
//#=====================================================================================================================
|
||||
//# toml::path_component
|
||||
//#=====================================================================================================================
|
||||
|
||||
TOML_NAMESPACE_START
|
||||
{
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
path_component::path_component() //
|
||||
: type_{ path_component_type::key }
|
||||
{
|
||||
store_key("", value_storage_);
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
path_component::path_component(size_t index) noexcept //
|
||||
: type_(path_component_type::array_index)
|
||||
{
|
||||
store_index(index, value_storage_);
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
path_component::path_component(std::string_view key) //
|
||||
: type_(path_component_type::key)
|
||||
{
|
||||
store_key(key, value_storage_);
|
||||
}
|
||||
|
||||
#if TOML_ENABLE_WINDOWS_COMPAT
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
path_component::path_component(std::wstring_view key) //
|
||||
: path_component(impl::narrow(key))
|
||||
{}
|
||||
|
||||
#endif
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
path_component::path_component(const path_component& pc) //
|
||||
: type_{ pc.type_ }
|
||||
{
|
||||
if (type_ == path_component_type::array_index)
|
||||
store_index(pc.index(), value_storage_);
|
||||
else
|
||||
store_key(pc.key(), value_storage_);
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
path_component::path_component(path_component && pc) noexcept //
|
||||
: type_{ pc.type_ }
|
||||
{
|
||||
if (type_ == path_component_type::array_index)
|
||||
store_index(pc.index_ref(), value_storage_);
|
||||
else
|
||||
store_key(std::move(pc.key_ref()), value_storage_);
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
path_component& path_component::operator=(const path_component& rhs)
|
||||
{
|
||||
if (type_ != rhs.type_)
|
||||
{
|
||||
destroy();
|
||||
|
||||
type_ = rhs.type_;
|
||||
if (type_ == path_component_type::array_index)
|
||||
store_index(rhs.index(), value_storage_);
|
||||
else
|
||||
store_key(rhs.key(), value_storage_);
|
||||
}
|
||||
else
|
||||
{
|
||||
if (type_ == path_component_type::array_index)
|
||||
index_ref() = rhs.index();
|
||||
else
|
||||
key_ref() = rhs.key();
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
path_component& path_component::operator=(path_component&& rhs) noexcept
|
||||
{
|
||||
if (type_ != rhs.type_)
|
||||
{
|
||||
destroy();
|
||||
|
||||
type_ = rhs.type_;
|
||||
if (type_ == path_component_type::array_index)
|
||||
store_index(rhs.index(), value_storage_);
|
||||
else
|
||||
store_key(std::move(rhs.key_ref()), value_storage_);
|
||||
}
|
||||
else
|
||||
{
|
||||
if (type_ == path_component_type::array_index)
|
||||
index_ref() = rhs.index();
|
||||
else
|
||||
key_ref() = std::move(rhs.key_ref());
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
TOML_PURE_GETTER
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
bool TOML_CALLCONV path_component::equal(const path_component& lhs, const path_component& rhs) noexcept
|
||||
{
|
||||
// Different comparison depending on contents
|
||||
if (lhs.type_ != rhs.type_)
|
||||
return false;
|
||||
|
||||
if (lhs.type_ == path_component_type::array_index)
|
||||
return lhs.index() == rhs.index();
|
||||
else // path_component_type::key
|
||||
return lhs.key() == rhs.key();
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
path_component& path_component::operator=(size_t new_index) noexcept
|
||||
{
|
||||
// If currently a key, string will need to be destroyed regardless
|
||||
destroy();
|
||||
|
||||
type_ = path_component_type::array_index;
|
||||
store_index(new_index, value_storage_);
|
||||
|
||||
return *this;
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
path_component& path_component::operator=(std::string_view new_key)
|
||||
{
|
||||
if (type_ == path_component_type::key)
|
||||
key_ref() = new_key;
|
||||
else
|
||||
{
|
||||
type_ = path_component_type::key;
|
||||
store_key(new_key, value_storage_);
|
||||
}
|
||||
|
||||
return *this;
|
||||
}
|
||||
|
||||
#if TOML_ENABLE_WINDOWS_COMPAT
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
path_component& path_component::operator=(std::wstring_view new_key)
|
||||
{
|
||||
if (type_ == path_component_type::key)
|
||||
key_ref() = impl::narrow(new_key);
|
||||
else
|
||||
{
|
||||
type_ = path_component_type::key;
|
||||
store_key(impl::narrow(new_key), value_storage_);
|
||||
}
|
||||
|
||||
return *this;
|
||||
}
|
||||
|
||||
#endif
|
||||
}
|
||||
TOML_NAMESPACE_END;
|
||||
|
||||
//#=====================================================================================================================
|
||||
//# toml::path
|
||||
//#=====================================================================================================================
|
||||
|
||||
TOML_ANON_NAMESPACE_START
|
||||
{
|
||||
TOML_INTERNAL_LINKAGE
|
||||
bool parse_path_into(std::string_view path_str, std::vector<path_component> & components)
|
||||
{
|
||||
using components_type = std::remove_reference_t<decltype(components)>;
|
||||
|
||||
const auto original_size = components.size();
|
||||
|
||||
static constexpr auto on_key = [](void* data, std::string_view key) -> bool
|
||||
{
|
||||
auto& comps = *static_cast<components_type*>(data);
|
||||
comps.emplace_back(key);
|
||||
return true;
|
||||
};
|
||||
|
||||
static constexpr auto on_index = [](void* data, size_t index) -> bool
|
||||
{
|
||||
auto& comps = *static_cast<components_type*>(data);
|
||||
comps.emplace_back(index);
|
||||
return true;
|
||||
};
|
||||
|
||||
if (!impl::parse_path(path_str, &components, on_key, on_index))
|
||||
{
|
||||
components.resize(original_size);
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
TOML_ANON_NAMESPACE_END;
|
||||
|
||||
TOML_NAMESPACE_START
|
||||
{
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
void path::print_to(std::ostream & os) const
|
||||
{
|
||||
bool root = true;
|
||||
for (const auto& component : components_)
|
||||
{
|
||||
if (component.type() == path_component_type::key) // key
|
||||
{
|
||||
if (!root)
|
||||
impl::print_to_stream(os, '.');
|
||||
impl::print_to_stream(os, component.key());
|
||||
}
|
||||
else if (component.type() == path_component_type::array_index) // array
|
||||
{
|
||||
impl::print_to_stream(os, '[');
|
||||
impl::print_to_stream(os, component.index());
|
||||
impl::print_to_stream(os, ']');
|
||||
}
|
||||
root = false;
|
||||
}
|
||||
}
|
||||
|
||||
TOML_PURE_GETTER
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
bool TOML_CALLCONV path::equal(const path& lhs, const path& rhs) noexcept
|
||||
{
|
||||
return lhs.components_ == rhs.components_;
|
||||
}
|
||||
|
||||
//#=== constructors =================================================
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
path::path(std::string_view str) //
|
||||
{
|
||||
TOML_ANON_NAMESPACE::parse_path_into(str, components_);
|
||||
}
|
||||
|
||||
#if TOML_ENABLE_WINDOWS_COMPAT
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
path::path(std::wstring_view str) //
|
||||
: path(impl::narrow(str))
|
||||
{}
|
||||
|
||||
#endif
|
||||
|
||||
//#=== assignment =================================================
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
path& path::operator=(std::string_view rhs)
|
||||
{
|
||||
components_.clear();
|
||||
TOML_ANON_NAMESPACE::parse_path_into(rhs, components_);
|
||||
return *this;
|
||||
}
|
||||
|
||||
#if TOML_ENABLE_WINDOWS_COMPAT
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
path& path::operator=(std::wstring_view rhs)
|
||||
{
|
||||
return assign(impl::narrow(rhs));
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
//#=== appending =================================================
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
path& path::operator+=(const path& rhs)
|
||||
{
|
||||
components_.insert(components_.cend(), rhs.begin(), rhs.end());
|
||||
return *this;
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
path& path::operator+=(path&& rhs)
|
||||
{
|
||||
components_.insert(components_.end(),
|
||||
std::make_move_iterator(rhs.components_.begin()),
|
||||
std::make_move_iterator(rhs.components_.end()));
|
||||
return *this;
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
path& path::operator+=(std::string_view str)
|
||||
{
|
||||
TOML_ANON_NAMESPACE::parse_path_into(str, components_);
|
||||
return *this;
|
||||
}
|
||||
|
||||
#if TOML_ENABLE_WINDOWS_COMPAT
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
path& path::operator+=(std::wstring_view str)
|
||||
{
|
||||
return *this += impl::narrow(str);
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
//#=== prepending =================================================
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
path& path::prepend(const path& source)
|
||||
{
|
||||
components_.insert(components_.begin(), source.components_.begin(), source.components_.end());
|
||||
return *this;
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
path& path::prepend(path && source)
|
||||
{
|
||||
components_.insert(components_.begin(),
|
||||
std::make_move_iterator(source.components_.begin()),
|
||||
std::make_move_iterator(source.components_.end()));
|
||||
return *this;
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
path& path::prepend(std::string_view source)
|
||||
{
|
||||
return prepend(path{ source });
|
||||
}
|
||||
|
||||
#if TOML_ENABLE_WINDOWS_COMPAT
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
path& path::prepend(std::wstring_view source)
|
||||
{
|
||||
return prepend(impl::narrow(source));
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
//#=== string conversion =================================================
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
std::string path::str() const
|
||||
{
|
||||
if (empty())
|
||||
return "";
|
||||
|
||||
std::ostringstream ss;
|
||||
print_to(ss);
|
||||
return std::move(ss).str();
|
||||
}
|
||||
|
||||
#if TOML_ENABLE_WINDOWS_COMPAT
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
std::wstring path::wide_str() const
|
||||
{
|
||||
return impl::widen(str());
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
//#=== equality and comparison =================================================
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
void path::clear() noexcept
|
||||
{
|
||||
components_.clear();
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
path& path::truncate(size_t n)
|
||||
{
|
||||
n = n > components_.size() ? components_.size() : n;
|
||||
|
||||
auto it_end = components_.end();
|
||||
components_.erase(it_end - static_cast<int>(n), it_end);
|
||||
|
||||
return *this;
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
path path::truncated(size_t n) const
|
||||
{
|
||||
path truncated_path{};
|
||||
|
||||
n = n > components_.size() ? components_.size() : n;
|
||||
|
||||
// Copy all components except one
|
||||
// Need at least two path components to have a parent, since if there is
|
||||
// only one path component, the parent is the root/null path ""
|
||||
truncated_path.components_.insert(truncated_path.components_.begin(),
|
||||
components_.begin(),
|
||||
components_.end() - static_cast<int>(n));
|
||||
|
||||
return truncated_path;
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
path path::parent() const
|
||||
{
|
||||
return truncated(1);
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
path path::leaf(size_t n) const
|
||||
{
|
||||
path leaf_path{};
|
||||
|
||||
n = n > components_.size() ? components_.size() : n;
|
||||
|
||||
if (n > 0)
|
||||
{
|
||||
leaf_path.components_.insert(leaf_path.components_.begin(),
|
||||
components_.end() - static_cast<int>(n),
|
||||
components_.end());
|
||||
}
|
||||
|
||||
return leaf_path;
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
path path::subpath(std::vector<path_component>::const_iterator start,
|
||||
std::vector<path_component>::const_iterator end) const
|
||||
{
|
||||
if (start >= end)
|
||||
return {};
|
||||
|
||||
path subpath;
|
||||
subpath.components_.insert(subpath.components_.begin(), start, end);
|
||||
return subpath;
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
path path::subpath(size_t start, size_t length) const
|
||||
{
|
||||
return subpath(begin() + static_cast<int>(start), begin() + static_cast<int>(start + length));
|
||||
}
|
||||
}
|
||||
TOML_NAMESPACE_END;
|
||||
|
||||
//#=====================================================================================================================
|
||||
//# at_path() overloads for toml::path
|
||||
//#=====================================================================================================================
|
||||
|
||||
TOML_NAMESPACE_START
|
||||
{
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
node_view<node> TOML_CALLCONV at_path(node & root, const toml::path& path) noexcept
|
||||
{
|
||||
// early-exit sanity-checks
|
||||
if (root.is_value())
|
||||
return {};
|
||||
if (auto tbl = root.as_table(); tbl && tbl->empty())
|
||||
return {};
|
||||
if (auto arr = root.as_array(); arr && arr->empty())
|
||||
return {};
|
||||
|
||||
node* current = &root;
|
||||
|
||||
for (const auto& component : path)
|
||||
{
|
||||
auto type = component.type();
|
||||
if (type == path_component_type::array_index)
|
||||
{
|
||||
const auto current_array = current->as<array>();
|
||||
if (!current_array)
|
||||
return {}; // not an array, using array index doesn't work
|
||||
|
||||
current = current_array->get(component.index());
|
||||
}
|
||||
else if (type == path_component_type::key)
|
||||
{
|
||||
const auto current_table = current->as<table>();
|
||||
if (!current_table)
|
||||
return {};
|
||||
|
||||
current = current_table->get(component.key());
|
||||
}
|
||||
else
|
||||
{
|
||||
// Error: invalid component
|
||||
return {};
|
||||
}
|
||||
|
||||
if (!current)
|
||||
return {}; // not found
|
||||
}
|
||||
|
||||
return node_view{ current };
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
node_view<const node> TOML_CALLCONV at_path(const node& root, const toml::path& path) noexcept
|
||||
{
|
||||
return node_view<const node>{ at_path(const_cast<node&>(root), path).node() };
|
||||
}
|
||||
}
|
||||
TOML_NAMESPACE_END;
|
||||
|
||||
#include "header_end.hpp"
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,129 @@
|
||||
//# This file is a part of toml++ and is subject to the the terms of the MIT license.
|
||||
//# Copyright (c) Mark Gillard <mark.gillard@outlook.com.au>
|
||||
//# See https://github.com/marzer/tomlplusplus/blob/master/LICENSE for the full license text.
|
||||
// SPDX-License-Identifier: MIT
|
||||
#pragma once
|
||||
|
||||
#include "std_string.hpp"
|
||||
#include "forward_declarations.hpp"
|
||||
#include "header_start.hpp"
|
||||
|
||||
TOML_IMPL_NAMESPACE_START
|
||||
{
|
||||
// Q: "why does print_to_stream() exist? why not just use ostream::write(), ostream::put() etc?"
|
||||
// A: - I'm using <charconv> to format numerics. Faster and locale-independent.
|
||||
// - I can (potentially) avoid forcing users to drag in <sstream> and <iomanip>.
|
||||
// - Strings in C++. Honestly.
|
||||
|
||||
TOML_EXPORTED_FREE_FUNCTION
|
||||
TOML_ATTR(nonnull)
|
||||
void TOML_CALLCONV print_to_stream(std::ostream&, const char*, size_t);
|
||||
|
||||
TOML_EXPORTED_FREE_FUNCTION
|
||||
void TOML_CALLCONV print_to_stream(std::ostream&, std::string_view);
|
||||
|
||||
TOML_EXPORTED_FREE_FUNCTION
|
||||
void TOML_CALLCONV print_to_stream(std::ostream&, const std::string&);
|
||||
|
||||
TOML_EXPORTED_FREE_FUNCTION
|
||||
void TOML_CALLCONV print_to_stream(std::ostream&, char);
|
||||
|
||||
TOML_EXPORTED_FREE_FUNCTION
|
||||
void TOML_CALLCONV print_to_stream(std::ostream&, signed char, value_flags = {}, size_t min_digits = 0);
|
||||
|
||||
TOML_EXPORTED_FREE_FUNCTION
|
||||
void TOML_CALLCONV print_to_stream(std::ostream&, signed short, value_flags = {}, size_t min_digits = 0);
|
||||
|
||||
TOML_EXPORTED_FREE_FUNCTION
|
||||
void TOML_CALLCONV print_to_stream(std::ostream&, signed int, value_flags = {}, size_t min_digits = 0);
|
||||
|
||||
TOML_EXPORTED_FREE_FUNCTION
|
||||
void TOML_CALLCONV print_to_stream(std::ostream&, signed long, value_flags = {}, size_t min_digits = 0);
|
||||
|
||||
TOML_EXPORTED_FREE_FUNCTION
|
||||
void TOML_CALLCONV print_to_stream(std::ostream&, signed long long, value_flags = {}, size_t min_digits = 0);
|
||||
|
||||
TOML_EXPORTED_FREE_FUNCTION
|
||||
void TOML_CALLCONV print_to_stream(std::ostream&, unsigned char, value_flags = {}, size_t min_digits = 0);
|
||||
|
||||
TOML_EXPORTED_FREE_FUNCTION
|
||||
void TOML_CALLCONV print_to_stream(std::ostream&, unsigned short, value_flags = {}, size_t min_digits = 0);
|
||||
|
||||
TOML_EXPORTED_FREE_FUNCTION
|
||||
void TOML_CALLCONV print_to_stream(std::ostream&, unsigned int, value_flags = {}, size_t min_digits = 0);
|
||||
|
||||
TOML_EXPORTED_FREE_FUNCTION
|
||||
void TOML_CALLCONV print_to_stream(std::ostream&, unsigned long, value_flags = {}, size_t min_digits = 0);
|
||||
|
||||
TOML_EXPORTED_FREE_FUNCTION
|
||||
void TOML_CALLCONV print_to_stream(std::ostream&, unsigned long long, value_flags = {}, size_t min_digits = 0);
|
||||
|
||||
TOML_EXPORTED_FREE_FUNCTION
|
||||
void TOML_CALLCONV print_to_stream(std::ostream&, float, value_flags = {}, bool relaxed_precision = false);
|
||||
|
||||
TOML_EXPORTED_FREE_FUNCTION
|
||||
void TOML_CALLCONV print_to_stream(std::ostream&, double, value_flags = {}, bool relaxed_precision = false);
|
||||
|
||||
TOML_EXPORTED_FREE_FUNCTION
|
||||
void TOML_CALLCONV print_to_stream(std::ostream&, bool);
|
||||
|
||||
TOML_EXPORTED_FREE_FUNCTION
|
||||
void TOML_CALLCONV print_to_stream(std::ostream&, const toml::date&);
|
||||
|
||||
TOML_EXPORTED_FREE_FUNCTION
|
||||
void TOML_CALLCONV print_to_stream(std::ostream&, const toml::time&);
|
||||
|
||||
TOML_EXPORTED_FREE_FUNCTION
|
||||
void TOML_CALLCONV print_to_stream(std::ostream&, const toml::time_offset&);
|
||||
|
||||
TOML_EXPORTED_FREE_FUNCTION
|
||||
void TOML_CALLCONV print_to_stream(std::ostream&, const toml::date_time&);
|
||||
|
||||
TOML_EXPORTED_FREE_FUNCTION
|
||||
void TOML_CALLCONV print_to_stream(std::ostream&, const source_position&);
|
||||
|
||||
TOML_EXPORTED_FREE_FUNCTION
|
||||
void TOML_CALLCONV print_to_stream(std::ostream&, const source_region&);
|
||||
|
||||
#if TOML_ENABLE_FORMATTERS
|
||||
|
||||
TOML_EXPORTED_FREE_FUNCTION
|
||||
void TOML_CALLCONV print_to_stream(std::ostream&, const array&);
|
||||
|
||||
TOML_EXPORTED_FREE_FUNCTION
|
||||
void TOML_CALLCONV print_to_stream(std::ostream&, const table&);
|
||||
|
||||
TOML_EXPORTED_FREE_FUNCTION
|
||||
void TOML_CALLCONV print_to_stream(std::ostream&, const value<std::string>&);
|
||||
|
||||
TOML_EXPORTED_FREE_FUNCTION
|
||||
void TOML_CALLCONV print_to_stream(std::ostream&, const value<int64_t>&);
|
||||
|
||||
TOML_EXPORTED_FREE_FUNCTION
|
||||
void TOML_CALLCONV print_to_stream(std::ostream&, const value<double>&);
|
||||
|
||||
TOML_EXPORTED_FREE_FUNCTION
|
||||
void TOML_CALLCONV print_to_stream(std::ostream&, const value<bool>&);
|
||||
|
||||
TOML_EXPORTED_FREE_FUNCTION
|
||||
void TOML_CALLCONV print_to_stream(std::ostream&, const value<date>&);
|
||||
|
||||
TOML_EXPORTED_FREE_FUNCTION
|
||||
void TOML_CALLCONV print_to_stream(std::ostream&, const value<time>&);
|
||||
|
||||
TOML_EXPORTED_FREE_FUNCTION
|
||||
void TOML_CALLCONV print_to_stream(std::ostream&, const value<date_time>&);
|
||||
|
||||
#endif
|
||||
|
||||
template <typename T, typename U>
|
||||
inline void print_to_stream_bookended(std::ostream & stream, const T& val, const U& bookend)
|
||||
{
|
||||
print_to_stream(stream, bookend);
|
||||
print_to_stream(stream, val);
|
||||
print_to_stream(stream, bookend);
|
||||
}
|
||||
}
|
||||
TOML_IMPL_NAMESPACE_END;
|
||||
|
||||
#include "header_end.hpp"
|
||||
@@ -0,0 +1,490 @@
|
||||
//# This file is a part of toml++ and is subject to the the terms of the MIT license.
|
||||
//# Copyright (c) Mark Gillard <mark.gillard@outlook.com.au>
|
||||
//# See https://github.com/marzer/tomlplusplus/blob/master/LICENSE for the full license text.
|
||||
// SPDX-License-Identifier: MIT
|
||||
#pragma once
|
||||
|
||||
//# {{
|
||||
#include "preprocessor.hpp"
|
||||
#if !TOML_IMPLEMENTATION
|
||||
#error This is an implementation-only header.
|
||||
#endif
|
||||
//# }}
|
||||
|
||||
#include "print_to_stream.hpp"
|
||||
#include "source_region.hpp"
|
||||
#include "date_time.hpp"
|
||||
#include "toml_formatter.hpp"
|
||||
#include "value.hpp"
|
||||
#include "array.hpp"
|
||||
#include "table.hpp"
|
||||
TOML_DISABLE_WARNINGS;
|
||||
#include <ostream>
|
||||
#if TOML_INT_CHARCONV || TOML_FLOAT_CHARCONV
|
||||
#include <charconv>
|
||||
#endif
|
||||
#if !TOML_INT_CHARCONV || !TOML_FLOAT_CHARCONV
|
||||
#include <sstream>
|
||||
#endif
|
||||
#if !TOML_INT_CHARCONV
|
||||
#include <iomanip>
|
||||
#endif
|
||||
TOML_ENABLE_WARNINGS;
|
||||
#include "header_start.hpp"
|
||||
|
||||
TOML_ANON_NAMESPACE_START
|
||||
{
|
||||
template <typename T>
|
||||
inline constexpr size_t charconv_buffer_length = 0;
|
||||
|
||||
template <>
|
||||
inline constexpr size_t charconv_buffer_length<int8_t> = 4; // strlen("-128")
|
||||
|
||||
template <>
|
||||
inline constexpr size_t charconv_buffer_length<int16_t> = 6; // strlen("-32768")
|
||||
|
||||
template <>
|
||||
inline constexpr size_t charconv_buffer_length<int32_t> = 11; // strlen("-2147483648")
|
||||
|
||||
template <>
|
||||
inline constexpr size_t charconv_buffer_length<int64_t> = 20; // strlen("-9223372036854775808")
|
||||
|
||||
template <>
|
||||
inline constexpr size_t charconv_buffer_length<uint8_t> = 3; // strlen("255")
|
||||
|
||||
template <>
|
||||
inline constexpr size_t charconv_buffer_length<uint16_t> = 5; // strlen("65535")
|
||||
|
||||
template <>
|
||||
inline constexpr size_t charconv_buffer_length<uint32_t> = 10; // strlen("4294967295")
|
||||
|
||||
template <>
|
||||
inline constexpr size_t charconv_buffer_length<uint64_t> = 20; // strlen("18446744073709551615")
|
||||
|
||||
template <>
|
||||
inline constexpr size_t charconv_buffer_length<float> = 64;
|
||||
|
||||
template <>
|
||||
inline constexpr size_t charconv_buffer_length<double> = 64;
|
||||
|
||||
template <typename T>
|
||||
TOML_INTERNAL_LINKAGE
|
||||
void print_integer_to_stream(std::ostream & stream, T val, value_flags format = {}, size_t min_digits = 0)
|
||||
{
|
||||
if (!val)
|
||||
{
|
||||
if (!min_digits)
|
||||
min_digits = 1;
|
||||
|
||||
for (size_t i = 0; i < min_digits; i++)
|
||||
stream.put('0');
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
static constexpr auto value_flags_mask =
|
||||
value_flags::format_as_binary | value_flags::format_as_octal | value_flags::format_as_hexadecimal;
|
||||
format &= value_flags_mask;
|
||||
|
||||
int base = 10;
|
||||
if (format != value_flags::none && val > T{})
|
||||
{
|
||||
switch (format)
|
||||
{
|
||||
case value_flags::format_as_binary: base = 2; break;
|
||||
case value_flags::format_as_octal: base = 8; break;
|
||||
case value_flags::format_as_hexadecimal: base = 16; break;
|
||||
default: break;
|
||||
}
|
||||
}
|
||||
|
||||
#if TOML_INT_CHARCONV
|
||||
|
||||
char buf[(sizeof(T) * CHAR_BIT)];
|
||||
const auto res = std::to_chars(buf, buf + sizeof(buf), val, base);
|
||||
const auto len = static_cast<size_t>(res.ptr - buf);
|
||||
for (size_t i = len; i < min_digits; i++)
|
||||
stream.put('0');
|
||||
if (base == 16)
|
||||
{
|
||||
for (size_t i = 0; i < len; i++)
|
||||
if (buf[i] >= 'a')
|
||||
buf[i] -= 32;
|
||||
}
|
||||
impl::print_to_stream(stream, buf, len);
|
||||
|
||||
#else
|
||||
|
||||
using unsigned_type = std::conditional_t<(sizeof(T) > sizeof(unsigned)), std::make_unsigned_t<T>, unsigned>;
|
||||
using cast_type = std::conditional_t<std::is_signed_v<T>, std::make_signed_t<unsigned_type>, unsigned_type>;
|
||||
|
||||
if (base == 2)
|
||||
{
|
||||
const auto len = sizeof(T) * CHAR_BIT;
|
||||
for (size_t i = len; i < min_digits; i++)
|
||||
stream.put('0');
|
||||
|
||||
bool found_one = false;
|
||||
const auto v = static_cast<unsigned_type>(val);
|
||||
unsigned_type mask = unsigned_type{ 1 } << (len - 1u);
|
||||
for (size_t i = 0; i < len; i++)
|
||||
{
|
||||
if ((v & mask))
|
||||
{
|
||||
stream.put('1');
|
||||
found_one = true;
|
||||
}
|
||||
else if (found_one)
|
||||
stream.put('0');
|
||||
mask >>= 1;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
std::ostringstream ss;
|
||||
ss.imbue(std::locale::classic());
|
||||
ss << std::uppercase << std::setbase(base);
|
||||
if (min_digits)
|
||||
ss << std::setfill('0') << std::setw(static_cast<int>(min_digits));
|
||||
ss << static_cast<cast_type>(val);
|
||||
const auto str = std::move(ss).str();
|
||||
impl::print_to_stream(stream, str);
|
||||
}
|
||||
|
||||
#endif
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
TOML_INTERNAL_LINKAGE
|
||||
void print_floating_point_to_stream(std::ostream & stream,
|
||||
T val,
|
||||
value_flags format,
|
||||
[[maybe_unused]] bool relaxed_precision)
|
||||
{
|
||||
switch (impl::fpclassify(val))
|
||||
{
|
||||
case impl::fp_class::neg_inf: impl::print_to_stream(stream, "-inf"sv); break;
|
||||
|
||||
case impl::fp_class::pos_inf: impl::print_to_stream(stream, "inf"sv); break;
|
||||
|
||||
case impl::fp_class::nan: impl::print_to_stream(stream, "nan"sv); break;
|
||||
|
||||
case impl::fp_class::ok:
|
||||
{
|
||||
static constexpr auto needs_decimal_point = [](auto&& s) noexcept
|
||||
{
|
||||
for (auto c : s)
|
||||
if (c == '.' || c == 'E' || c == 'e')
|
||||
return false;
|
||||
return true;
|
||||
};
|
||||
|
||||
#if TOML_FLOAT_CHARCONV
|
||||
|
||||
const auto hex = !!(format & value_flags::format_as_hexadecimal);
|
||||
char buf[charconv_buffer_length<T>];
|
||||
auto res = hex ? std::to_chars(buf, buf + sizeof(buf), val, std::chars_format::hex)
|
||||
: std::to_chars(buf, buf + sizeof(buf), val);
|
||||
auto str = std::string_view{ buf, static_cast<size_t>(res.ptr - buf) };
|
||||
|
||||
char buf2[charconv_buffer_length<T>];
|
||||
if (!hex && relaxed_precision)
|
||||
{
|
||||
res = std::to_chars(buf2, buf2 + sizeof(buf2), val, std::chars_format::general, 6);
|
||||
const auto str2 = std::string_view{ buf2, static_cast<size_t>(res.ptr - buf2) };
|
||||
if (str2.length() < str.length())
|
||||
str = str2;
|
||||
}
|
||||
|
||||
impl::print_to_stream(stream, str);
|
||||
if (!hex && needs_decimal_point(str))
|
||||
toml::impl::print_to_stream(stream, ".0"sv);
|
||||
|
||||
#else
|
||||
|
||||
std::ostringstream ss;
|
||||
ss.imbue(std::locale::classic());
|
||||
if (!relaxed_precision)
|
||||
ss.precision(std::numeric_limits<T>::max_digits10);
|
||||
if (!!(format & value_flags::format_as_hexadecimal))
|
||||
ss << std::hexfloat;
|
||||
ss << val;
|
||||
const auto str = std::move(ss).str();
|
||||
impl::print_to_stream(stream, str);
|
||||
if (!(format & value_flags::format_as_hexadecimal) && needs_decimal_point(str))
|
||||
impl::print_to_stream(stream, ".0"sv);
|
||||
|
||||
#endif
|
||||
}
|
||||
break;
|
||||
|
||||
default: TOML_UNREACHABLE;
|
||||
}
|
||||
}
|
||||
}
|
||||
TOML_ANON_NAMESPACE_END;
|
||||
|
||||
TOML_IMPL_NAMESPACE_START
|
||||
{
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
TOML_ATTR(nonnull)
|
||||
void TOML_CALLCONV print_to_stream(std::ostream & stream, const char* val, size_t len)
|
||||
{
|
||||
stream.write(val, static_cast<std::streamsize>(len));
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
void TOML_CALLCONV print_to_stream(std::ostream & stream, std::string_view val)
|
||||
{
|
||||
stream.write(val.data(), static_cast<std::streamsize>(val.length()));
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
void TOML_CALLCONV print_to_stream(std::ostream & stream, const std::string& val)
|
||||
{
|
||||
stream.write(val.data(), static_cast<std::streamsize>(val.length()));
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
void TOML_CALLCONV print_to_stream(std::ostream & stream, char val)
|
||||
{
|
||||
stream.put(val);
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
void TOML_CALLCONV print_to_stream(std::ostream & stream, signed char val, value_flags format, size_t min_digits)
|
||||
{
|
||||
TOML_ANON_NAMESPACE::print_integer_to_stream(stream, val, format, min_digits);
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
void TOML_CALLCONV print_to_stream(std::ostream & stream, signed short val, value_flags format, size_t min_digits)
|
||||
{
|
||||
TOML_ANON_NAMESPACE::print_integer_to_stream(stream, val, format, min_digits);
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
void TOML_CALLCONV print_to_stream(std::ostream & stream, signed int val, value_flags format, size_t min_digits)
|
||||
{
|
||||
TOML_ANON_NAMESPACE::print_integer_to_stream(stream, val, format, min_digits);
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
void TOML_CALLCONV print_to_stream(std::ostream & stream, signed long val, value_flags format, size_t min_digits)
|
||||
{
|
||||
TOML_ANON_NAMESPACE::print_integer_to_stream(stream, val, format, min_digits);
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
void TOML_CALLCONV print_to_stream(std::ostream & stream,
|
||||
signed long long val,
|
||||
value_flags format,
|
||||
size_t min_digits)
|
||||
{
|
||||
TOML_ANON_NAMESPACE::print_integer_to_stream(stream, val, format, min_digits);
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
void TOML_CALLCONV print_to_stream(std::ostream & stream, unsigned char val, value_flags format, size_t min_digits)
|
||||
{
|
||||
TOML_ANON_NAMESPACE::print_integer_to_stream(stream, val, format, min_digits);
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
void TOML_CALLCONV print_to_stream(std::ostream & stream, unsigned short val, value_flags format, size_t min_digits)
|
||||
{
|
||||
TOML_ANON_NAMESPACE::print_integer_to_stream(stream, val, format, min_digits);
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
void TOML_CALLCONV print_to_stream(std::ostream & stream, unsigned int val, value_flags format, size_t min_digits)
|
||||
{
|
||||
TOML_ANON_NAMESPACE::print_integer_to_stream(stream, val, format, min_digits);
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
void TOML_CALLCONV print_to_stream(std::ostream & stream, unsigned long val, value_flags format, size_t min_digits)
|
||||
{
|
||||
TOML_ANON_NAMESPACE::print_integer_to_stream(stream, val, format, min_digits);
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
void TOML_CALLCONV print_to_stream(std::ostream & stream,
|
||||
unsigned long long val,
|
||||
value_flags format,
|
||||
size_t min_digits)
|
||||
{
|
||||
TOML_ANON_NAMESPACE::print_integer_to_stream(stream, val, format, min_digits);
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
void TOML_CALLCONV print_to_stream(std::ostream & stream, float val, value_flags format, bool relaxed_precision)
|
||||
{
|
||||
TOML_ANON_NAMESPACE::print_floating_point_to_stream(stream, val, format, relaxed_precision);
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
void TOML_CALLCONV print_to_stream(std::ostream & stream, double val, value_flags format, bool relaxed_precision)
|
||||
{
|
||||
TOML_ANON_NAMESPACE::print_floating_point_to_stream(stream, val, format, relaxed_precision);
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
void TOML_CALLCONV print_to_stream(std::ostream & stream, bool val)
|
||||
{
|
||||
print_to_stream(stream, val ? "true"sv : "false"sv);
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
void TOML_CALLCONV print_to_stream(std::ostream & stream, const toml::date& val)
|
||||
{
|
||||
print_to_stream(stream, val.year, {}, 4);
|
||||
stream.put('-');
|
||||
print_to_stream(stream, val.month, {}, 2);
|
||||
stream.put('-');
|
||||
print_to_stream(stream, val.day, {}, 2);
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
void TOML_CALLCONV print_to_stream(std::ostream & stream, const toml::time& val)
|
||||
{
|
||||
print_to_stream(stream, val.hour, {}, 2);
|
||||
stream.put(':');
|
||||
print_to_stream(stream, val.minute, {}, 2);
|
||||
stream.put(':');
|
||||
print_to_stream(stream, val.second, {}, 2);
|
||||
if (val.nanosecond && val.nanosecond <= 999999999u)
|
||||
{
|
||||
stream.put('.');
|
||||
auto ns = val.nanosecond;
|
||||
size_t digits = 9u;
|
||||
while (ns % 10u == 0u)
|
||||
{
|
||||
ns /= 10u;
|
||||
digits--;
|
||||
}
|
||||
print_to_stream(stream, ns, {}, digits);
|
||||
}
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
void TOML_CALLCONV print_to_stream(std::ostream & stream, const toml::time_offset& val)
|
||||
{
|
||||
if (!val.minutes)
|
||||
{
|
||||
stream.put('Z');
|
||||
return;
|
||||
}
|
||||
|
||||
auto mins = static_cast<int>(val.minutes);
|
||||
if (mins < 0)
|
||||
{
|
||||
stream.put('-');
|
||||
mins = -mins;
|
||||
}
|
||||
else
|
||||
stream.put('+');
|
||||
const auto hours = mins / 60;
|
||||
if (hours)
|
||||
{
|
||||
print_to_stream(stream, static_cast<unsigned int>(hours), {}, 2);
|
||||
mins -= hours * 60;
|
||||
}
|
||||
else
|
||||
print_to_stream(stream, "00"sv);
|
||||
stream.put(':');
|
||||
print_to_stream(stream, static_cast<unsigned int>(mins), {}, 2);
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
void TOML_CALLCONV print_to_stream(std::ostream & stream, const toml::date_time& val)
|
||||
{
|
||||
print_to_stream(stream, val.date);
|
||||
stream.put('T');
|
||||
print_to_stream(stream, val.time);
|
||||
if (val.offset)
|
||||
print_to_stream(stream, *val.offset);
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
void TOML_CALLCONV print_to_stream(std::ostream & stream, const source_position& val)
|
||||
{
|
||||
print_to_stream(stream, "line "sv);
|
||||
print_to_stream(stream, val.line);
|
||||
print_to_stream(stream, ", column "sv);
|
||||
print_to_stream(stream, val.column);
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
void TOML_CALLCONV print_to_stream(std::ostream & stream, const source_region& val)
|
||||
{
|
||||
print_to_stream(stream, val.begin);
|
||||
if (val.path)
|
||||
{
|
||||
print_to_stream(stream, " of '"sv);
|
||||
print_to_stream(stream, *val.path);
|
||||
stream.put('\'');
|
||||
}
|
||||
}
|
||||
|
||||
#if TOML_ENABLE_FORMATTERS
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
void TOML_CALLCONV print_to_stream(std::ostream & stream, const array& arr)
|
||||
{
|
||||
stream << toml_formatter{ arr };
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
void TOML_CALLCONV print_to_stream(std::ostream & stream, const table& tbl)
|
||||
{
|
||||
stream << toml_formatter{ tbl };
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
void TOML_CALLCONV print_to_stream(std::ostream & stream, const value<std::string>& val)
|
||||
{
|
||||
stream << toml_formatter{ val };
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
void TOML_CALLCONV print_to_stream(std::ostream & stream, const value<int64_t>& val)
|
||||
{
|
||||
stream << toml_formatter{ val };
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
void TOML_CALLCONV print_to_stream(std::ostream & stream, const value<double>& val)
|
||||
{
|
||||
stream << toml_formatter{ val };
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
void TOML_CALLCONV print_to_stream(std::ostream & stream, const value<bool>& val)
|
||||
{
|
||||
stream << toml_formatter{ val };
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
void TOML_CALLCONV print_to_stream(std::ostream & stream, const value<date>& val)
|
||||
{
|
||||
stream << toml_formatter{ val };
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
void TOML_CALLCONV print_to_stream(std::ostream & stream, const value<time>& val)
|
||||
{
|
||||
stream << toml_formatter{ val };
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
void TOML_CALLCONV print_to_stream(std::ostream & stream, const value<date_time>& val)
|
||||
{
|
||||
stream << toml_formatter{ val };
|
||||
}
|
||||
|
||||
#endif
|
||||
}
|
||||
TOML_IMPL_NAMESPACE_END;
|
||||
|
||||
#include "header_end.hpp"
|
||||
@@ -0,0 +1,35 @@
|
||||
//# This file is a part of toml++ and is subject to the the terms of the MIT license.
|
||||
//# Copyright (c) Mark Gillard <mark.gillard@outlook.com.au>
|
||||
//# See https://github.com/marzer/tomlplusplus/blob/master/LICENSE for the full license text.
|
||||
// SPDX-License-Identifier: MIT
|
||||
#pragma once
|
||||
|
||||
#include "preprocessor.hpp"
|
||||
#if TOML_ENABLE_SIMD
|
||||
|
||||
#if defined(__SSE2__) \
|
||||
|| (defined(_MSC_VER) && (defined(_M_AMD64) || defined(_M_X64) || (defined(_M_IX86_FP) && _M_IX86_FP >= 2)))
|
||||
#define TOML_HAS_SSE2 1
|
||||
#endif
|
||||
|
||||
#if defined(__SSE4_1__) || (defined(_MSC_VER) && (defined(__AVX__) || defined(__AVX2__)))
|
||||
#define TOML_HAS_SSE4_1 1
|
||||
#endif
|
||||
|
||||
#endif // TOML_ENABLE_SIMD
|
||||
|
||||
#ifndef TOML_HAS_SSE2
|
||||
#define TOML_HAS_SSE2 0
|
||||
#endif
|
||||
#ifndef TOML_HAS_SSE4_1
|
||||
#define TOML_HAS_SSE4_1 0
|
||||
#endif
|
||||
|
||||
TOML_DISABLE_WARNINGS;
|
||||
#if TOML_HAS_SSE4_1
|
||||
#include <smmintrin.h>
|
||||
#endif
|
||||
#if TOML_HAS_SSE2
|
||||
#include <emmintrin.h>
|
||||
#endif
|
||||
TOML_ENABLE_WARNINGS;
|
||||
@@ -0,0 +1,223 @@
|
||||
//# This file is a part of toml++ and is subject to the the terms of the MIT license.
|
||||
//# Copyright (c) Mark Gillard <mark.gillard@outlook.com.au>
|
||||
//# See https://github.com/marzer/tomlplusplus/blob/master/LICENSE for the full license text.
|
||||
// SPDX-License-Identifier: MIT
|
||||
#pragma once
|
||||
|
||||
#include "std_optional.hpp"
|
||||
#include "std_string.hpp"
|
||||
#include "forward_declarations.hpp"
|
||||
#include "print_to_stream.hpp"
|
||||
#include "header_start.hpp"
|
||||
|
||||
TOML_NAMESPACE_START
|
||||
{
|
||||
/// \brief The integer type used to tally line numbers and columns.
|
||||
using source_index = uint32_t;
|
||||
|
||||
/// \brief A pointer to a shared string resource containing a source path.
|
||||
using source_path_ptr = std::shared_ptr<const std::string>;
|
||||
|
||||
/// \brief A source document line-and-column pair.
|
||||
///
|
||||
/// \detail \cpp
|
||||
/// auto table = toml::parse_file("config.toml"sv);
|
||||
/// std::cout << "The node 'description' was defined at "sv
|
||||
/// << table.get("description")->source().begin()
|
||||
/// << "\n";
|
||||
/// \ecpp
|
||||
///
|
||||
/// \out
|
||||
/// The value 'description' was defined at line 7, column 15
|
||||
/// \eout
|
||||
///
|
||||
/// \remarks toml++'s parser is unicode-aware insofar as it knows how to handle
|
||||
/// non-ASCII whitespace and newline characters, but it doesn't give much thought
|
||||
/// to combining marks, grapheme clusters vs. characters, et cetera.
|
||||
/// If a TOML document contains lots of codepoints outside of the ASCII range
|
||||
/// you may find that your source_positions don't match those given by a text editor
|
||||
/// (typically the line numbers will be accurate but column numbers will be too high).
|
||||
/// <strong>This is not an error.</strong> I've chosen this behaviour as a deliberate trade-off
|
||||
/// between parser complexity and correctness.
|
||||
struct TOML_TRIVIAL_ABI source_position
|
||||
{
|
||||
/// \brief The line number.
|
||||
/// \remarks Valid line numbers start at 1.
|
||||
source_index line;
|
||||
|
||||
/// \brief The column number.
|
||||
/// \remarks Valid column numbers start at 1.
|
||||
source_index column;
|
||||
|
||||
/// \brief Returns true if both line and column numbers are non-zero.
|
||||
TOML_PURE_GETTER
|
||||
explicit constexpr operator bool() const noexcept
|
||||
{
|
||||
return line > source_index{} //
|
||||
&& column > source_index{};
|
||||
}
|
||||
|
||||
/// \brief Equality operator.
|
||||
TOML_PURE_GETTER
|
||||
friend constexpr bool operator==(const source_position& lhs, const source_position& rhs) noexcept
|
||||
{
|
||||
return lhs.line == rhs.line //
|
||||
&& lhs.column == rhs.column;
|
||||
}
|
||||
|
||||
/// \brief Inequality operator.
|
||||
TOML_PURE_INLINE_GETTER
|
||||
friend constexpr bool operator!=(const source_position& lhs, const source_position& rhs) noexcept
|
||||
{
|
||||
return !(lhs == rhs);
|
||||
}
|
||||
|
||||
private:
|
||||
/// \cond
|
||||
|
||||
TOML_PURE_GETTER
|
||||
static constexpr uint64_t pack(const source_position& pos) noexcept
|
||||
{
|
||||
return static_cast<uint64_t>(pos.line) << 32 | static_cast<uint64_t>(pos.column);
|
||||
}
|
||||
|
||||
/// \endcond
|
||||
|
||||
public:
|
||||
/// \brief Less-than operator.
|
||||
TOML_PURE_GETTER
|
||||
friend constexpr bool operator<(const source_position& lhs, const source_position& rhs) noexcept
|
||||
{
|
||||
return pack(lhs) < pack(rhs);
|
||||
}
|
||||
|
||||
/// \brief Less-than-or-equal-to operator.
|
||||
TOML_PURE_GETTER
|
||||
friend constexpr bool operator<=(const source_position& lhs, const source_position& rhs) noexcept
|
||||
{
|
||||
return pack(lhs) <= pack(rhs);
|
||||
}
|
||||
|
||||
/// \brief Greater-than operator.
|
||||
TOML_PURE_GETTER
|
||||
friend constexpr bool operator>(const source_position& lhs, const source_position& rhs) noexcept
|
||||
{
|
||||
return pack(lhs) > pack(rhs);
|
||||
}
|
||||
|
||||
/// \brief Greater-than-or-equal-to operator.
|
||||
TOML_PURE_GETTER
|
||||
friend constexpr bool operator>=(const source_position& lhs, const source_position& rhs) noexcept
|
||||
{
|
||||
return pack(lhs) >= pack(rhs);
|
||||
}
|
||||
|
||||
/// \brief Prints a source_position to a stream.
|
||||
///
|
||||
/// \detail \cpp
|
||||
/// auto tbl = toml::parse("bar = 42"sv);
|
||||
///
|
||||
/// std::cout << "The value for 'bar' was found on "sv
|
||||
/// << tbl.get("bar")->source().begin()
|
||||
/// << "\n";
|
||||
/// \ecpp
|
||||
///
|
||||
/// \out
|
||||
/// The value for 'bar' was found on line 1, column 7
|
||||
/// \eout
|
||||
///
|
||||
/// \param lhs The stream.
|
||||
/// \param rhs The source_position.
|
||||
///
|
||||
/// \returns The input stream.
|
||||
friend std::ostream& operator<<(std::ostream& lhs, const source_position& rhs)
|
||||
{
|
||||
impl::print_to_stream(lhs, rhs);
|
||||
return lhs;
|
||||
}
|
||||
};
|
||||
|
||||
/// \brief A source document region.
|
||||
///
|
||||
/// \detail \cpp
|
||||
/// auto tbl = toml::parse_file("config.toml"sv);
|
||||
/// if (auto server = tbl.get("server"))
|
||||
/// {
|
||||
/// std::cout << "begin: "sv << server->source().begin << "\n";
|
||||
/// std::cout << "end: "sv << server->source().end << "\n";
|
||||
/// std::cout << "path: "sv << *server->source().path << "\n";
|
||||
/// }
|
||||
/// \ecpp
|
||||
///
|
||||
/// \out
|
||||
/// begin: line 3, column 1
|
||||
/// end: line 3, column 22
|
||||
/// path: config.toml
|
||||
/// \eout
|
||||
///
|
||||
/// \remarks toml++'s parser is unicode-aware insofar as it knows how to handle
|
||||
/// non-ASCII whitespace and newline characters, but it doesn't give much thought
|
||||
/// to combining marks, grapheme clusters vs. characters, et cetera.
|
||||
/// If a TOML document contains lots of codepoints outside of the ASCII range
|
||||
/// you may find that your source_positions don't match those given by a text editor
|
||||
/// (typically the line numbers will be accurate but column numbers will be too high).
|
||||
/// <strong>This is not an error.</strong> I've chosen this behaviour as a deliberate trade-off
|
||||
/// between parser complexity and correctness.
|
||||
struct source_region
|
||||
{
|
||||
/// \brief The beginning of the region (inclusive).
|
||||
source_position begin;
|
||||
|
||||
/// \brief The end of the region (exclusive).
|
||||
source_position end;
|
||||
|
||||
/// \brief The path to the corresponding source document.
|
||||
///
|
||||
/// \remarks This will be `nullptr` if no path was provided to toml::parse().
|
||||
source_path_ptr path;
|
||||
|
||||
#if TOML_ENABLE_WINDOWS_COMPAT
|
||||
|
||||
/// \brief The path to the corresponding source document as a wide-string.
|
||||
///
|
||||
/// \availability This function is only available when #TOML_ENABLE_WINDOWS_COMPAT is enabled.
|
||||
///
|
||||
/// \remarks This will return an empty optional if no path was provided to toml::parse().
|
||||
TOML_NODISCARD
|
||||
optional<std::wstring> wide_path() const
|
||||
{
|
||||
if (!path || path->empty())
|
||||
return {};
|
||||
return { impl::widen(*path) };
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
/// \brief Prints a source_region to a stream.
|
||||
///
|
||||
/// \detail \cpp
|
||||
/// auto tbl = toml::parse("bar = 42", "config.toml");
|
||||
///
|
||||
/// std::cout << "The value for 'bar' was found on "sv
|
||||
/// << tbl.get("bar")->source()
|
||||
/// << "\n";
|
||||
/// \ecpp
|
||||
///
|
||||
/// \out
|
||||
/// The value for 'bar' was found on line 1, column 7 of 'config.toml'
|
||||
/// \eout
|
||||
///
|
||||
/// \param lhs The stream.
|
||||
/// \param rhs The source_position.
|
||||
///
|
||||
/// \returns The input stream.
|
||||
friend std::ostream& operator<<(std::ostream& lhs, const source_region& rhs)
|
||||
{
|
||||
impl::print_to_stream(lhs, rhs);
|
||||
return lhs;
|
||||
}
|
||||
};
|
||||
}
|
||||
TOML_NAMESPACE_END;
|
||||
|
||||
#include "header_end.hpp"
|
||||
@@ -0,0 +1,12 @@
|
||||
//# This file is a part of toml++ and is subject to the the terms of the MIT license.
|
||||
//# Copyright (c) Mark Gillard <mark.gillard@outlook.com.au>
|
||||
//# See https://github.com/marzer/tomlplusplus/blob/master/LICENSE for the full license text.
|
||||
// SPDX-License-Identifier: MIT
|
||||
#pragma once
|
||||
|
||||
#include "preprocessor.hpp"
|
||||
TOML_DISABLE_WARNINGS;
|
||||
#if TOML_EXCEPTIONS
|
||||
#include <stdexcept>
|
||||
#endif
|
||||
TOML_ENABLE_WARNINGS;
|
||||
@@ -0,0 +1,10 @@
|
||||
//# This file is a part of toml++ and is subject to the the terms of the MIT license.
|
||||
//# Copyright (c) Mark Gillard <mark.gillard@outlook.com.au>
|
||||
//# See https://github.com/marzer/tomlplusplus/blob/master/LICENSE for the full license text.
|
||||
// SPDX-License-Identifier: MIT
|
||||
#pragma once
|
||||
|
||||
#include "preprocessor.hpp"
|
||||
TOML_DISABLE_WARNINGS;
|
||||
#include <initializer_list>
|
||||
TOML_ENABLE_WARNINGS;
|
||||
@@ -0,0 +1,11 @@
|
||||
//# This file is a part of toml++ and is subject to the the terms of the MIT license.
|
||||
//# Copyright (c) Mark Gillard <mark.gillard@outlook.com.au>
|
||||
//# See https://github.com/marzer/tomlplusplus/blob/master/LICENSE for the full license text.
|
||||
// SPDX-License-Identifier: MIT
|
||||
#pragma once
|
||||
|
||||
#include "preprocessor.hpp"
|
||||
TOML_DISABLE_WARNINGS;
|
||||
#include <map>
|
||||
#include <iterator>
|
||||
TOML_ENABLE_WARNINGS;
|
||||
@@ -0,0 +1,18 @@
|
||||
//# This file is a part of toml++ and is subject to the the terms of the MIT license.
|
||||
//# Copyright (c) Mark Gillard <mark.gillard@outlook.com.au>
|
||||
//# See https://github.com/marzer/tomlplusplus/blob/master/LICENSE for the full license text.
|
||||
// SPDX-License-Identifier: MIT
|
||||
#pragma once
|
||||
|
||||
#include "preprocessor.hpp"
|
||||
TOML_DISABLE_WARNINGS;
|
||||
#include <new>
|
||||
TOML_ENABLE_WARNINGS;
|
||||
|
||||
#if (!defined(__apple_build_version__) && TOML_CLANG >= 8) || TOML_GCC >= 7 || TOML_ICC >= 1910 || TOML_MSVC >= 1914
|
||||
#define TOML_LAUNDER(x) __builtin_launder(x)
|
||||
#elif defined(__cpp_lib_launder) && __cpp_lib_launder >= 201606
|
||||
#define TOML_LAUNDER(x) std::launder(x)
|
||||
#else
|
||||
#define TOML_LAUNDER(x) x
|
||||
#endif
|
||||
@@ -0,0 +1,32 @@
|
||||
//# This file is a part of toml++ and is subject to the the terms of the MIT license.
|
||||
//# Copyright (c) Mark Gillard <mark.gillard@outlook.com.au>
|
||||
//# See https://github.com/marzer/tomlplusplus/blob/master/LICENSE for the full license text.
|
||||
// SPDX-License-Identifier: MIT
|
||||
#pragma once
|
||||
|
||||
#include "preprocessor.hpp"
|
||||
TOML_DISABLE_WARNINGS;
|
||||
#if !TOML_HAS_CUSTOM_OPTIONAL_TYPE
|
||||
#include <optional>
|
||||
#endif
|
||||
TOML_ENABLE_WARNINGS;
|
||||
|
||||
TOML_NAMESPACE_START
|
||||
{
|
||||
#if TOML_HAS_CUSTOM_OPTIONAL_TYPE
|
||||
|
||||
template <typename T>
|
||||
using optional = TOML_OPTIONAL_TYPE<T>;
|
||||
|
||||
#else
|
||||
|
||||
/// \brief The 'optional' type used throughout the library.
|
||||
///
|
||||
/// \remarks By default this will be an alias for std::optional, but you can change the optional type
|
||||
/// used by the library by defining #TOML_OPTIONAL_TYPE.
|
||||
template <typename T>
|
||||
using optional = std::optional<T>;
|
||||
|
||||
#endif
|
||||
}
|
||||
TOML_NAMESPACE_END;
|
||||
@@ -0,0 +1,53 @@
|
||||
//# This file is a part of toml++ and is subject to the the terms of the MIT license.
|
||||
//# Copyright (c) Mark Gillard <mark.gillard@outlook.com.au>
|
||||
//# See https://github.com/marzer/tomlplusplus/blob/master/LICENSE for the full license text.
|
||||
// SPDX-License-Identifier: MIT
|
||||
#pragma once
|
||||
|
||||
#include "preprocessor.hpp"
|
||||
TOML_DISABLE_WARNINGS;
|
||||
#include <string_view>
|
||||
#include <string>
|
||||
TOML_ENABLE_WARNINGS;
|
||||
|
||||
#if TOML_DOXYGEN \
|
||||
|| (defined(__cpp_char8_t) && __cpp_char8_t >= 201811 && defined(__cpp_lib_char8_t) \
|
||||
&& __cpp_lib_char8_t >= 201907)
|
||||
#define TOML_HAS_CHAR8 1
|
||||
#else
|
||||
#define TOML_HAS_CHAR8 0
|
||||
#endif
|
||||
|
||||
/// \cond
|
||||
|
||||
namespace toml // non-abi namespace; this is not an error
|
||||
{
|
||||
using namespace std::string_literals;
|
||||
using namespace std::string_view_literals;
|
||||
}
|
||||
|
||||
#if TOML_ENABLE_WINDOWS_COMPAT
|
||||
|
||||
TOML_IMPL_NAMESPACE_START
|
||||
{
|
||||
TOML_NODISCARD
|
||||
TOML_EXPORTED_FREE_FUNCTION
|
||||
std::string narrow(std::wstring_view);
|
||||
|
||||
TOML_NODISCARD
|
||||
TOML_EXPORTED_FREE_FUNCTION
|
||||
std::wstring widen(std::string_view);
|
||||
|
||||
#if TOML_HAS_CHAR8
|
||||
|
||||
TOML_NODISCARD
|
||||
TOML_EXPORTED_FREE_FUNCTION
|
||||
std::wstring widen(std::u8string_view);
|
||||
|
||||
#endif
|
||||
}
|
||||
TOML_IMPL_NAMESPACE_END;
|
||||
|
||||
#endif // TOML_ENABLE_WINDOWS_COMPAT
|
||||
|
||||
/// \endcond
|
||||
@@ -0,0 +1,99 @@
|
||||
//# This file is a part of toml++ and is subject to the the terms of the MIT license.
|
||||
//# Copyright (c) Mark Gillard <mark.gillard@outlook.com.au>
|
||||
//# See https://github.com/marzer/tomlplusplus/blob/master/LICENSE for the full license text.
|
||||
// SPDX-License-Identifier: MIT
|
||||
#pragma once
|
||||
|
||||
//# {{
|
||||
#include "preprocessor.hpp"
|
||||
#if !TOML_IMPLEMENTATION
|
||||
#error This is an implementation-only header.
|
||||
#endif
|
||||
//# }}
|
||||
|
||||
#if TOML_WINDOWS
|
||||
#include "std_string.hpp"
|
||||
#ifndef _WINDOWS_
|
||||
#if TOML_INCLUDE_WINDOWS_H
|
||||
#include <Windows.h>
|
||||
#else
|
||||
|
||||
extern "C" __declspec(dllimport) int __stdcall WideCharToMultiByte(unsigned int CodePage,
|
||||
unsigned long dwFlags,
|
||||
const wchar_t* lpWideCharStr,
|
||||
int cchWideChar,
|
||||
char* lpMultiByteStr,
|
||||
int cbMultiByte,
|
||||
const char* lpDefaultChar,
|
||||
int* lpUsedDefaultChar);
|
||||
|
||||
extern "C" __declspec(dllimport) int __stdcall MultiByteToWideChar(unsigned int CodePage,
|
||||
unsigned long dwFlags,
|
||||
const char* lpMultiByteStr,
|
||||
int cbMultiByte,
|
||||
wchar_t* lpWideCharStr,
|
||||
int cchWideChar);
|
||||
|
||||
#endif // TOML_INCLUDE_WINDOWS_H
|
||||
#endif // _WINDOWS_
|
||||
#include "header_start.hpp"
|
||||
|
||||
TOML_IMPL_NAMESPACE_START
|
||||
{
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
std::string narrow(std::wstring_view str)
|
||||
{
|
||||
if (str.empty())
|
||||
return {};
|
||||
|
||||
std::string s;
|
||||
const auto len =
|
||||
::WideCharToMultiByte(65001, 0, str.data(), static_cast<int>(str.length()), nullptr, 0, nullptr, nullptr);
|
||||
if (len)
|
||||
{
|
||||
s.resize(static_cast<size_t>(len));
|
||||
::WideCharToMultiByte(65001,
|
||||
0,
|
||||
str.data(),
|
||||
static_cast<int>(str.length()),
|
||||
s.data(),
|
||||
len,
|
||||
nullptr,
|
||||
nullptr);
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
std::wstring widen(std::string_view str)
|
||||
{
|
||||
if (str.empty())
|
||||
return {};
|
||||
|
||||
std::wstring s;
|
||||
const auto len = ::MultiByteToWideChar(65001, 0, str.data(), static_cast<int>(str.length()), nullptr, 0);
|
||||
if (len)
|
||||
{
|
||||
s.resize(static_cast<size_t>(len));
|
||||
::MultiByteToWideChar(65001, 0, str.data(), static_cast<int>(str.length()), s.data(), len);
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
#if TOML_HAS_CHAR8
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
std::wstring widen(std::u8string_view str)
|
||||
{
|
||||
if (str.empty())
|
||||
return {};
|
||||
|
||||
return widen(std::string_view{ reinterpret_cast<const char*>(str.data()), str.length() });
|
||||
}
|
||||
|
||||
#endif // TOML_HAS_CHAR8
|
||||
}
|
||||
TOML_IMPL_NAMESPACE_END;
|
||||
|
||||
#include "header_end.hpp"
|
||||
#endif // TOML_WINDOWS
|
||||
@@ -0,0 +1,10 @@
|
||||
//# This file is a part of toml++ and is subject to the the terms of the MIT license.
|
||||
//# Copyright (c) Mark Gillard <mark.gillard@outlook.com.au>
|
||||
//# See https://github.com/marzer/tomlplusplus/blob/master/LICENSE for the full license text.
|
||||
// SPDX-License-Identifier: MIT
|
||||
#pragma once
|
||||
|
||||
#include "preprocessor.hpp"
|
||||
TOML_DISABLE_WARNINGS;
|
||||
#include <utility>
|
||||
TOML_ENABLE_WARNINGS;
|
||||
@@ -0,0 +1,10 @@
|
||||
//# This file is a part of toml++ and is subject to the the terms of the MIT license.
|
||||
//# Copyright (c) Mark Gillard <mark.gillard@outlook.com.au>
|
||||
//# See https://github.com/marzer/tomlplusplus/blob/master/LICENSE for the full license text.
|
||||
// SPDX-License-Identifier: MIT
|
||||
#pragma once
|
||||
|
||||
#include "preprocessor.hpp"
|
||||
TOML_DISABLE_WARNINGS;
|
||||
#include <variant>
|
||||
TOML_ENABLE_WARNINGS;
|
||||
@@ -0,0 +1,11 @@
|
||||
//# This file is a part of toml++ and is subject to the the terms of the MIT license.
|
||||
//# Copyright (c) Mark Gillard <mark.gillard@outlook.com.au>
|
||||
//# See https://github.com/marzer/tomlplusplus/blob/master/LICENSE for the full license text.
|
||||
// SPDX-License-Identifier: MIT
|
||||
#pragma once
|
||||
|
||||
#include "preprocessor.hpp"
|
||||
TOML_DISABLE_WARNINGS;
|
||||
#include <vector>
|
||||
#include <iterator>
|
||||
TOML_ENABLE_WARNINGS;
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,318 @@
|
||||
//# This file is a part of toml++ and is subject to the the terms of the MIT license.
|
||||
//# Copyright (c) Mark Gillard <mark.gillard@outlook.com.au>
|
||||
//# See https://github.com/marzer/tomlplusplus/blob/master/LICENSE for the full license text.
|
||||
// SPDX-License-Identifier: MIT
|
||||
#pragma once
|
||||
|
||||
//# {{
|
||||
#include "preprocessor.hpp"
|
||||
#if !TOML_IMPLEMENTATION
|
||||
#error This is an implementation-only header.
|
||||
#endif
|
||||
//# }}
|
||||
|
||||
#include "table.hpp"
|
||||
#include "node_view.hpp"
|
||||
#include "header_start.hpp"
|
||||
|
||||
TOML_NAMESPACE_START
|
||||
{
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
table::table() noexcept
|
||||
{
|
||||
#if TOML_LIFETIME_HOOKS
|
||||
TOML_TABLE_CREATED;
|
||||
#endif
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
table::~table() noexcept
|
||||
{
|
||||
#if TOML_LIFETIME_HOOKS
|
||||
TOML_TABLE_DESTROYED;
|
||||
#endif
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
table::table(const impl::table_init_pair* b, const impl::table_init_pair* e)
|
||||
{
|
||||
#if TOML_LIFETIME_HOOKS
|
||||
TOML_TABLE_CREATED;
|
||||
#endif
|
||||
|
||||
TOML_ASSERT_ASSUME(b);
|
||||
TOML_ASSERT_ASSUME(e);
|
||||
TOML_ASSERT_ASSUME(b <= e);
|
||||
|
||||
if TOML_UNLIKELY(b == e)
|
||||
return;
|
||||
|
||||
for (; b != e; b++)
|
||||
{
|
||||
if (!b->value) // empty node_views
|
||||
continue;
|
||||
|
||||
map_.insert_or_assign(std::move(b->key), std::move(b->value));
|
||||
}
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
table::table(const table& other) //
|
||||
: node(other),
|
||||
inline_{ other.inline_ }
|
||||
{
|
||||
for (auto&& [k, v] : other.map_)
|
||||
map_.emplace_hint(map_.end(), k, impl::make_node(*v));
|
||||
|
||||
#if TOML_LIFETIME_HOOKS
|
||||
TOML_TABLE_CREATED;
|
||||
#endif
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
table::table(table && other) noexcept //
|
||||
: node(std::move(other)),
|
||||
map_{ std::move(other.map_) },
|
||||
inline_{ other.inline_ }
|
||||
{
|
||||
#if TOML_LIFETIME_HOOKS
|
||||
TOML_TABLE_CREATED;
|
||||
#endif
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
table& table::operator=(const table& rhs)
|
||||
{
|
||||
if (&rhs != this)
|
||||
{
|
||||
node::operator=(rhs);
|
||||
map_.clear();
|
||||
for (auto&& [k, v] : rhs.map_)
|
||||
map_.emplace_hint(map_.end(), k, impl::make_node(*v));
|
||||
inline_ = rhs.inline_;
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
table& table::operator=(table&& rhs) noexcept
|
||||
{
|
||||
if (&rhs != this)
|
||||
{
|
||||
node::operator=(std::move(rhs));
|
||||
map_ = std::move(rhs.map_);
|
||||
inline_ = rhs.inline_;
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
TOML_PURE_GETTER
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
bool table::is_homogeneous(node_type ntype) const noexcept
|
||||
{
|
||||
if (map_.empty())
|
||||
return false;
|
||||
|
||||
if (ntype == node_type::none)
|
||||
ntype = map_.cbegin()->second->type();
|
||||
|
||||
for (auto&& [k, v] : map_)
|
||||
{
|
||||
TOML_UNUSED(k);
|
||||
if (v->type() != ntype)
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
TOML_PURE_GETTER
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
bool table::is_homogeneous(node_type ntype, node * &first_nonmatch) noexcept
|
||||
{
|
||||
if (map_.empty())
|
||||
{
|
||||
first_nonmatch = {};
|
||||
return false;
|
||||
}
|
||||
if (ntype == node_type::none)
|
||||
ntype = map_.cbegin()->second->type();
|
||||
for (const auto& [k, v] : map_)
|
||||
{
|
||||
TOML_UNUSED(k);
|
||||
if (v->type() != ntype)
|
||||
{
|
||||
first_nonmatch = v.get();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
TOML_PURE_GETTER
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
bool table::is_homogeneous(node_type ntype, const node*& first_nonmatch) const noexcept
|
||||
{
|
||||
node* fnm = nullptr;
|
||||
const auto result = const_cast<table&>(*this).is_homogeneous(ntype, fnm);
|
||||
first_nonmatch = fnm;
|
||||
return result;
|
||||
}
|
||||
|
||||
TOML_PURE_GETTER
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
node* table::get(std::string_view key) noexcept
|
||||
{
|
||||
if (auto it = map_.find(key); it != map_.end())
|
||||
return it->second.get();
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
node& table::at(std::string_view key)
|
||||
{
|
||||
auto n = get(key);
|
||||
|
||||
#if TOML_COMPILER_HAS_EXCEPTIONS
|
||||
|
||||
if (!n)
|
||||
{
|
||||
auto err = "key '"s;
|
||||
err.append(key);
|
||||
err.append("' not found in table"sv);
|
||||
throw std::out_of_range{ err };
|
||||
}
|
||||
|
||||
#else
|
||||
|
||||
TOML_ASSERT_ASSUME(n && "key not found in table!");
|
||||
|
||||
#endif
|
||||
|
||||
return *n;
|
||||
}
|
||||
|
||||
TOML_PURE_GETTER
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
table::map_iterator table::get_lower_bound(std::string_view key) noexcept
|
||||
{
|
||||
return map_.lower_bound(key);
|
||||
}
|
||||
|
||||
TOML_PURE_GETTER
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
table::iterator table::find(std::string_view key) noexcept
|
||||
{
|
||||
return iterator{ map_.find(key) };
|
||||
}
|
||||
|
||||
TOML_PURE_GETTER
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
table::const_iterator table::find(std::string_view key) const noexcept
|
||||
{
|
||||
return const_iterator{ map_.find(key) };
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
table::map_iterator table::erase(const_map_iterator pos) noexcept
|
||||
{
|
||||
return map_.erase(pos);
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
table::map_iterator table::erase(const_map_iterator begin, const_map_iterator end) noexcept
|
||||
{
|
||||
return map_.erase(begin, end);
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
size_t table::erase(std::string_view key) noexcept
|
||||
{
|
||||
if (auto it = map_.find(key); it != map_.end())
|
||||
{
|
||||
map_.erase(it);
|
||||
return size_t{ 1 };
|
||||
}
|
||||
return size_t{};
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
table& table::prune(bool recursive)& noexcept
|
||||
{
|
||||
if (map_.empty())
|
||||
return *this;
|
||||
|
||||
for (auto it = map_.begin(); it != map_.end();)
|
||||
{
|
||||
if (auto arr = it->second->as_array())
|
||||
{
|
||||
if (recursive)
|
||||
arr->prune(true);
|
||||
|
||||
if (arr->empty())
|
||||
{
|
||||
it = map_.erase(it);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
else if (auto tbl = it->second->as_table())
|
||||
{
|
||||
if (recursive)
|
||||
tbl->prune(true);
|
||||
|
||||
if (tbl->empty())
|
||||
{
|
||||
it = map_.erase(it);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
it++;
|
||||
}
|
||||
|
||||
return *this;
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
void table::clear() noexcept
|
||||
{
|
||||
map_.clear();
|
||||
}
|
||||
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
table::map_iterator table::insert_with_hint(const_iterator hint, key && k, impl::node_ptr && v)
|
||||
{
|
||||
return map_.emplace_hint(const_map_iterator{ hint }, std::move(k), std::move(v));
|
||||
}
|
||||
|
||||
TOML_PURE_GETTER
|
||||
TOML_EXTERNAL_LINKAGE
|
||||
bool TOML_CALLCONV table::equal(const table& lhs, const table& rhs) noexcept
|
||||
{
|
||||
if (&lhs == &rhs)
|
||||
return true;
|
||||
if (lhs.map_.size() != rhs.map_.size())
|
||||
return false;
|
||||
|
||||
for (auto l = lhs.map_.begin(), r = rhs.map_.begin(), e = lhs.map_.end(); l != e; l++, r++)
|
||||
{
|
||||
if (l->first != r->first)
|
||||
return false;
|
||||
|
||||
const auto lhs_type = l->second->type();
|
||||
const node& rhs_ = *r->second;
|
||||
const auto rhs_type = rhs_.type();
|
||||
if (lhs_type != rhs_type)
|
||||
return false;
|
||||
|
||||
const bool equal = l->second->visit(
|
||||
[&](const auto& lhs_) noexcept
|
||||
{ return lhs_ == *reinterpret_cast<std::remove_reference_t<decltype(lhs_)>*>(&rhs_); });
|
||||
if (!equal)
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
TOML_NAMESPACE_END;
|
||||
|
||||
#include "header_end.hpp"
|
||||
Loaded 100 of 138 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user