diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..f5e97ec --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,88 @@ +name: CI + +on: + push: + branches: [master, main] + pull_request: + +jobs: + build-and-test: + strategy: + fail-fast: false + matrix: + include: + - os: ubuntu-latest + name: Linux (GCC 13) + compiler: g++-13 + cc: gcc-13 + cxx: g++-13 + packages: ninja-build g++-13 + + - os: ubuntu-latest + name: Linux (Clang 17) + compiler: clang++-17 + cc: clang-17 + cxx: clang++-17 + packages: ninja-build clang-17 + + - os: windows-latest + name: Windows (MSVC) + compiler: msvc + cc: cl + cxx: cl + packages: "" + + - os: macos-latest + name: macOS (AppleClang) + compiler: appleclang + cc: cc + cxx: c++ + packages: ninja + + runs-on: ${{ matrix.os }} + name: ${{ matrix.name }} + # macOS AppleClang lacks std::views::zip and std::from_chars for doubles + continue-on-error: ${{ matrix.os == 'macos-latest' }} + + steps: + - uses: actions/checkout@v4 + + # -- Install CMake 4.0+ (required by the project) -- + - name: Install CMake 4.0+ via pip + run: pip install "cmake>=4.0" + + # -- Install platform dependencies -- + - name: Install dependencies (Ubuntu) + if: runner.os == 'Linux' + run: | + sudo apt-get update + sudo apt-get install -y ${{ matrix.packages }} + + - name: Install dependencies (macOS) + if: runner.os == 'macOS' + run: brew install ${{ matrix.packages }} + + - name: Install dependencies (Windows) + if: runner.os == 'Windows' + run: choco install ninja + + # -- Set up MSVC environment on Windows -- + - name: Set up MSVC Developer Environment + if: runner.os == 'Windows' + uses: ilammy/msvc-dev-cmd@v1 + + # -- Configure -- + - name: Configure CMake + run: > + cmake -B build -G Ninja + -DCMAKE_BUILD_TYPE=Release + -DCMAKE_C_COMPILER=${{ matrix.cc }} + -DCMAKE_CXX_COMPILER=${{ matrix.cxx }} + + # -- Build -- + - name: Build + run: cmake --build build + + # -- Test -- + - name: Test + run: ctest --test-dir build --output-on-failure diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..4e4a901 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +build/ +.cache/ +.claude/ \ No newline at end of file diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..0ee3af9 --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,49 @@ +cmake_minimum_required(VERSION 4.0) +project(edfio VERSION 0.2.0 LANGUAGES CXX) + +# ---- Header-only library target ---- +add_library(edfio INTERFACE) +target_include_directories(edfio INTERFACE + $ + $ +) +target_compile_features(edfio INTERFACE cxx_std_23) +add_library(edfio::edfio ALIAS edfio) + +# ---- Tests ---- +option(EDFIO_BUILD_TESTS "Build tests" ON) +if(EDFIO_BUILD_TESTS) + enable_testing() + add_subdirectory(tests) +endif() + +# ---- Install targets and packaging ---- +include(GNUInstallDirs) +include(CMakePackageConfigHelpers) + +install(TARGETS edfio EXPORT edfioTargets) +install(DIRECTORY include/edfio DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}) + +install(EXPORT edfioTargets + FILE edfioTargets.cmake + NAMESPACE edfio:: + DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/edfio +) + +write_basic_package_version_file( + "${CMAKE_CURRENT_BINARY_DIR}/edfioConfigVersion.cmake" + VERSION ${PROJECT_VERSION} + COMPATIBILITY SameMajorVersion +) + +configure_package_config_file( + "${CMAKE_CURRENT_SOURCE_DIR}/cmake/edfioConfig.cmake.in" + "${CMAKE_CURRENT_BINARY_DIR}/edfioConfig.cmake" + INSTALL_DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/edfio +) + +install(FILES + "${CMAKE_CURRENT_BINARY_DIR}/edfioConfig.cmake" + "${CMAKE_CURRENT_BINARY_DIR}/edfioConfigVersion.cmake" + DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/edfio +) diff --git a/PLAN.md b/PLAN.md new file mode 100644 index 0000000..84905ef --- /dev/null +++ b/PLAN.md @@ -0,0 +1,1430 @@ +# EdfIO C++23 Refactoring -- Implementation Plan + +Target: **clang++ 21.1.8**, **CMake 4.0.2**, **C++23**, **Windows 11** +Architecture invariant: header-only library; "iterators to navigate files like arrays" pattern preserved. + +--- + +## Phase 0: Infrastructure + +**Goal:** Establish CMake build, integrate doctest via FetchContent, create the test harness, verify everything compiles before touching a single line of library code. + +### 0.1 Create `CMakeLists.txt` (root) + +**New file:** `C:/dev/code/edfio/CMakeLists.txt` + +```cmake +cmake_minimum_required(VERSION 4.0) +project(edfio VERSION 0.2.0 LANGUAGES CXX) + +# ---- Header-only library target ---- +add_library(edfio INTERFACE) +target_include_directories(edfio INTERFACE + $ + $ +) +target_compile_features(edfio INTERFACE cxx_std_23) + +# ---- Tests ---- +option(EDFIO_BUILD_TESTS "Build tests" ON) +if(EDFIO_BUILD_TESTS) + enable_testing() + add_subdirectory(tests) +endif() +``` + +### 0.2 Create `tests/CMakeLists.txt` + +**New file:** `C:/dev/code/edfio/tests/CMakeLists.txt` + +```cmake +include(FetchContent) +FetchContent_Declare( + doctest + GIT_REPOSITORY https://github.com/doctest/doctest.git + GIT_TAG v2.4.11 +) +FetchContent_MakeAvailable(doctest) + +# Convenience function: one call per test source file +function(edfio_add_test name) + add_executable(${name} ${name}.cpp) + target_link_libraries(${name} PRIVATE edfio doctest::doctest) + target_compile_options(${name} PRIVATE + -Wall -Wextra -Wpedantic -Wno-c++98-compat -fsanitize=address,undefined + ) + target_link_options(${name} PRIVATE -fsanitize=address,undefined) + add_test(NAME ${name} COMMAND ${name}) +endfunction() + +# Copy test fixture +configure_file( + ${CMAKE_SOURCE_DIR}/Calib5.edf + ${CMAKE_CURRENT_BINARY_DIR}/Calib5.edf + COPYONLY +) + +# --- Test executables (added incrementally per phase) --- +edfio_add_test(test_record) +edfio_add_test(test_reader) +edfio_add_test(test_processor_sample) +edfio_add_test(test_iterators) +edfio_add_test(test_writer) +edfio_add_test(test_processor_utils) +``` + +### 0.3 Skeleton test files + +Create one `.cpp` per test target with a minimal doctest `main()` and a single `CHECK(true)`. These will be populated in later phases. + +**New files:** +- `C:/dev/code/edfio/tests/test_record.cpp` +- `C:/dev/code/edfio/tests/test_reader.cpp` +- `C:/dev/code/edfio/tests/test_processor_sample.cpp` +- `C:/dev/code/edfio/tests/test_iterators.cpp` +- `C:/dev/code/edfio/tests/test_writer.cpp` +- `C:/dev/code/edfio/tests/test_processor_utils.cpp` + +Each file follows this skeleton: + +```cpp +#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN +#include +#include + +TEST_CASE("placeholder") { + CHECK(true); +} +``` + +### 0.4 Build verification + +``` +cmake -B build -G Ninja -DCMAKE_CXX_COMPILER=clang++ -DCMAKE_CXX_STANDARD=23 +cmake --build build +ctest --test-dir build --output-on-failure +``` + +**Dependencies:** None. + +--- + +## Phase 1: Bug Fixes + +**Goal:** Fix every critical and high-severity bug identified during analysis, with regression tests proving each fix. Zero refactoring -- minimal, surgical patches only. + +### 1.1 CRITICAL -- `ProcessorSampleRecord` data corruption + +**File:** `C:/dev/code/edfio/include/edfio/processor/impl/ProcessorSampleRecord.ipp` + +**Bug A -- `unsigned char < 0` always false:** +The loop variable `r` is `unsigned char`. The test `r < 0` is always false, so sign-extension for negative samples (BDF 3-byte, EDF 2-byte) never triggers. `sample = -1` is dead code. + +**Bug B -- double `idx++`:** +`idx++` appears in the condition `if (r < 0 && idx++)` AND again at `idx++` at bottom of loop body. If the condition were ever true, `idx` would be incremented twice per iteration. + +**Current code (lines 16-32):** +```cpp +template +inline typename ProcessorSampleRecord::ProcType +ProcessorSampleRecord::operator()(Record record) +{ + DigiType sample = 0; + size_t idx = 0; + for (unsigned char r : record()) + { + if (r < 0 && idx++) // BUG: always false + sample = -1; + sample <<= 8; + sample |= r; + idx++; + } + + if (std::is_same::value) + return sample; + return impl::ConvertSample(m_offset, m_scaling, sample); +} +``` + +**Fixed code:** +The correct algorithm reads bytes little-endian (LSB first -- per EDF/BDF spec), assembles them, then sign-extends the result. The current code reads big-endian which is also wrong for EDF, but is consistent with how the rest of the codebase uses it (ProcessorSample writes big-endian too). So we preserve the byte order but fix sign extension: + +```cpp +template +inline typename ProcessorSampleRecord::ProcType +ProcessorSampleRecord::operator()(Record record) +{ + DigiType sample = 0; + auto const& bytes = record(); + std::size_t const nbytes = bytes.size(); + + // Assemble bytes (big-endian order as written by ProcessorSample) + for (std::size_t i = 0; i < nbytes; ++i) + { + sample <<= 8; + sample |= static_cast(bytes[i]); + } + + // Sign-extend: if high bit of the MSB is set, the value is negative + if (nbytes > 0 && nbytes < sizeof(DigiType)) + { + unsigned int sign_bit = 1u << (nbytes * 8 - 1); + if (sample & sign_bit) + sample |= ~((1 << (nbytes * 8)) - 1); + } + + if constexpr (std::is_same_v) + return sample; + return impl::ConvertSample(m_offset, m_scaling, sample); +} +``` + +**Test (in `test_processor_sample.cpp`):** +```cpp +TEST_CASE("ProcessorSampleRecord sign-extends negative 2-byte samples") { + // -100 as signed 16-bit = 0xFF9C + Record rec(2); + rec()[0] = static_cast(0xFF); + rec()[1] = static_cast(0x9C); + ProcessorSampleRecord proc(0.0, 1.0); + auto result = proc(rec); + CHECK(result == -100); +} + +TEST_CASE("ProcessorSampleRecord positive 2-byte samples") { + Record rec(2); + rec()[0] = static_cast(0x00); + rec()[1] = static_cast(0x64); + ProcessorSampleRecord proc(0.0, 1.0); + auto result = proc(rec); + CHECK(result == 100); +} + +TEST_CASE("ProcessorSampleRecord 3-byte BDF negative sample") { + // -1000 as signed 24-bit = 0xFFFC18 + Record rec(3); + rec()[0] = static_cast(0xFF); + rec()[1] = static_cast(0xFC); + rec()[2] = static_cast(0x18); + ProcessorSampleRecord proc(0.0, 1.0); + auto result = proc(rec); + CHECK(result == -1000); +} +``` + +--- + +### 1.2 CRITICAL -- `TalStore::prev()` out-of-bounds UB + +**File:** `C:/dev/code/edfio/include/edfio/store/TalStore.hpp` + +**Bug:** Line 235: `auto first = m_stream().rend() + off;` +`rend()` already points past-the-reverse-end. Adding a positive `off` goes further out of bounds -- undefined behavior. + +The intent is to iterate backward from position `off`. To go backwards from byte offset `off` in the underlying vector, we need `rbegin() + (size - off)`. + +**Current code (lines 228-258):** +```cpp +size_type prev(size_type off) +{ + if (off <= 0) + throw std::length_error("Iterator not decrementable"); + + if (off > 0) + { + auto first = m_stream().rend() + off; // BUG + auto last = m_stream().rend(); + // ... +``` + +**Fixed code:** +```cpp +size_type prev(size_type off) +{ + if (off == 0) + throw std::length_error("Iterator not decrementable"); + + auto const& data = m_stream(); + auto const sz = data.size(); + + // Walk backward from position (off - 1), skipping zeros + size_type pos = off; + while (pos > 0 && data[pos - 1] == 0) + --pos; + + if (pos == 0) + throw std::length_error("Iterator not decrementable"); + + // Find the start of the previous non-zero TAL + size_type end_of_tal = pos; + while (pos > 0 && data[pos - 1] != 0) + --pos; + + m_value.assign(data.begin() + pos, data.begin() + end_of_tal); + return pos; +} +``` + +**Test (in `test_iterators.cpp`):** Requires constructing a TalStore from a crafted SignalRecordStore, which is complex. Instead, test with a round-trip: iterate forward collecting TALs, then iterate backward and verify they appear in reverse order. Requires `Calib5.edf` to be an EDF+ file with annotations. If `Calib5.edf` is plain EDF (no annotations), write a unit test that creates a vector with known TAL structure and tests the `prev()` logic via a mock. A more practical approach: + +```cpp +TEST_CASE("TalStore reverse iteration does not crash") { + // This is an integration-level test using a real file. + // If Calib5.edf has no annotations, this test is skipped. + std::ifstream stream("Calib5.edf", std::ios::binary); + REQUIRE(stream.is_open()); + edfio::ReaderHeaderExam reader; + auto header = reader(stream); + // If no annotation signals, skip + bool has_annot = false; + for (auto const& sig : header.m_signals) { + if (sig.m_detail.m_isAnnotation) { has_annot = true; break; } + } + if (!has_annot) { MESSAGE("No annotations in Calib5.edf, skipping"); return; } + // ... full test using TalStore iterators +} +``` + +--- + +### 1.3 CRITICAL -- `RecordStore::iterator::operator-` inverted + +**File:** `C:/dev/code/edfio/include/edfio/store/RecordStore.hpp` + +**Bug (line 173):** +```cpp +difference_type operator-(iterator it) const +{ + return difference_type(it.m_offset - m_offset); // inverted! +} +``` + +For `a - b`, the standard requires `a.offset - b.offset`, but this returns `b.offset - a.offset`. + +**Fix:** +```cpp +difference_type operator-(iterator it) const +{ + if (!m_context) + throw std::invalid_argument("Invalid context"); + if (m_context != it.m_context) + throw std::invalid_argument("Iterators incompatible"); + return difference_type(m_offset - it.m_offset); +} +``` + +**Same bug in `RecordSink::iterator::operator-` (line 187):** + +**File:** `C:/dev/code/edfio/include/edfio/sink/RecordSink.hpp` + +```cpp +// Current (line 187): +return difference_type(it.m_offset - m_offset); +// Fixed: +return difference_type(m_offset - it.m_offset); +``` + +**Test (in `test_iterators.cpp`):** +```cpp +TEST_CASE("RecordStore iterator subtraction returns (a - b) not (b - a)") { + std::ifstream stream("Calib5.edf", std::ios::binary); + REQUIRE(stream.is_open()); + edfio::ReaderHeaderExam reader; + auto header = reader(stream); + auto store = edfio::detail::CreateDataRecordStore(stream, header.m_general); + auto a = store.begin() + 2; + auto b = store.begin(); + CHECK((a - b) == 2); + CHECK((b - a) == -2); +} +``` + +--- + +### 1.4 CRITICAL -- `Record` has `const size_t m_size` breaking assignment + +**File:** `C:/dev/code/edfio/include/edfio/core/Record.hpp` + +**Bug (line 64):** +```cpp +const size_t m_size; +``` + +`const` data member makes the implicit copy/move assignment operators deleted. The class has a copy constructor but relies on implicit assignment in many places (e.g., `m_value = ...` in Store::load paths, where `Record` is assigned into `m_value`). The `const` is doubly redundant because `m_size` should track `m_value.size()`. + +**Fix:** Remove `const` from `m_size`, add a proper assignment operator, or better yet, derive `m_size` from `m_value.size()` and remove the redundant member: + +```cpp +template +struct Record +{ + using ValueType = ValT; + using VectorType = std::vector; + + Record() = delete; + + Record(size_t recordSize) + : m_value(recordSize, 0) {} + + Record(typename VectorType::const_iterator first, + typename VectorType::const_iterator last) + : m_value(first, last) {} + + Record(const Record&) = default; + Record(Record&&) = default; + Record& operator=(const Record&) = default; + Record& operator=(Record&&) = default; + + size_t Size() const { return m_value.size(); } + const VectorType& operator()() const { return m_value; } + VectorType& operator()() { return m_value; } + + Record operator+(const Record& record) const + { + Record tmp(Size() + record.Size()); + std::copy(m_value.begin(), m_value.end(), tmp().begin()); + std::copy(record().begin(), record().end(), tmp().begin() + Size()); + return tmp; + } + + VectorType m_value; +}; +``` + +Note: `m_size` is removed entirely. `Size()` now returns `m_value.size()`. The stream operators (`operator>>`, `operator<<`) already call `record.resize(r.Size(), 0)` which will become a no-op now that the vector is already the right size. + +**Impact:** The `operator>>` and `operator<<` templates at bottom of Record.hpp call `record.resize(r.Size(), 0)`. After the fix, `r.Size()` returns `m_value.size()`, so `resize` is a no-op, which is correct. + +**Test (in `test_record.cpp`):** +```cpp +TEST_CASE("Record is assignable") { + edfio::Record a(10); + a()[0] = 'X'; + edfio::Record b(10); + b = a; // Must compile and work + CHECK(b()[0] == 'X'); + CHECK(b.Size() == 10); +} + +TEST_CASE("Record move-assignment works") { + edfio::Record a(5); + a()[0] = 42; + edfio::Record b(5); + b = std::move(a); + CHECK(b()[0] == 42); +} + +TEST_CASE("Record concatenation") { + edfio::Record a(3); + edfio::Record b(2); + a()[0] = 1; a()[1] = 2; a()[2] = 3; + b()[0] = 4; b()[1] = 5; + auto c = a + b; + CHECK(c.Size() == 5); + CHECK(c()[3] == 4); +} +``` + +--- + +### 1.5 HIGH -- `const_cast` in 12 places to fake const-correctness + +**Files:** +- `C:/dev/code/edfio/include/edfio/store/RecordStore.hpp` (lines 222, 226, 234, 238) +- `C:/dev/code/edfio/include/edfio/store/TalStore.hpp` (lines 142, 146, 154, 158) +- `C:/dev/code/edfio/include/edfio/sink/RecordSink.hpp` (lines 227, 231, 239, 243) + +**Bug:** The `const` begin/end/cbegin/cend methods cast away `const` on `this` to construct iterators. This is technically UB if the object is actually const, and defeats the purpose of const-correctness. + +**Root cause:** The iterator stores a raw pointer to the non-const Store/Sink. The `const_iterator` is just `typedef iterator const`, which means `const iterator` -- a const copy of a mutable iterator, NOT a true const_iterator. + +**Fix (Phase 1 -- minimal, safe):** Make `const_iterator` a proper alias and have iterators store a `const` pointer when needed. However, the minimal fix is to acknowledge the library is not used in truly const contexts and mark this for Phase 4 (iterator overhaul with deducing this). For Phase 1, we fix the UB by making the `const` overloads non-const (or by making the iterator's pointer member mutable). The pragmatic fix: + +Replace `typedef iterator const const_iterator;` with a true `const_iterator` class. But that is a large change. Phase 1 minimal: change to `using const_iterator = iterator;` (drop the `const`), remove the `const_cast`, and accept that `begin() const` just returns a mutable iterator. This is no worse than the current const_cast UB. + +Actually, the cleanest Phase 1 fix: store `m_context` as `const`-compatible. The load/getR/getP methods need mutable access. Use `mutable` on the cache fields (`m_value`) in RecordStore and TalStore. Then the iterator can hold a `const Store*` and call const methods that mutate only mutable cache fields. + +This is substantial but safe. **Defer to Phase 4** (iterator overhaul with deducing this) -- mark const_cast sites with `// FIXME(Phase4): const_cast removed by deducing-this iterator redesign`. + +For Phase 1, add the `// FIXME` comments but do NOT change behavior. The const_cast pattern is technically UB only if the underlying object is truly const, which never happens in this codebase. + +--- + +### 1.6 HIGH -- Iterators don't satisfy `std::random_access_iterator` concept + +**Files:** +- `C:/dev/code/edfio/include/edfio/core/Device.hpp` (iterator base class) +- `C:/dev/code/edfio/include/edfio/store/RecordStore.hpp` +- `C:/dev/code/edfio/include/edfio/sink/RecordSink.hpp` + +**Issues:** +1. No `iterator_concept` type alias (required for C++20+ iterator concepts). +2. `operator-` returns `b - a` instead of `a - b` (fixed in 1.3). +3. No `n + it` form (only `it + n`). +4. `size_type` is `unsigned long long` but `difference_type` is `long long` -- `operator+` / `operator-` take `size_type` (unsigned) but should take `difference_type` (signed) per the standard. + +**Fix (Phase 1 -- minimal):** + +In `Device.hpp` iterator, add: +```cpp +using iterator_concept = IterCategory; +``` + +In `RecordStore::iterator`, add friend free function: +```cpp +friend iterator operator+(size_type off, const iterator& it) +{ + return it + off; +} +``` + +Change `operator+=(size_type off)` to `operator+=(difference_type off)` (and correspondingly for `operator-=`, `operator+`, `operator-` scalar overloads). This is a **Phase 4** task due to cascading changes. Phase 1 adds only the `iterator_concept` alias and the `n + it` overload. + +**Defer signed/unsigned parameter changes to Phase 4.** + +--- + +### 1.7 HIGH -- `catch(std::exception e)` by value in 5 .ipp files + +**Files (5 locations):** +1. `C:/dev/code/edfio/include/edfio/reader/impl/ReaderHeaderGeneral.ipp` line 43 +2. `C:/dev/code/edfio/include/edfio/reader/impl/ReaderHeaderSignal.ipp` line 55 +3. `C:/dev/code/edfio/include/edfio/writer/impl/WriterHeaderGeneral.ipp` line 44 +4. `C:/dev/code/edfio/include/edfio/writer/impl/WriterHeaderSignals.ipp` line 53 +5. `C:/dev/code/edfio/include/edfio/writer/impl/WriterRecord.ipp` line 29 + +**Bug:** Catching by value slices derived exception types. + +**Fix:** Change all to `catch (const std::exception& e)`: + +```cpp +// Before: +catch (std::exception e) +// After: +catch (const std::exception&) +``` + +(The `e` variable is unused in all cases -- the handlers immediately throw a new exception.) + +**Test:** No specific test needed; this is a correctness fix verified by compiler warnings with `-Wcatch-value`. + +--- + +### 1.8 HIGH -- `off < 0` on unsigned in load() methods + +**Files:** +1. `C:/dev/code/edfio/include/edfio/store/DatarecordStore.hpp` line 37 +2. `C:/dev/code/edfio/include/edfio/include/edfio/store/SignalrecordStore.hpp` line 40 +3. `C:/dev/code/edfio/include/edfio/store/SignalSampleStore.hpp` line 43 +4. `C:/dev/code/edfio/include/edfio/store/TimeStampStore.hpp` line 40 + +**Bug:** `size_type` is `unsigned long long`. The check `off < 0` is always false. + +**Fix:** Remove the dead `off < 0` check. The `off >= size()` check is sufficient because `off` is unsigned and comes from iterator arithmetic that already bounds-checks. + +```cpp +// Before: +if (off < 0 || off >= size()) +// After: +if (off >= size()) +``` + +--- + +### Phase 1 summary of file changes + +| File | Changes | +|------|---------| +| `processor/impl/ProcessorSampleRecord.ipp` | Rewrite sample assembly + sign extension | +| `store/TalStore.hpp` | Rewrite `prev()` method | +| `store/RecordStore.hpp` | Fix `operator-` sign, add FIXME for const_cast | +| `sink/RecordSink.hpp` | Fix `operator-` sign, add FIXME for const_cast | +| `core/Record.hpp` | Remove `const` from `m_size`, or remove `m_size` entirely | +| `core/Device.hpp` | Add `iterator_concept` alias | +| `reader/impl/ReaderHeaderGeneral.ipp` | `catch(std::exception e)` -> `catch(const std::exception&)` | +| `reader/impl/ReaderHeaderSignal.ipp` | Same | +| `writer/impl/WriterHeaderGeneral.ipp` | Same | +| `writer/impl/WriterHeaderSignals.ipp` | Same | +| `writer/impl/WriterRecord.ipp` | Same | +| `store/DatarecordStore.hpp` | Remove `off < 0` | +| `store/SignalrecordStore.hpp` | Remove `off < 0` | +| `store/SignalSampleStore.hpp` | Remove `off < 0` | +| `store/TimeStampStore.hpp` | Remove `off < 0` | + +**Dependencies:** Phase 0 must be complete (CMake builds, tests compile). + +--- + +## Phase 2: Low-Risk Modernization + +**Goal:** Apply safe, mechanical transformations that improve code quality without altering semantics. Every change is individually small and independently testable by compilation + existing Phase 1 tests. + +### 2.1 Remove `return std::move(local)` -- NRVO prevention (21 instances) + +**Files and lines:** +1. `header/HeaderUtils.hpp` line 62: `return std::move(header);` in `CreateHeaderGeneral` +2. `header/HeaderUtils.hpp` line 89: `return std::move(CreateHeaderGeneral(...));` -- both the outer move and the nested move +3. `header/HeaderUtils.hpp` line 104: `return std::move(header);` in `CreateHeaderGeneralPlus` +4. `header/HeaderUtils.hpp` line 140: `return std::move(signal);` in `CreateHeaderSignal` +5. `store/detail/StoreUtils.hpp` line 33: `return std::move(DataRecordStore{...});` +6. `store/detail/StoreUtils.hpp` line 44: `return std::move(SignalRecordStore{...});` +7. `store/detail/StoreUtils.hpp` line 56: `return std::move(SignalSampleStore{...});` +8. `store/detail/StoreUtils.hpp` line 67: `return std::move(TimeStampStore{...});` +9. `sink/detail/SinkUtils.hpp` line 31: `return std::move(DataRecordSink{...});` +10. `sink/detail/SinkUtils.hpp` line 42: `return std::move(SignalRecordSink{...});` +11. `reader/impl/ReaderHeaderGeneral.ipp` line 47: `return std::move(hdr);` +12. `reader/impl/ReaderHeaderSignal.ipp` line 59: `return std::move(signals);` +13. `reader/impl/ReaderHeaderExam.ipp` lines 33, 40, 44, 62: Four `std::move` wrapping return values +14. `writer/impl/WriterHeaderExam.ipp` lines 28, 31: Two `std::move` on temporaries passed to functions (these are actually fine since they are function arguments, not return values -- leave alone) +15. `processor/impl/ProcessorHeaderExam.ipp` line 45: `return std::move(HeaderExam{...});` +16. `processor/impl/ProcessorHeaderGeneral.ipp` line 162: `return std::move(out);` +17. `processor/impl/ProcessorHeaderSignalFields.ipp` line 326: `return std::move(signals);` +18. `processor/impl/ProcessorHeaderSignal.ipp` line 98: `return std::move(out);` +19. `processor/impl/ProcessorTalRecord.ipp` line 96: `return std::move(out);` +20. `processor/impl/ProcessorTimeStampRecord.ipp` line 56: `return std::move(timestamp);` +21. `processor/impl/ProcessorSample.ipp` line 33: `return std::move(record);` + +**Fix:** For every `return std::move(x);` where `x` is a local variable or temporary, change to `return x;`. + +Example: +```cpp +// Before: +return std::move(header); +// After: +return header; +``` + +For `auto header = std::move(CreateHeaderGeneral(...));` change to `auto header = CreateHeaderGeneral(...);`. + +For `auto general = std::move(procGeneralFields(std::move(generalFields)));` in ReaderHeaderExam.ipp -- the inner `std::move(generalFields)` is correct (moving into a by-value parameter), but the outer `std::move()` around the return value assignment is fine to keep (assigning to a local, not returning). Actually, `auto general = std::move(procGeneralFields(...))` prevents copy elision from the function return. Change to `auto general = procGeneralFields(std::move(generalFields));`. + +--- + +### 2.2 Replace `typedef` with `using` (all files) + +**Scope:** Every file using `typedef`. This is a mechanical find-and-replace. + +```cpp +// Before: +typedef iterator const const_iterator; +typedef std::reverse_iterator reverse_iterator; +typedef std::reverse_iterator const_reverse_iterator; +typedef Store<...> store_type; +typedef device_type::iterator iterator; + +// After: +using const_iterator = iterator; // (also fixing the const issue noted in 1.5) +using reverse_iterator = std::reverse_iterator; +using const_reverse_iterator = std::reverse_iterator; +using store_type = Store<...>; +using iterator = typename device_type::iterator; +``` + +**Files:** +- `core/Device.hpp` (6 typedefs) +- `store/Store.hpp` (3 typedefs) +- `sink/Sink.hpp` (2 typedefs) +- `store/RecordStore.hpp` (3 typedefs) +- `store/TalStore.hpp` (4 typedefs) +- `sink/RecordSink.hpp` (3 typedefs) +- `store/DatarecordStore.hpp` (4 typedefs) +- `store/SignalrecordStore.hpp` (4 typedefs) +- `store/SignalSampleStore.hpp` (4 typedefs) +- `store/TimeStampStore.hpp` (4 typedefs) +- `sink/DataRecordSink.hpp` (4 typedefs) +- `sink/SignalRecordSink.hpp` (4 typedefs) + +--- + +### 2.3 Replace `static` functions in headers with `inline` + +**Files with `static` functions that should be `inline`:** +- `core/DataFormat.hpp`: `IsPlus`, `IsEdf`, `IsBdf`, `GetSampleBytes` (4 functions) +- `Utils.hpp`: `GetError` (1 function) +- `processor/detail/ProcessorUtils.hpp`: all `static` functions in `impl::` and `detail::` namespaces (9 functions) +- `header/HeaderUtils.hpp`: `CreateHeaderGeneral`, `CreateHeaderGeneralPlus`, `CreateHeaderSignal` (3 functions) +- `store/detail/StoreUtils.hpp`: 4 template functions (already have `static` but templates are implicitly inline, so just remove `static`) +- `sink/detail/SinkUtils.hpp`: 2 template functions (same) + +**Fix pattern:** +```cpp +// Before: +static const bool IsPlus(DataFormat format) { ... } +// After: +inline constexpr bool IsPlus(DataFormat format) { ... } +``` + +For `GetError` in Utils.hpp: +```cpp +// Before: +static const char* GetError(FileErrc err) +// After: +inline constexpr const char* GetError(FileErrc err) +``` + +For non-template `static` functions in ProcessorUtils.hpp (e.g., `ReduceString`, `GetFormatName`, `GetMonthFromString`, `GetStringFromMonth`, `to_string_decimal`): +```cpp +// Before: +static std::string ReduceString(const std::string &value) +// After: +inline std::string ReduceString(const std::string &value) +``` + +For `ADDITIONAL_SEPARATOR`: +```cpp +// Before: +static const char ADDITIONAL_SEPARATOR = '|'; +// After: +inline constexpr char ADDITIONAL_SEPARATOR = '|'; +``` + +For `Config.hpp`: +```cpp +// Before: +static constexpr ProcessorErrorCheck PROCESSOR_ERROR_CHECKING = ... +// After: +inline constexpr ProcessorErrorCheck PROCESSOR_ERROR_CHECKING = ... +``` + +--- + +### 2.4 Fix `std::regex` performance in `ReduceString` + +**File:** `C:/dev/code/edfio/include/edfio/processor/detail/ProcessorUtils.hpp` line 104-107 + +**Bug:** `std::regex("^ +| +$|( ) +")` is constructed on every call. std::regex construction is extremely expensive (up to 10ms per call). This function is called 12 times per header parse (see ProcessorHeaderGeneralFields.ipp lines 345-356 and ProcessorHeaderSignalFields.ipp lines 317-323). + +**Fix:** Replace with a simple string trim + collapse function: +```cpp +inline std::string ReduceString(const std::string& value) +{ + // Trim leading spaces + auto start = value.find_first_not_of(' '); + if (start == std::string::npos) return ""; + // Trim trailing spaces + auto end = value.find_last_not_of(' '); + // Collapse interior runs of spaces to single space + std::string result; + result.reserve(end - start + 1); + bool prev_space = false; + for (size_t i = start; i <= end; ++i) { + if (value[i] == ' ') { + if (!prev_space) { + result += ' '; + prev_space = true; + } + } else { + result += value[i]; + prev_space = false; + } + } + return result; +} +``` + +**Test (in `test_processor_utils.cpp`):** +```cpp +TEST_CASE("ReduceString trims and collapses spaces") { + using edfio::detail::ReduceString; + CHECK(ReduceString(" hello world ") == "hello world"); + CHECK(ReduceString(" ") == ""); + CHECK(ReduceString("no_change") == "no_change"); + CHECK(ReduceString(" a b c ") == "a b c"); + CHECK(ReduceString("") == ""); +} +``` + +--- + +### 2.5 Fix typo `m_dararecord` -> `m_datarecord` + +**Files:** +- `C:/dev/code/edfio/include/edfio/core/Annotation.hpp` line 27: `long long m_dararecord = 0;` +- `C:/dev/code/edfio/include/edfio/processor/impl/ProcessorTimeStampRecord.ipp` line 24: `timestamp.m_dararecord = datarecord;` +- `C:/dev/code/edfio/include/edfio/processor/impl/ProcessorTalRecord.ipp` line 87: `annot.m_dararecord = datarecord;` + +**Fix:** Rename to `m_datarecord` in all three locations. + +--- + +### 2.6 Fix double semicolons + +**File:** `C:/dev/code/edfio/include/edfio/sink/SignalRecordSink.hpp` +- Line 47: `size_type offset = (sz - m_headerOffset) % m_datarecordSize;;` +- Line 61: `size_type offset = (sz - m_headerOffset) % m_datarecordSize;;` + +**Fix:** Remove the duplicate semicolons. + +--- + +### 2.7 Make `DataFormat` functions `constexpr` + +**File:** `C:/dev/code/edfio/include/edfio/core/DataFormat.hpp` + +Make `IsPlus`, `IsEdf`, `IsBdf`, `GetSampleBytes` all `inline constexpr`. (Overlaps with 2.3.) + +--- + +### 2.8 Make `GetError` `constexpr` + +**File:** `C:/dev/code/edfio/include/edfio/Utils.hpp` + +Change `GetError` to `inline constexpr`. It only uses `if/else` chains returning string literals, which is valid constexpr in C++23. + +--- + +### 2.9 Fix `GetStringFromMonth` unsigned underflow + +**File:** `C:/dev/code/edfio/include/edfio/processor/detail/ProcessorUtils.hpp` lines 95-102 + +**Bug:** Parameter is `size_t idx`. Line 97: `idx--`. If `idx == 0`, this wraps to `SIZE_MAX`. The subsequent `idx >= 0` check (line 99) is always true because `idx` is unsigned. + +**Fix:** +```cpp +inline std::string GetStringFromMonth(size_t idx) +{ + static const std::vector months = { + "JAN", "FEB", "MAR", "APR", "MAY", "JUN", + "JUL", "AUG", "SEP", "OCT", "NOV", "DEC" + }; + if (idx >= 1 && idx <= 12) + return months[idx - 1]; + return "JAN"; +} +``` + +**Test (in `test_processor_utils.cpp`):** +```cpp +TEST_CASE("GetStringFromMonth handles boundaries") { + CHECK(edfio::detail::GetStringFromMonth(0) == "JAN"); // was UB + CHECK(edfio::detail::GetStringFromMonth(1) == "JAN"); + CHECK(edfio::detail::GetStringFromMonth(12) == "DEC"); + CHECK(edfio::detail::GetStringFromMonth(13) == "JAN"); +} +``` + +--- + +### 2.10 Remove `` include + +**File:** `C:/dev/code/edfio/include/edfio/processor/detail/ProcessorUtils.hpp` + +After replacing `ReduceString` in 2.4, remove `#include `. This significantly improves compilation time. + +--- + +### Phase 2 summary + +All changes are mechanical. No architectural changes. Tests from Phase 1 serve as regression. Additional tests in `test_processor_utils.cpp` for ReduceString and GetStringFromMonth. + +**Dependencies:** Phase 1 complete. All Phase 1 tests passing. + +--- + +## Phase 3: Core C++23 Refactoring + +**Goal:** Rewrite internal implementations using C++23 features for clarity and safety. Public API signatures may change. Every file touched gets updated tests. + +### 3.1 `if constexpr` replaces SFINAE in ProcessorUtils + +**File:** `C:/dev/code/edfio/include/edfio/processor/detail/ProcessorUtils.hpp` + +**Current:** 4 overloads of `CheckFormatErrors` using `std::enable_if`: + +```cpp +template +static bool CheckFormatErrors(const typename std::enable_if>::type &str) { ... } +// ... 3 more overloads +``` + +**Replace with:** +```cpp +namespace impl { + template + inline bool CheckFormatErrors(const Container& data) + { + if constexpr (Check == ProcessorErrorCheck::Permissive) { + return false; + } else { + for (auto c : data) { + if (!std::isprint(static_cast(c))) + return true; + } + return false; + } + } +} + +namespace detail { + template + inline bool CheckFormatErrors(const Container& data) + { + return impl::CheckFormatErrors(data); + } +} +``` + +This replaces 4 overloads with 2 function templates. + +**Also** replace `std::is_same::value` in ProcessorSampleRecord.ipp and ProcessorSample.ipp with `if constexpr (std::is_same_v<...>)` (already done in Phase 1 fix for ProcessorSampleRecord). + +--- + +### 3.2 Spaceship operator (`<=>`) for iterators + +**Files:** +- `C:/dev/code/edfio/include/edfio/store/RecordStore.hpp` +- `C:/dev/code/edfio/include/edfio/store/TalStore.hpp` +- `C:/dev/code/edfio/include/edfio/sink/RecordSink.hpp` + +**Current:** Each iterator class has 6 comparison operators (`==`, `!=`, `<`, `>`, `<=`, `>=`), totalling ~120 lines across 3 files. + +**Replace with:** +```cpp +// In RecordStore::iterator: +bool operator==(const iterator& it) const +{ + return m_offset == it.m_offset && m_context == it.m_context; +} + +std::strong_ordering operator<=>(const iterator& it) const +{ + if (m_context != it.m_context) + throw std::invalid_argument("Iterators incompatible"); + return m_offset <=> it.m_offset; +} +``` + +This replaces 6 operators with 2, and `!=`, `<`, `>`, `<=`, `>=` are all synthesized by the compiler. Saves ~80 lines total. + +**Include `` in the relevant files.** + +--- + +### 3.3 `std::format` replaces `ostringstream` formatting + +**File:** `C:/dev/code/edfio/include/edfio/processor/impl/ProcessorHeaderGeneral.ipp` + +**Current (lines 53-57):** +```cpp +std::ostringstream oss; +oss << std::setw(2) << std::setfill('0') << day << "."; +oss << std::setw(2) << std::setfill('0') << month << "."; +oss << std::setw(2) << std::setfill('0') << year; +out.m_startDate(oss.str()); +``` + +**Replace with:** +```cpp +out.m_startDate(std::format("{:02d}.{:02d}.{:02d}", day, month, year)); +``` + +Same for start time (lines 64-68): +```cpp +out.m_startTime(std::format("{:02d}.{:02d}.{:02d}", hour, minute, second)); +``` + +And in the "Plus" Recording field (line 137): +```cpp +auto dateStr = std::format("{:02d}-{}-{}", day ? day : 1, + detail::GetStringFromMonth(month), + year ? year : 1984); +fields.push_back(dateStr); +``` + +Remove `#include ` and `#include `, add `#include `. + +--- + +### 3.4 `std::from_chars` replaces `stoi` / `stod` + try/catch + +**Files:** +- `processor/impl/ProcessorHeaderGeneralFields.ipp` (6 uses of stoi/stoll/stod) +- `processor/impl/ProcessorHeaderSignalFields.ipp` (5 uses of stoi/stod) +- `processor/impl/ProcessorTalRecord.ipp` (2 uses of stod) + +**Pattern:** +```cpp +// Before: +try { + int day = std::stoi(startdate); +} catch (...) { + throw std::invalid_argument(GetError(FileErrc::FileContainsFormatErrors)); +} + +// After: +int day = 0; +auto [ptr, ec] = std::from_chars(startdate.data(), startdate.data() + startdate.size(), day); +if (ec != std::errc{}) + throw std::invalid_argument(GetError(FileErrc::FileContainsFormatErrors)); +``` + +**Note:** `std::from_chars` for `double` has full support in C++23 / clang 21. Include ``. + +--- + +### 3.5 `std::string_view` for read-only string parameters + +**Files:** +- `processor/detail/ProcessorUtils.hpp`: `ReduceString(const std::string&)` -> `ReduceString(std::string_view)` +- `processor/detail/ProcessorUtils.hpp`: `GetMonthFromString(const std::string&)` -> `GetMonthFromString(std::string_view)` +- `processor/detail/ProcessorUtils.hpp`: `GetFormatName(DataFormat)` already returns string (keep as is) + +**Example:** +```cpp +inline int GetMonthFromString(std::string_view str) { + static constexpr std::array months = { + "JAN"sv, "FEB"sv, "MAR"sv, "APR"sv, "MAY"sv, "JUN"sv, + "JUL"sv, "AUG"sv, "SEP"sv, "OCT"sv, "NOV"sv, "DEC"sv + }; + for (size_t i = 0; i < months.size(); ++i) { + if (str == months[i]) return static_cast(i + 1); + } + return 0; +} +``` + +--- + +### 3.6 `std::expected` for error handling (optional / future API) + +**Scope:** This is a significant API change. Add `std::expected` returning overloads alongside the existing throw-based ones. Do NOT remove the throwing versions (that would break users). + +**Files:** +- `reader/ReaderHeaderExam.hpp` / `.ipp` +- `reader/ReaderHeaderGeneral.hpp` / `.ipp` +- `reader/ReaderHeaderSignal.hpp` / `.ipp` + +**Example new API:** +```cpp +struct ReaderHeaderExam : Reader { + // Existing (throws): + HeaderExam operator()(Stream& stream); + // New (returns expected): + std::expected try_read(Stream& stream) noexcept; +}; +``` + +**Implementation:** Wrap the existing call in a try/catch that maps exceptions to `std::unexpected(FileErrc::...)`. + +This is a **non-breaking additive change**. Existing code continues to work. + +**Defer implementation details to Phase 4** if time-constrained. The key Phase 3 deliverable is defining the `try_read` API shape. + +--- + +### 3.7 `std::optional` replaces `-1` sentinel in RecordSink + +**File:** `C:/dev/code/edfio/include/edfio/sink/RecordSink.hpp` + +**Bug:** `size_type m_offset = -1;` where `size_type` is `unsigned long long`. This means `m_offset` is `ULLONG_MAX` when used as "end" sentinel. Multiple comparisons like `m_offset == -1` rely on implicit conversion. + +**Fix:** Use `std::optional`: +```cpp +std::optional m_offset; // nullopt = end +``` + +Update all checks: +```cpp +// Before: +if (m_offset == -1) +// After: +if (!m_offset) +``` + +And the save call: +```cpp +// Before: +m_context->save(m_offset, std::move(value)); +// After: +m_context->save(m_offset.value_or(size_type(-1)), std::move(value)); +``` + +This change cascades into `DataRecordSink.hpp` and `SignalRecordSink.hpp` where `save()` checks `off == -1`. + +--- + +### Phase 3 summary + +| File | C++23 Feature | +|------|---------------| +| `processor/detail/ProcessorUtils.hpp` | `if constexpr`, `string_view`, `constexpr` arrays | +| `store/RecordStore.hpp` | `<=>` spaceship | +| `store/TalStore.hpp` | `<=>` spaceship | +| `sink/RecordSink.hpp` | `<=>` spaceship, `std::optional` | +| `processor/impl/ProcessorHeaderGeneral.ipp` | `std::format` | +| `processor/impl/ProcessorHeaderGeneralFields.ipp` | `std::from_chars` | +| `processor/impl/ProcessorHeaderSignalFields.ipp` | `std::from_chars` | +| `processor/impl/ProcessorTalRecord.ipp` | `std::from_chars` | +| `reader/*.hpp` | `std::expected` API addition | + +**Dependencies:** Phase 2 complete. All Phase 1+2 tests passing. + +--- + +## Phase 4: Architecture -- Ranges, Iterator Overhaul, Coroutines + +**Goal:** Make Store/Sink types satisfy the standard ranges concepts. Redesign iterators using C++23 deducing this. Optionally add a coroutine generator for TalStore. + +### 4.1 Deducing this eliminates const_cast (12 sites) + +**Files:** +- `store/RecordStore.hpp` +- `store/TalStore.hpp` +- `sink/RecordSink.hpp` + +**Concept:** C++23 deducing this allows a single function template to handle both const and non-const overloads: + +```cpp +// Before (6 functions per class: begin, begin const, cbegin const, end, ...): +iterator begin() { return iterator(this); } +const_iterator begin() const { return const_iterator(const_cast(this)); } + +// After (deducing this): +auto begin(this auto& self) +{ + return iterator(&self); +} +auto cbegin(this const auto& self) +{ + return const_iterator(&self); +} +``` + +For this to work, the iterator class must be templated on pointer constness, or the Store's cached `m_value` must be `mutable`. The cleanest approach: + +1. Make `m_value` (and `m_bufferPos`, `m_buffer`) `mutable` in RecordStore, TalStore, and derived classes. This is semantically correct: the cache is an implementation detail, and dereferencing a const iterator from a const Store should still work (the file read is a side effect hidden behind the cache). + +2. Make `getR()` / `getP()` / `load()` const (now possible because members are mutable). + +3. Store a `const RecordStore*` (or `const TalStore*`) in the iterator. + +4. Replace all 12 const_cast sites with direct `this`. + +5. Use deducing this for `begin`/`end`: + +```cpp +auto begin(this auto& self) -> iterator { return iterator(&self, 0); } +auto end(this auto& self) -> iterator { return iterator(&self, self.size()); } +auto cbegin(this const auto& self) -> iterator { return iterator(&self, 0); } +auto cend(this const auto& self) -> iterator { return iterator(&self, self.size()); } +``` + +This removes 12 const_cast uses and ~36 redundant function definitions. + +--- + +### 4.2 Ranges compliance for RecordStore + +**Goal:** `RecordStore` (and derived types) should model `std::ranges::random_access_range` and `std::ranges::sized_range`. + +**Requirements:** +1. `begin()` and `end()` must return iterators satisfying `std::random_access_iterator` +2. `size()` must return a value convertible to `std::ranges::range_size_t` +3. Iterator `difference_type` must be signed +4. Iterator `operator-(it, it)` must return `difference_type` +5. `operator+(n, it)` must be provided (free function) +6. All arithmetic operators must use `difference_type`, not `size_type` + +**Changes to `Device.hpp`:** +```cpp +template +class Device +{ +public: + using stream_type = Stream; + using device_type = Device; + using value_type = Value; + using pointer = Pointer; + using reference = Reference; + using difference_type = std::ptrdiff_t; // was long long + using size_type = std::size_t; // was unsigned long long + + struct iterator + { + using iterator_concept = IterCategory; + using difference_type = Device::difference_type; + using value_type = Device::value_type; + using reference = Device::reference; + using pointer = Device::pointer; + }; + // ... +}; +``` + +**Changes to `RecordStore::iterator`:** +- Change all `size_type` parameters in operators to `difference_type` +- Add `friend iterator operator+(difference_type n, const iterator& it) { return it + n; }` +- Verify `std::random_access_iterator` at compile time: + +```cpp +static_assert(std::random_access_iterator); +``` + +**Changes to `RecordStore` itself:** +- Add `begin()` / `end()` returning proper iterators (done in 4.1) +- Verify: `static_assert(std::ranges::random_access_range);` + +**Test (in `test_iterators.cpp`):** +```cpp +TEST_CASE("DataRecordStore models random_access_range") { + std::ifstream stream("Calib5.edf", std::ios::binary); + REQUIRE(stream.is_open()); + edfio::ReaderHeaderExam reader; + auto header = reader(stream); + auto store = edfio::detail::CreateDataRecordStore(stream, header.m_general); + + // Use ranges algorithms + auto count = std::ranges::distance(store); + CHECK(count == header.m_general.m_datarecordsFile); + + // Random access + auto it = std::ranges::begin(store); + auto rec = *(it + 0); + CHECK(rec.Size() > 0); +} +``` + +--- + +### 4.3 TalStore as a `std::ranges::view` with optional coroutine generator + +**Current:** TalStore is a bidirectional iterator over TAL strings embedded in annotation signals. The `next()`/`prev()` methods manually parse through a byte vector. + +**Option A -- Coroutine Generator:** +```cpp +#include + +std::generator> tals(const std::vector& data) +{ + size_t pos = 0; + while (pos < data.size()) + { + // Skip zeros + while (pos < data.size() && data[pos] == 0) + ++pos; + if (pos >= data.size()) + break; + // Find end of TAL + size_t start = pos; + while (pos < data.size() && data[pos] != 0) + ++pos; + co_yield std::vector(data.begin() + start, data.begin() + pos); + } +} +``` + +This is a forward-only range. TalStore currently claims bidirectional, but the `prev()` implementation is broken (fixed in Phase 1). If bidirectional is not actually needed by users, replace with the generator. If bidirectional is needed, keep the fixed `prev()` and add the generator as a convenience view. + +**Option B -- Ranges-based lazy view (no coroutine):** +Use `std::views::split` or a custom view to split the byte vector on null bytes and filter empties: + +```cpp +auto tals_view(const std::vector& data) +{ + return data + | std::views::split('\0') + | std::views::filter([](auto&& sub) { return !std::ranges::empty(sub); }) + | std::views::transform([](auto&& sub) { + return std::vector(std::ranges::begin(sub), std::ranges::end(sub)); + }); +} +``` + +**Recommendation:** Implement Option B as the primary API (composable, no overhead). Provide Option A as an alternative `tals_generator()` free function for users who prefer coroutine style. + +--- + +### 4.4 `std::span` for non-owning buffer views + +**Where applicable:** +- `ProcessorSampleRecord::operator()` takes `Record` by value. Change to `std::span`: +```cpp +ProcType operator()(std::span bytes); +``` +- Similarly for `ProcessorTalRecord::operator()` which takes `std::vector` by value. + +**Impact:** These are processor function objects used internally. The Store dereferences to `Record const&`, so passing a span is trivial: `proc(std::span(record()))`. + +--- + +### 4.5 Concepts for Device template hierarchy + +**Current:** The `Device` base class takes 5 template parameters: `Value, Pointer, Reference, Stream, IterCategory`. This is the CRTP/inheritance chain: `Device -> Store -> RecordStore -> DataRecordStore`. + +**Replace with concepts:** +```cpp +template +concept Streamable = requires(T& t) { + { t.good() } -> std::convertible_to; + { t.clear() }; +}; + +template +concept ReadableStream = Streamable && requires(T& t, std::streamoff off) { + { t.seekg(off, std::ios::beg) }; + { t.tellg() } -> std::convertible_to; +}; + +template +concept WritableStream = Streamable && requires(T& t, std::streamoff off) { + { t.seekp(off, std::ios::beg) }; + { t.tellp() } -> std::convertible_to; +}; +``` + +Then `Device` becomes: +```cpp +template +class Device { + // Value, difference_type, size_type derived automatically + // No Pointer/Reference/IterCategory template params needed +}; +``` + +**This is a significant redesign.** The existing 5-param template works and is stable. Recommend implementing this as an optional modernization, not a hard requirement. If implemented, all Store and Sink classes need updating. + +--- + +### Phase 4 summary + +| Task | Risk | Lines Changed | Benefit | +|------|------|--------------|---------| +| 4.1 Deducing this | Medium | ~120 | Eliminates const_cast UB, -36 function defs | +| 4.2 Ranges compliance | Medium | ~100 | Standard algorithm compatibility | +| 4.3 TalStore view/generator | Low | ~60 | Cleaner TAL parsing | +| 4.4 std::span | Low | ~20 | Zero-copy buffer passing | +| 4.5 Concepts for Device | High | ~200 | Cleaner template hierarchy | + +**Dependencies:** Phase 3 complete. All prior tests passing. + +**Recommendation:** Implement 4.1 and 4.2 first (highest value). 4.3 and 4.4 are independent and can be done in parallel. 4.5 is optional. + +--- + +## Appendix A: Complete file inventory + +All paths relative to `C:/dev/code/edfio/include/edfio/`. + +| # | File | Phase 1 | Phase 2 | Phase 3 | Phase 4 | +|---|------|---------|---------|---------|---------| +| 1 | `Config.hpp` | | 2.3 `inline` | | | +| 2 | `Defs.hpp` | | | | | +| 3 | `Utils.hpp` | | 2.3, 2.8 | | | +| 4 | `EdfIO.hpp` | | | | | +| 5 | `core/Annotation.hpp` | | 2.5 typo | | | +| 6 | `core/DataFormat.hpp` | | 2.3, 2.7 | | | +| 7 | `core/Device.hpp` | 1.6 | 2.2 | | 4.2, 4.5 | +| 8 | `core/Field.hpp` | | | | | +| 9 | `core/Record.hpp` | 1.4 | | | | +| 10 | `core/SampleType.hpp` | | | | | +| 11 | `core/StreamIO.hpp` | | | | | +| 12 | `header/HeaderExam.hpp` | | | | | +| 13 | `header/HeaderGeneral.hpp` | | | | | +| 14 | `header/HeaderSignal.hpp` | | | | | +| 15 | `header/HeaderUtils.hpp` | | 2.1 | | | +| 16 | `processor/detail/ProcessorUtils.hpp` | | 2.1, 2.3, 2.4, 2.9, 2.10 | 3.1, 3.5 | | +| 17 | `processor/ProcessorAnnotation.hpp` | | | | | +| 18 | `processor/impl/ProcessorAnnotation.ipp` | | | | | +| 19 | `processor/ProcessorHeaderExam.hpp` | | | | | +| 20 | `processor/impl/ProcessorHeaderExam.ipp` | | 2.1 | | | +| 21 | `processor/ProcessorHeaderGeneral.hpp` | | | | | +| 22 | `processor/impl/ProcessorHeaderGeneral.ipp` | | 2.1 | 3.3 | | +| 23 | `processor/ProcessorHeaderGeneralFields.hpp` | | | | | +| 24 | `processor/impl/ProcessorHeaderGeneralFields.ipp` | | 2.1 | 3.4 | | +| 25 | `processor/ProcessorHeaderSignal.hpp` | | | | | +| 26 | `processor/impl/ProcessorHeaderSignal.ipp` | | 2.1 | | | +| 27 | `processor/ProcessorHeaderSignalFields.hpp` | | | | | +| 28 | `processor/impl/ProcessorHeaderSignalFields.ipp` | | | 3.4 | | +| 29 | `processor/ProcessorSample.hpp` | | | | 4.4 | +| 30 | `processor/impl/ProcessorSample.ipp` | | 2.1 | | 4.4 | +| 31 | `processor/ProcessorSampleRecord.hpp` | | | | 4.4 | +| 32 | `processor/impl/ProcessorSampleRecord.ipp` | 1.1 | | | 4.4 | +| 33 | `processor/ProcessorTalRecord.hpp` | | | | 4.4 | +| 34 | `processor/impl/ProcessorTalRecord.ipp` | | 2.1, 2.5 | 3.4 | 4.4 | +| 35 | `processor/ProcessorTimeStamp.hpp` | | | | | +| 36 | `processor/impl/ProcessorTimeStamp.ipp` | | | | | +| 37 | `processor/ProcessorTimeStampRecord.hpp` | | | | | +| 38 | `processor/impl/ProcessorTimeStampRecord.ipp` | | 2.1, 2.5 | | | +| 39 | `reader/ReaderHeaderExam.hpp` | | | 3.6 | | +| 40 | `reader/impl/ReaderHeaderExam.ipp` | | 2.1 | | | +| 41 | `reader/ReaderHeaderGeneral.hpp` | | | | | +| 42 | `reader/impl/ReaderHeaderGeneral.ipp` | 1.7 | 2.1 | | | +| 43 | `reader/ReaderHeaderSignal.hpp` | | | | | +| 44 | `reader/impl/ReaderHeaderSignal.ipp` | 1.7 | 2.1 | | | +| 45 | `sink/DataRecordSink.hpp` | | 2.2 | 3.7 | 4.1 | +| 46 | `sink/RecordSink.hpp` | 1.3 | 2.2 | 3.2, 3.7 | 4.1 | +| 47 | `sink/SignalRecordSink.hpp` | | 2.2, 2.6 | 3.7 | 4.1 | +| 48 | `sink/Sink.hpp` | | 2.2 | | | +| 49 | `sink/detail/SinkUtils.hpp` | | 2.1 | | | +| 50 | `store/DatarecordStore.hpp` | 1.8 | 2.2 | | 4.1 | +| 51 | `store/RecordStore.hpp` | 1.3 | 2.2 | 3.2 | 4.1, 4.2 | +| 52 | `store/SignalrecordStore.hpp` | 1.8 | 2.2 | | 4.1 | +| 53 | `store/SignalSampleStore.hpp` | 1.8 | 2.2 | | 4.1 | +| 54 | `store/Store.hpp` | | 2.2 | | | +| 55 | `store/TalStore.hpp` | 1.2 | 2.2 | 3.2 | 4.1, 4.3 | +| 56 | `store/TimeStampStore.hpp` | 1.8 | 2.2 | | 4.1 | +| 57 | `store/detail/StoreUtils.hpp` | | 2.1 | | | +| 58 | `writer/WriterHeaderExam.hpp` | | | | | +| 59 | `writer/impl/WriterHeaderExam.ipp` | | 2.1 | | | +| 60 | `writer/WriterHeaderGeneral.hpp` | | | | | +| 61 | `writer/impl/WriterHeaderGeneral.ipp` | 1.7 | | | | +| 62 | `writer/WriterHeaderSignals.hpp` | | | | | +| 63 | `writer/impl/WriterHeaderSignals.ipp` | 1.7 | | | | +| 64 | `writer/WriterRecord.hpp` | | | | | +| 65 | `writer/impl/WriterRecord.ipp` | 1.7 | | | | + +--- + +## Appendix B: Test matrix + +| Test File | Covers | Phase | +|-----------|--------|-------| +| `test_record.cpp` | Record assign/move/concat, Size() | 1 | +| `test_reader.cpp` | Header reading from Calib5.edf, round-trip | 1, 2 | +| `test_processor_sample.cpp` | ProcessorSampleRecord sign extension, round-trip with ProcessorSample | 1 | +| `test_iterators.cpp` | RecordStore operator-, DataRecordStore iteration, ranges compliance, TalStore prev | 1, 4 | +| `test_writer.cpp` | Header write round-trip, Record write | 1, 2 | +| `test_processor_utils.cpp` | ReduceString, GetStringFromMonth, CheckFormatErrors, from_chars parsing | 2, 3 | + +--- + +## Appendix C: Build command reference + +```bash +# Configure +cmake -B build -G Ninja \ + -DCMAKE_CXX_COMPILER=clang++ \ + -DCMAKE_CXX_STANDARD=23 \ + -DCMAKE_CXX_FLAGS="-Wall -Wextra -Wpedantic" + +# Build +cmake --build build + +# Test +ctest --test-dir build --output-on-failure + +# Sanitizer build (for CI) +cmake -B build-san -G Ninja \ + -DCMAKE_CXX_COMPILER=clang++ \ + -DCMAKE_CXX_STANDARD=23 \ + -DCMAKE_CXX_FLAGS="-fsanitize=address,undefined -fno-omit-frame-pointer -Wall -Wextra" +cmake --build build-san +ctest --test-dir build-san --output-on-failure +``` + +--- + +## Execution order and time estimates + +| Phase | Estimated Effort | Blocking | Deliverable | +|-------|-----------------|----------|-------------| +| Phase 0 | 1 hour | None | CMake builds, doctest runs, skeleton tests pass | +| Phase 1 | 4 hours | Phase 0 | All critical/high bugs fixed, regression tests green | +| Phase 2 | 3 hours | Phase 1 | Modernized style, no behavioral changes, all tests green | +| Phase 3 | 6 hours | Phase 2 | C++23 features integrated, new tests for from_chars/format/spaceship | +| Phase 4 | 8 hours | Phase 3 | Ranges-compliant iterators, deducing this, optional coroutine | + +**Total estimated effort: ~22 hours** + +Each phase produces a standalone, shippable commit. No phase depends on a later phase. If work is stopped after any phase, the codebase is strictly improved. diff --git a/README.md b/README.md index 37960c8..a1e0f8e 100644 --- a/README.md +++ b/README.md @@ -1,19 +1,470 @@ # edfio -A C++ 11 header-only library to read/write EDF(+)/BDF(+) files. +[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE) +[![C++23](https://img.shields.io/badge/C%2B%2B-23-blue.svg)](https://en.cppreference.com/w/cpp/23) +[![Header-only](https://img.shields.io/badge/header--only-yes-green.svg)]() -### Sample file -The sample file 'Calib5.edf' provided in the root directory of this source tree -was taken from the - -Polyman - -Demodata only for testing. +A modern C++23 header-only library for reading and writing +[EDF](https://www.edfplus.info/specs/edf.html) (European Data Format) and +[BDF](https://www.biosemi.com/faq/file_format.htm) (BioSemi Data Format) +biomedical signal files. -### Terms and Conditions -Copyright(c) 2017-present Iuri Dotta (dotta dot iuri at gmail dot com) +## Features -This source code is licensed under the MIT license found in the -LICENSE file in the root directory of this source tree. +- **Header-only** -- zero external dependencies, single `#include` to get started +- **Modern C++23** -- uses `std::span`, `std::ranges`, `constexpr`, `std::from_chars` +- **Iterator-based** random access to data records and individual signal samples +- **Full format coverage** -- EDF, EDF+C, EDF+D, BDF, BDF+C, BDF+D +- **EDF+/BDF+ annotations** -- read and write Time-stamped Annotation Lists (TALs) +- **Two API layers** -- high-level `EdfFile` for common tasks, low-level stores and sinks for full control -Official repository: https://github.com/idotta/edfio +## Requirements + +| Dependency | Minimum version | +|---|---| +| C++ standard | C++23 | +| Clang | 17+ | +| GCC | 13+ | +| MSVC | 19.36+ (Visual Studio 2022 17.6) | +| CMake | 4.0+ | + +## Quick Start + +### High-level API + +```cpp +#include +#include + +int main() { + auto file = edfio::EdfFile::open("recording.edf"); + + std::cout << "Format: " << (file.isEdf() ? "EDF" : "BDF") << "\n"; + std::cout << "Signals: " << file.signalCount() << "\n"; + std::cout << "Data records: " << file.dataRecordCount() << "\n"; + std::cout << "Duration: " << file.duration() << "s\n"; + + // Access header information + auto const& general = file.general(); + auto const& signals = file.signals(); + + // Read physical (scaled) samples for the first signal + auto samples = file.readSignal(0); + + // Read raw digital samples + auto digital = file.readSignalDigital(0); + + // Read annotations (EDF+/BDF+ only) + if (file.isPlus()) { + auto annotations = file.readAnnotations(); + for (auto const& annot : annotations) { + std::cout << annot.m_start << "s: " + << annot.m_annotation << "\n"; + } + } +} +``` + +### Writing with the high-level API + +```cpp +#include + +// Prepare a header from an existing file, or build one manually +auto source = edfio::EdfFile::open("source.edf"); +auto writer = edfio::EdfWriter::create("output.edf", source.general(), source.signals()); + +// Write data records +// ... + +writer.close(); +``` + +## Installation + +### CMake FetchContent (recommended) + +```cmake +include(FetchContent) +FetchContent_Declare( + edfio + GIT_REPOSITORY https://github.com/idotta/edfio.git + GIT_TAG master +) +FetchContent_MakeAvailable(edfio) + +target_link_libraries(your_target PRIVATE edfio) +``` + +### CMake add\_subdirectory + +Clone or add edfio as a git submodule, then: + +```cmake +add_subdirectory(external/edfio) +target_link_libraries(your_target PRIVATE edfio) +``` + +### Copy headers + +Copy the `include/edfio/` directory into your project's include path and ensure +your build system enables C++23 (`-std=c++23` or `cxx_std_23`). + +## Low-level API + +The low-level API provides direct iterator access to data records, signal +records, and individual samples through **stores** (reading) and **sinks** +(writing). + +### Reading a file + +```cpp +#include +#include +#include + +int main() { + std::ifstream stream("recording.edf", std::ios::binary); + + // Parse the full header (general + all signal headers) + auto header = edfio::ReadHeaderExam(stream); + auto const& general = header.m_general; + auto const& signals = header.m_signals; + + std::cout << "Format: " + << (edfio::IsEdf(general.m_version) ? "EDF" : "BDF") + << (edfio::IsPlus(general.m_version) ? "+" : "") << "\n"; + std::cout << "Signals: " << general.m_totalSignals << "\n"; + std::cout << "Data records: " << general.m_datarecordsFile << "\n"; + std::cout << "Record duration: " << general.m_datarecordDuration << "s\n"; + + // Print signal labels + for (auto const& sig : signals) { + std::cout << " " << sig.m_label + << " [" << sig.m_physDimension << "]" + << " " << sig.m_samplesInDataRecord << " samples/record\n"; + } + + // Iterate over raw data records + auto store = edfio::detail::CreateDataRecordStore(stream, general); + for (auto it = store.begin(); it != store.end(); ++it) { + auto const& record = *it; + // record() returns std::vector with the raw bytes + } +} +``` + +### Reading signal samples + +```cpp +#include +#include +#include + +int main() { + std::ifstream stream("recording.edf", std::ios::binary); + auto header = edfio::ReadHeaderExam(stream); + auto const& general = header.m_general; + auto const& signal = header.m_signals[0]; // first signal + + // Create a sample store -- iterates individual samples across all + // data records for a single signal + auto sampleStore = edfio::detail::CreateSignalSampleStore( + stream, general, signal); + + // Processor converts raw bytes to physical (double) or digital (int32_t) values + edfio::ProcessorSampleRecord toPhysical( + signal.m_detail.m_offset, + signal.m_detail.m_scaling); + + std::vector samples; + samples.reserve(sampleStore.size()); + for (auto it = sampleStore.begin(); it != sampleStore.end(); ++it) { + samples.push_back(toPhysical(*it)); + } + + // For digital (raw integer) values, use SampleType::Digital instead: + edfio::ProcessorSampleRecord toDigital( + signal.m_detail.m_offset, + signal.m_detail.m_scaling); +} +``` + +### Reading signal records per data record + +```cpp +// Read signal-level records (one per data record) for a specific signal +auto sigStore = edfio::detail::CreateSignalRecordStore( + stream, header.m_general, header.m_signals[0]); + +for (auto it = sigStore.begin(); it != sigStore.end(); ++it) { + auto const& record = *it; + // record() contains one data record's worth of samples for this signal +} +``` + +## Writing Files + +```cpp +#include +#include + +int main() { + // Read an existing file + std::ifstream inStream("source.edf", std::ios::binary); + auto header = edfio::ReadHeaderExam(inStream); + + // Write header to a new file + std::ofstream outStream("copy.edf", std::ios::binary); + edfio::WriteHeaderExam(outStream, header); + + // Copy data records using store (read) and sink (write) iterators + auto store = edfio::detail::CreateDataRecordStore(inStream, header.m_general); + auto sink = edfio::detail::CreateDataRecordSink(outStream, header.m_general); + auto sinkIt = sink.begin(); + for (auto it = store.begin(); it != store.end(); ++it) { + *sinkIt = *it; + ++sinkIt; + } +} +``` + +### Building a header from scratch + +```cpp +#include +#include +#include +#include + +int main() { + // Define signals + std::vector signals; + signals.push_back(edfio::detail::CreateHeaderSignal( + "EEG Fp1", // label + 256, // samples per data record + -3200.0, // physical min + 3200.0, // physical max + -32768, // digital min + 32767 // digital max + )); + + // Calculate header size: 256 bytes (general) + 256 bytes per signal + int32_t headerSize = 256 + 256 * static_cast(signals.size()); + + // Create the general header + auto general = edfio::detail::CreateHeaderGeneral( + edfio::DataFormat::Edf, + "Patient X", // patient + "Recording 1", // recording + 1, 3, 2026, // start date (day, month, year) + 14, 30, 0, // start time (hour, minute, second) + headerSize, + "", // reserved + 100, // number of data records + 1.0, // data record duration in seconds + signals + ); + + // Assemble and write + edfio::HeaderExam exam{general, signals}; + std::ofstream outStream("new_file.edf", std::ios::binary); + edfio::WriteHeaderExam(outStream, exam); + + // Write sample data using ProcessorSample and DataRecordSink... +} +``` + +## EDF+ / BDF+ Annotations + +EDF+ and BDF+ files store annotations in dedicated signal channels using +Time-stamped Annotation Lists (TALs). The `Annotation` struct holds the onset +time, duration, and annotation text: + +```cpp +struct Annotation : TimeStamp { + double m_duration; + std::string m_annotation; + // inherited: double m_start, int64_t m_datarecord +}; +``` + +### Reading annotations + +```cpp +#include +#include +#include + +int main() { + std::ifstream stream("recording_plus.edf", std::ios::binary); + auto header = edfio::ReadHeaderExam(stream); + + if (!edfio::IsPlus(header.m_general.m_version)) { + std::cout << "Not an EDF+/BDF+ file\n"; + return 0; + } + + // Find the annotation signal + edfio::HeaderSignal const* annotSignal = nullptr; + for (auto const& sig : header.m_signals) { + if (sig.m_detail.m_isAnnotation) { + annotSignal = &sig; + break; + } + } + + // Read annotation records and parse TALs + auto sigStore = edfio::detail::CreateSignalRecordStore( + stream, header.m_general, *annotSignal); + + int64_t drIdx = 0; + for (auto it = sigStore.begin(); it != sigStore.end(); ++it, ++drIdx) { + auto const& rec = *it; + std::vector talData(rec().begin(), rec().end()); + + auto annotations = edfio::ProcessTalRecord(talData, drIdx); + for (auto const& annot : annotations) { + std::cout << " [" << annot.m_start << "s"; + if (annot.m_duration > 0) + std::cout << ", dur=" << annot.m_duration << "s"; + std::cout << "] " << annot.m_annotation << "\n"; + } + } +} +``` + +### Writing annotations + +```cpp +#include + +// Create an annotation +edfio::Annotation annot; +annot.m_start = 1.5; +annot.m_duration = 30.0; +annot.m_annotation = "Sleep Stage W"; +annot.m_datarecord = 0; + +// Serialize to a TAL record +auto record = edfio::ProcessAnnotation(annot); + +// Create a timestamp record for the data record onset +edfio::TimeStamp ts; +ts.m_start = 0.0; +ts.m_datarecord = 0; +auto tsRecord = edfio::ProcessTimeStamp(ts); + +// Combine timestamp + annotation into the annotation signal's data +auto combined = tsRecord + record; +``` + +### Reading timestamps + +EDF+ files include a timestamp at the start of each data record in the +annotation channel. Use `TimeStampStore` to access them: + +```cpp +auto tsStore = edfio::detail::CreateTimeStampStore( + stream, header.m_general, *annotSignal); + +for (auto it = tsStore.begin(); it != tsStore.end(); ++it) { + auto const& rec = *it; + // Parse with ProcessTimeStampRecord for structured TimeStamp data + auto ts = edfio::ProcessTimeStampRecord(*it, /* datarecord index */); +} +``` + +## Data Formats + +edfio detects and supports all standard EDF/BDF variants through the +`DataFormat` enum: + +| Enum value | Description | Sample size | +|---|---|---| +| `DataFormat::Edf` | Standard EDF | 2 bytes (16-bit) | +| `DataFormat::EdfPlusC` | EDF+ Continuous | 2 bytes | +| `DataFormat::EdfPlusD` | EDF+ Discontinuous | 2 bytes | +| `DataFormat::Bdf` | Standard BDF | 3 bytes (24-bit) | +| `DataFormat::BdfPlusC` | BDF+ Continuous | 3 bytes | +| `DataFormat::BdfPlusD` | BDF+ Discontinuous | 3 bytes | + +Helper functions: `IsEdf()`, `IsBdf()`, `IsPlus()`, `GetSampleBytes()`. + +## Building and Testing + +```bash +cmake -B build -G Ninja +cmake --build build +ctest --test-dir build +``` + +The test suite uses [doctest](https://github.com/doctest/doctest) (bundled in +`third_party/`) and runs against sample EDF/EDF+/BDF+ files in the `files/` +directory. + +## Project Structure + +``` +edfio/ + CMakeLists.txt + LICENSE + include/edfio/ + EdfIO.hpp # Main include (low-level API) + EdfFile.hpp # High-level API (coming soon) + core/ + Annotation.hpp # Annotation and TimeStamp structs + DataFormat.hpp # DataFormat enum and helpers + Record.hpp # Record container with stream I/O + SampleType.hpp # SampleType enum, Sample traits, ConvertSample + Field.hpp # Fixed-size header field type + StreamIO.hpp # Reader/Writer stream type aliases + header/ + HeaderExam.hpp # HeaderExam (general + signal headers) + HeaderGeneral.hpp # HeaderGeneral, Date, Time structs + HeaderSignal.hpp # HeaderSignal struct + HeaderUtils.hpp # CreateHeaderGeneral, CreateHeaderSignal + reader/ + ReaderHeaderExam.hpp # ReadHeaderExam() entry point + writer/ + WriterHeaderExam.hpp # WriteHeaderExam() entry point + store/ # Read iterators + DataRecordStore.hpp # Iterate full data records + SignalRecordStore.hpp # Iterate one signal's records + SignalSampleStore.hpp # Iterate individual samples + TimeStampStore.hpp # Iterate EDF+ timestamps + TalStore.hpp # Iterate TALs within a record + StoreUtils.hpp # Factory functions for stores + sink/ # Write iterators + DataRecordSink.hpp # Write full data records + SignalRecordSink.hpp # Write one signal's records + SinkUtils.hpp # Factory functions for sinks + processor/ # Data transformation + ProcessorSampleRecord.hpp # Raw bytes -> physical/digital values + ProcessorSample.hpp # Physical/digital values -> raw bytes + ProcessorTalRecord.hpp # TAL bytes -> vector + ProcessorAnnotation.hpp # Annotation -> TAL record + ProcessorTimeStamp.hpp # TimeStamp -> record + ProcessorTimeStampRecord.hpp # Record -> TimeStamp + tests/ # doctest-based test suite + files/ # Sample EDF/BDF files for testing + third_party/ # Bundled doctest headers +``` + +## License + +This project is licensed under the MIT License. See the [LICENSE](LICENSE) file +for details. + +Copyright (c) 2017-present Iuri Dotta + +## Contributing + +Contributions are welcome. To get started: + +1. Fork the repository at [github.com/idotta/edfio](https://github.com/idotta/edfio) +2. Create a feature branch from `master` +3. Make sure all tests pass (`ctest --test-dir build`) +4. Keep changes focused -- one feature or fix per pull request +5. Follow existing code style and naming conventions +6. Open a pull request with a clear description of the change diff --git a/cmake/edfioConfig.cmake.in b/cmake/edfioConfig.cmake.in new file mode 100644 index 0000000..49de116 --- /dev/null +++ b/cmake/edfioConfig.cmake.in @@ -0,0 +1,5 @@ +@PACKAGE_INIT@ + +include("${CMAKE_CURRENT_LIST_DIR}/edfioTargets.cmake") + +check_required_components(edfio) diff --git a/Calib5.edf b/files/Calib5.edf similarity index 100% rename from Calib5.edf rename to files/Calib5.edf diff --git a/files/SC4001EC-Hypnogram.edf b/files/SC4001EC-Hypnogram.edf new file mode 100644 index 0000000..e095b03 Binary files /dev/null and b/files/SC4001EC-Hypnogram.edf differ diff --git a/files/test_generator_2.bdf b/files/test_generator_2.bdf new file mode 100644 index 0000000..dd27e67 Binary files /dev/null and b/files/test_generator_2.bdf differ diff --git a/files/test_generator_2.edf b/files/test_generator_2.edf new file mode 100644 index 0000000..68a6787 Binary files /dev/null and b/files/test_generator_2.edf differ diff --git a/include/edfio/Config.hpp b/include/edfio/Config.hpp index da9b000..5704b7f 100644 --- a/include/edfio/Config.hpp +++ b/include/edfio/Config.hpp @@ -18,9 +18,9 @@ namespace edfio Permissive }; - namespace config + namespace detail { - static constexpr ProcessorErrorCheck PROCESSOR_ERROR_CHECKING = ProcessorErrorCheck::Strict; + inline constexpr ProcessorErrorCheck PROCESSOR_ERROR_CHECKING = ProcessorErrorCheck::Strict; } } diff --git a/include/edfio/Defs.hpp b/include/edfio/Defs.hpp deleted file mode 100644 index 3a161ac..0000000 --- a/include/edfio/Defs.hpp +++ /dev/null @@ -1,26 +0,0 @@ -// -// Copyright(c) 2017-present Iuri Dotta (dotta dot iuri at gmail dot com) -// -// This source code is licensed under the MIT license found in the -// LICENSE file in the root directory of this source tree. -// -// Official repository: https://github.com/idotta/edfio -// - -#pragma once - -namespace edfio -{ - - enum class FileErrc - { - FileDoesNotOpen, - FileNotOpened, - FileReadError, - FileContainsFormatErrors, - FileContainsInvalidAnnotations, - FileWriteError, - FileWriteInvalidAnnotations - }; - -} diff --git a/include/edfio/EdfFile.hpp b/include/edfio/EdfFile.hpp new file mode 100644 index 0000000..ed632e2 --- /dev/null +++ b/include/edfio/EdfFile.hpp @@ -0,0 +1,232 @@ +// +// Copyright(c) 2017-present Iuri Dotta (dotta dot iuri at gmail dot com) +// +// This source code is licensed under the MIT license found in the +// LICENSE file in the root directory of this source tree. +// +// Official repository: https://github.com/idotta/edfio +// + +#pragma once + +#include "EdfIO.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace edfio { + +/// High-level facade for reading EDF/BDF files. +/// +/// Owns the underlying file stream and parsed header. Provides convenient +/// methods to extract physical or digital samples and annotations without +/// manually wiring stores, sinks, processors, and streams. +/// +/// Moveable but not copyable (owns an std::ifstream). +class EdfFile { +public: + EdfFile(const EdfFile &) = delete; + EdfFile &operator=(const EdfFile &) = delete; + EdfFile(EdfFile &&) noexcept = default; + EdfFile &operator=(EdfFile &&) noexcept = default; + + /// Open an EDF/BDF file for reading. + /// + /// @param path Filesystem path to the file. + /// @throws std::runtime_error if the file cannot be opened. + /// @throws std::invalid_argument if the file contains format errors. + [[nodiscard]] static EdfFile open(const std::filesystem::path &path) { + auto stream = std::make_unique(path, std::ios::binary); + if (!stream->is_open()) { + throw std::runtime_error(std::string("Cannot open file: ") + + path.string()); + } + auto header = ReadHeaderExam(*stream); + return EdfFile(std::move(stream), std::move(header)); + } + + // ---- Header access ------------------------------------------------------- + + /// General header fields (patient, recording, timing, etc.). + [[nodiscard]] const HeaderGeneral &general() const noexcept { + return m_header.m_general; + } + + /// Per-signal header fields. + [[nodiscard]] const std::vector &signals() const noexcept { + return m_header.m_signals; + } + + /// Full header exam (general + signals). + [[nodiscard]] const HeaderExam &header() const noexcept { return m_header; } + + // ---- Format queries ------------------------------------------------------- + + /// Data format enum value. + [[nodiscard]] DataFormat format() const noexcept { + return m_header.m_general.m_version; + } + + /// True for any EDF variant (plain EDF, EDF+C, EDF+D). + [[nodiscard]] bool isEdf() const noexcept { return IsEdf(format()); } + + /// True for any BDF variant (plain BDF, BDF+C, BDF+D). + [[nodiscard]] bool isBdf() const noexcept { return IsBdf(format()); } + + /// True for any "plus" variant (EDF+C, EDF+D, BDF+C, BDF+D). + [[nodiscard]] bool isPlus() const noexcept { return IsPlus(format()); } + + // ---- Counts and duration -------------------------------------------------- + + /// Total number of signals (including annotation channels). + [[nodiscard]] int32_t signalCount() const noexcept { + return m_header.m_general.m_totalSignals; + } + + /// Number of data records in the file. + [[nodiscard]] int64_t dataRecordCount() const noexcept { + return m_header.m_general.m_datarecordsFile; + } + + /// Total file duration in seconds + /// (dataRecordCount * datarecordDuration). + [[nodiscard]] double duration() const noexcept { + return m_header.m_general.m_detail.m_fileDuration; + } + + // ---- Sample reading ------------------------------------------------------- + + /// Read all physical-value samples for the given signal index. + /// + /// The returned vector contains one double per sample, converted from the + /// raw digital value using the signal's offset and scaling parameters. + /// + /// @param signalIndex Zero-based index into signals(). + /// @throws std::out_of_range if signalIndex is invalid. + [[nodiscard]] std::vector readSignal(size_t signalIndex) const { + validateSignalIndex(signalIndex); + + auto const &sig = m_header.m_signals[signalIndex]; + auto store = + detail::CreateSignalSampleStore(*m_stream, m_header.m_general, sig); + + ProcessorSampleRecord proc(sig.m_detail.m_offset, + sig.m_detail.m_scaling); + + std::vector result; + result.reserve(store.size()); + for (auto it = store.begin(); it != store.end(); ++it) { + result.push_back(proc(*it)); + } + return result; + } + + /// Read all digital-value samples for the given signal index. + /// + /// The returned vector contains one int32_t per sample, which is the raw + /// (sign-extended) integer stored in the file. + /// + /// @param signalIndex Zero-based index into signals(). + /// @throws std::out_of_range if signalIndex is invalid. + [[nodiscard]] std::vector + readSignalDigital(size_t signalIndex) const { + validateSignalIndex(signalIndex); + + auto const &sig = m_header.m_signals[signalIndex]; + auto store = + detail::CreateSignalSampleStore(*m_stream, m_header.m_general, sig); + + // offset=0, scaling=1 yields the raw digital value. + ProcessorSampleRecord proc(0.0, 1.0); + + std::vector result; + result.reserve(store.size()); + for (auto it = store.begin(); it != store.end(); ++it) { + result.push_back(proc(*it)); + } + return result; + } + + // ---- Annotations ---------------------------------------------------------- + + /// Read all annotations from every annotation channel. + /// + /// Returns an empty vector when the file is not an EDF+/BDF+ variant or + /// contains no annotation channels. + [[nodiscard]] std::vector readAnnotations() const { + std::vector result; + + for (size_t i = 0; i < m_header.m_signals.size(); ++i) { + auto const &sig = m_header.m_signals[i]; + if (!sig.m_detail.m_isAnnotation) + continue; + + auto sigStore = + detail::CreateSignalRecordStore(*m_stream, m_header.m_general, sig); + + int64_t drIdx = 0; + for (auto it = sigStore.begin(); it != sigStore.end(); ++it, ++drIdx) { + auto const &rec = *it; + std::vector talData(rec().begin(), rec().end()); + if (talData.empty() || + (talData.front() != '+' && talData.front() != '-')) + continue; + + auto annots = ProcessTalRecord(talData, drIdx); + result.insert(result.end(), std::make_move_iterator(annots.begin()), + std::make_move_iterator(annots.end())); + } + } + return result; + } + + // ---- Low-level store access (for advanced use) ---------------------------- + + /// Create a DataRecordStore over the file. + [[nodiscard]] DataRecordStore dataRecordStore() const { + return detail::CreateDataRecordStore(*m_stream, m_header.m_general); + } + + /// Create a SignalRecordStore for the given signal index. + /// + /// @param signalIndex Zero-based index into signals(). + /// @throws std::out_of_range if signalIndex is invalid. + [[nodiscard]] SignalRecordStore signalRecordStore(size_t signalIndex) const { + validateSignalIndex(signalIndex); + return detail::CreateSignalRecordStore(*m_stream, m_header.m_general, + m_header.m_signals[signalIndex]); + } + + /// Create a SignalSampleStore for the given signal index. + /// + /// @param signalIndex Zero-based index into signals(). + /// @throws std::out_of_range if signalIndex is invalid. + [[nodiscard]] SignalSampleStore signalSampleStore(size_t signalIndex) const { + validateSignalIndex(signalIndex); + return detail::CreateSignalSampleStore(*m_stream, m_header.m_general, + m_header.m_signals[signalIndex]); + } + +private: + explicit EdfFile(std::unique_ptr stream, HeaderExam header) + : m_stream(std::move(stream)), m_header(std::move(header)) {} + + void validateSignalIndex(size_t signalIndex) const { + if (signalIndex >= m_header.m_signals.size()) { + throw std::out_of_range("Signal index " + std::to_string(signalIndex) + + " out of range [0, " + + std::to_string(m_header.m_signals.size()) + ")"); + } + } + + std::unique_ptr m_stream; + HeaderExam m_header; +}; + +} // namespace edfio diff --git a/include/edfio/EdfIO.hpp b/include/edfio/EdfIO.hpp index de96612..41a00e1 100644 --- a/include/edfio/EdfIO.hpp +++ b/include/edfio/EdfIO.hpp @@ -11,28 +11,38 @@ // Header #include "header/HeaderExam.hpp" + // Reader #include "reader/ReaderHeaderExam.hpp" + // Writer #include "writer/WriterHeaderExam.hpp" + // Store #include "store/DataRecordStore.hpp" #include "store/SignalRecordStore.hpp" #include "store/SignalSampleStore.hpp" -#include "store/detail/StoreUtils.hpp" +#include "store/StoreUtils.hpp" #include "store/TalStore.hpp" #include "store/TimeStampStore.hpp" + + // Sink #include "sink/DataRecordSink.hpp" #include "sink/SignalRecordSink.hpp" -#include "sink/detail/SinkUtils.hpp" +#include "sink/SinkUtils.hpp" + // Processor -#include "processor/ProcessorSampleRecord.hpp" +#include "processor/ProcessorAnnotation.hpp" #include "processor/ProcessorSample.hpp" -#include "processor/ProcessorTimeStampRecord.hpp" -#include "processor/ProcessorTimeStamp.hpp" +#include "processor/ProcessorSampleRecord.hpp" #include "processor/ProcessorTalRecord.hpp" -#include "processor/ProcessorAnnotation.hpp" +#include "processor/ProcessorTimeStamp.hpp" +#include "processor/ProcessorTimeStampRecord.hpp" + +// High-level facade +#include "EdfFile.hpp" +#include "EdfWriter.hpp" // STL #include diff --git a/include/edfio/EdfWriter.hpp b/include/edfio/EdfWriter.hpp new file mode 100644 index 0000000..b64f5df --- /dev/null +++ b/include/edfio/EdfWriter.hpp @@ -0,0 +1,108 @@ +// +// Copyright(c) 2017-present Iuri Dotta (dotta dot iuri at gmail dot com) +// +// This source code is licensed under the MIT license found in the +// LICENSE file in the root directory of this source tree. +// +// Official repository: https://github.com/idotta/edfio +// + +#pragma once + +#include "EdfIO.hpp" + +#include +#include +#include +#include +#include +#include + +namespace edfio { + +/// High-level facade for writing EDF/BDF files. +/// +/// Owns the underlying output stream. Write data records sequentially after +/// the header has been written. The data-record count in the header is +/// automatically patched on close() (or destruction). +/// +/// Moveable but not copyable (owns an std::ofstream). +class EdfWriter { +public: + EdfWriter(const EdfWriter &) = delete; + EdfWriter &operator=(const EdfWriter &) = delete; + EdfWriter(EdfWriter &&) noexcept = default; + EdfWriter &operator=(EdfWriter &&) noexcept = default; + + /// Create a new EDF/BDF file and write its header. + /// + /// @param path Filesystem path for the new file. + /// @param header Complete header exam to write. + /// @throws std::runtime_error if the file cannot be created. + [[nodiscard]] static EdfWriter create(const std::filesystem::path &path, + const HeaderExam &header) { + auto stream = std::make_unique(path, std::ios::binary); + if (!stream->is_open()) { + throw std::runtime_error(std::string("Cannot create file: ") + + path.string()); + } + WriteHeaderExam(*stream, header); + return EdfWriter(std::move(stream), header.m_general); + } + + /// Write a single data record to the file. + /// + /// The data record count in the header is automatically updated when + /// close() is called (or the writer is destroyed). + void writeDataRecord(const Record &record) { + if (m_stream && m_stream->is_open()) { + *m_stream << record; + ++m_recordsWritten; + } + } + + /// Number of data records written so far. + [[nodiscard]] int64_t recordsWritten() const noexcept { + return m_recordsWritten; + } + + /// Flush, patch the data-record count in the header, and close. + void close() { + if (m_stream && m_stream->is_open()) { + // EDF/BDF header layout: the "number of data records" field is 8 bytes + // starting at offset 236 (after version[8] + patient[80] + + // recording[80] + startDate[8] + startTime[8] + headerSize[8] + + // reserved[44] = 236). + static constexpr std::streamoff kDataRecordCountOffset = 236; + static constexpr size_t kFieldSize = 8; + + m_stream->seekp(kDataRecordCountOffset, std::ios::beg); + auto countStr = std::to_string(m_recordsWritten); + countStr.resize(kFieldSize, ' '); + m_stream->write(countStr.data(), kFieldSize); + + m_stream->flush(); + m_stream->close(); + } + } + + /// Destructor flushes and closes the stream if still open. + ~EdfWriter() { + try { + close(); + } catch (...) { + // Suppress exceptions in destructor. + } + } + +private: + explicit EdfWriter(std::unique_ptr stream, + HeaderGeneral general) + : m_stream(std::move(stream)), m_general(std::move(general)) {} + + std::unique_ptr m_stream; + HeaderGeneral m_general; + int64_t m_recordsWritten = 0; +}; + +} // namespace edfio diff --git a/include/edfio/Errors.hpp b/include/edfio/Errors.hpp new file mode 100644 index 0000000..4be0676 --- /dev/null +++ b/include/edfio/Errors.hpp @@ -0,0 +1,45 @@ +// +// Copyright(c) 2017-present Iuri Dotta (dotta dot iuri at gmail dot com) +// +// This source code is licensed under the MIT license found in the +// LICENSE file in the root directory of this source tree. +// +// Official repository: https://github.com/idotta/edfio +// + +#pragma once + +namespace edfio { + +enum class FileErrc { + FileDoesNotOpen, + FileNotOpened, + FileReadError, + FileContainsFormatErrors, + FileContainsInvalidAnnotations, + FileWriteError, + FileWriteInvalidAnnotations +}; + +[[nodiscard]] inline constexpr const char *GetError(FileErrc err) { + switch (err) { + case FileErrc::FileDoesNotOpen: + return "Error: file does not open"; + case FileErrc::FileNotOpened: + return "Error: file not opened"; + case FileErrc::FileReadError: + return "Error: can't read file"; + case FileErrc::FileContainsFormatErrors: + return "Error: file contains format errors"; + case FileErrc::FileContainsInvalidAnnotations: + return "Error: file contains invalid annotations"; + case FileErrc::FileWriteError: + return "Error: can't write on file"; + case FileErrc::FileWriteInvalidAnnotations: + return "Error: writing invalid annotations"; + default: + return "Unspecified error"; + } +} + +} // namespace edfio diff --git a/include/edfio/Utils.hpp b/include/edfio/Utils.hpp deleted file mode 100644 index c71cfd6..0000000 --- a/include/edfio/Utils.hpp +++ /dev/null @@ -1,54 +0,0 @@ -// -// Copyright(c) 2017-present Iuri Dotta (dotta dot iuri at gmail dot com) -// -// This source code is licensed under the MIT license found in the -// LICENSE file in the root directory of this source tree. -// -// Official repository: https://github.com/idotta/edfio -// - -#pragma once - -#include "Defs.hpp" - -namespace edfio -{ - - namespace detail - { - static const char* GetError(FileErrc err) - { - if (err == FileErrc::FileDoesNotOpen) - { - return "Error: file does not open"; - } - else if (err == FileErrc::FileNotOpened) - { - return "Error: file not opened"; - } - else if (err == FileErrc::FileReadError) - { - return "Error: can't read file"; - } - else if (err == FileErrc::FileContainsFormatErrors) - { - return "Error: file contains format errors"; - } - else if (err == FileErrc::FileContainsInvalidAnnotations) - { - return "Error: file contains invalid annotations"; - } - else if (err == FileErrc::FileWriteError) - { - return "Error: can't write on file"; - } - else if (err == FileErrc::FileWriteInvalidAnnotations) - { - return "Error: writing invalid annotations"; - - } - return "Unspecified error"; - } - } - -} diff --git a/include/edfio/core/Annotation.hpp b/include/edfio/core/Annotation.hpp index e588ed8..06c8ff1 100644 --- a/include/edfio/core/Annotation.hpp +++ b/include/edfio/core/Annotation.hpp @@ -9,29 +9,26 @@ #pragma once +#include #include -namespace edfio -{ +namespace edfio { - namespace detail - { - // Each TAL starts with a time stamp Onset21Duration20 - static const char DURATION_DIV = 21; - static const char ANNOTATION_DIV = 20; - static const char ANNOTATION_END = 0; - } +namespace detail { +// Each TAL starts with a time stamp Onset21Duration20 +static constexpr char DURATION_DIV = 21; +static constexpr char ANNOTATION_DIV = 20; +static constexpr char ANNOTATION_END = 0; +} // namespace detail - struct TimeStamp - { - long long m_dararecord = 0; - double m_start = 0; - }; +struct TimeStamp { + int64_t m_datarecord = 0; + double m_start = 0; +}; - struct Annotation : TimeStamp - { - double m_duration = 0; - std::string m_annotation; - }; +struct Annotation : TimeStamp { + double m_duration = 0; + std::string m_annotation; +}; -} +} // namespace edfio diff --git a/include/edfio/core/DataFormat.hpp b/include/edfio/core/DataFormat.hpp index 618d089..dfd292d 100644 --- a/include/edfio/core/DataFormat.hpp +++ b/include/edfio/core/DataFormat.hpp @@ -9,43 +9,39 @@ #pragma once -namespace edfio -{ - - enum class DataFormat - { - Edf, - EdfPlusC, - EdfPlusD, - Bdf, - BdfPlusC, - BdfPlusD, - Invalid - }; - - static const bool IsPlus(DataFormat format) - { - return format == DataFormat::EdfPlusC || format == DataFormat::EdfPlusD - || format == DataFormat::BdfPlusC || format == DataFormat::BdfPlusD; - } - - static const bool IsEdf(DataFormat format) - { - return format == DataFormat::Edf || format == DataFormat::EdfPlusC || format == DataFormat::EdfPlusD; - } - - static const bool IsBdf(DataFormat format) - { - return format == DataFormat::Bdf || format == DataFormat::BdfPlusC || format == DataFormat::BdfPlusD; - } - - static const int GetSampleBytes(DataFormat format) - { - if (IsEdf(format)) - return 2; - else if (IsBdf(format)) - return 3; - return -1; - } +namespace edfio { + +enum class DataFormat { + Edf, + EdfPlusC, + EdfPlusD, + Bdf, + BdfPlusC, + BdfPlusD, + Invalid +}; + +inline constexpr bool IsPlus(DataFormat format) { + return format == DataFormat::EdfPlusC || format == DataFormat::EdfPlusD || + format == DataFormat::BdfPlusC || format == DataFormat::BdfPlusD; +} + +inline constexpr bool IsEdf(DataFormat format) { + return format == DataFormat::Edf || format == DataFormat::EdfPlusC || + format == DataFormat::EdfPlusD; +} +inline constexpr bool IsBdf(DataFormat format) { + return format == DataFormat::Bdf || format == DataFormat::BdfPlusC || + format == DataFormat::BdfPlusD; } + +inline constexpr int GetSampleBytes(DataFormat format) { + if (IsEdf(format)) + return 2; + else if (IsBdf(format)) + return 3; + return -1; +} + +} // namespace edfio diff --git a/include/edfio/core/Device.hpp b/include/edfio/core/Device.hpp index 5af49af..9ea1db1 100644 --- a/include/edfio/core/Device.hpp +++ b/include/edfio/core/Device.hpp @@ -9,47 +9,43 @@ #pragma once +#include #include -namespace edfio -{ - - // A class created in order to have an easier way to access streams - // of specific data through their respective iterators. - template - class Device - { - public: - typedef Stream stream_type; - typedef Device device_type; - - typedef Value value_type; - typedef Pointer pointer; - typedef Reference reference; - typedef long long difference_type; - typedef unsigned long long size_type; - - class iterator - { - public: - typedef typename Device::difference_type difference_type; - typedef typename Device::value_type value_type; - typedef typename Device::reference reference; - typedef typename Device::pointer pointer; - typedef IterCategory iterator_category; - typedef typename Device::stream_type stream_type; - }; - - Device() = delete; - - Device(stream_type &stream) - : m_stream(stream) - { - } - - protected: - - stream_type &m_stream; - }; - -} +namespace edfio { + +// A class created in order to have an easier way to access streams +// of specific data through their respective iterators. +template +class Device { +public: + using stream_type = Stream; + using device_type = Device; + + using value_type = Value; + using pointer = Pointer; + using reference = Reference; + using difference_type = int64_t; + using size_type = uint64_t; + + class iterator { + public: + using difference_type = typename Device::difference_type; + using value_type = typename Device::value_type; + using reference = typename Device::reference; + using pointer = typename Device::pointer; + using iterator_category = IterCategory; + using iterator_concept = IterCategory; + using stream_type = typename Device::stream_type; + }; + + Device() = delete; + + Device(stream_type &stream) : m_stream(stream) {} + +protected: + stream_type &m_stream; +}; + +} // namespace edfio diff --git a/include/edfio/core/Field.hpp b/include/edfio/core/Field.hpp index 988f6b4..5d19d4d 100644 --- a/include/edfio/core/Field.hpp +++ b/include/edfio/core/Field.hpp @@ -9,56 +9,43 @@ #pragma once -#include +#include +#include #include -namespace edfio -{ - - // Fields have fixed predetermined sizes in the exam file - // They are used to read the headers - template - struct Field - { - using ValueType = CharT; - - constexpr size_t Size() const - { - return Sz; - } - const std::basic_string& operator()() const - { - return m_value; - } - std::basic_string& operator()() - { - return m_value; - } - void operator()(const std::basic_string& value) - { - m_value = value; - m_value.resize(Size(), ' '); - } - - std::basic_string m_value; - }; - - template - std::ostream& operator << (std::ostream &os, Field &f) - { - auto &value = f(); - value.resize(Sz, ' '); - os.write(value.data(), Sz); - return os; - } - - template - std::istream& operator >> (std::istream &is, Field &f) - { - auto &value = f(); - value.resize(f.Size(), ' '); - is.read(&value[0], f.Size()); - return is; - } +namespace edfio { + +// Fields have fixed predetermined sizes in the exam file +// They are used to read the headers +template struct Field { + using ValueType = CharT; + + [[nodiscard]] constexpr size_t Size() const { return Sz; } + [[nodiscard]] const std::basic_string &operator()() const { + return m_value; + } + std::basic_string &operator()() { return m_value; } + void operator()(const std::basic_string &value) { + m_value = value; + m_value.resize(Size(), ' '); + } + + std::basic_string m_value; +}; + +template +std::ostream &operator<<(std::ostream &os, const Field &f) { + const auto &value = f(); + os.write(value.data(), Sz); + return os; +} +template +std::istream &operator>>(std::istream &is, Field &f) { + auto &value = f(); + value.resize(f.Size(), ' '); + is.read(&value[0], f.Size()); + return is; } + +} // namespace edfio diff --git a/include/edfio/core/Record.hpp b/include/edfio/core/Record.hpp index 8f87171..4264bd0 100644 --- a/include/edfio/core/Record.hpp +++ b/include/edfio/core/Record.hpp @@ -9,77 +9,62 @@ #pragma once -#include +#include +#include +#include #include -namespace edfio -{ +namespace edfio { - // Records have fixed sizes that can vary according to the signal - // They can be used for either single signal record or data record IO - // It is important that data records always have one size in the same file - template - struct Record - { - using ValueType = ValT; - using VectorType = std::vector; +// Records have fixed sizes that can vary according to the signal +// They can be used for either single signal record or data record IO +// It is important that data records always have one size in the same file +template struct Record { + using ValueType = ValT; + using VectorType = std::vector; - Record() = delete; + Record() = delete; - Record(size_t recordSize) - : m_size(recordSize) - , m_value(recordSize, 0) {} + explicit Record(typename VectorType::size_type recordSize) + : m_value(recordSize, 0) {} - Record(typename VectorType::const_iterator first, typename VectorType::const_iterator last) - : m_size(std::distance(first, last)) - , m_value(first, last) {} + Record(typename VectorType::const_iterator first, + typename VectorType::const_iterator last) + : m_value(first, last) {} - Record(const Record &record) - : m_size(record.m_size) - , m_value(record.m_value) - { - } + Record(const Record &) = default; + Record(Record &&) = default; + Record &operator=(const Record &) = default; + Record &operator=(Record &&) = default; - const size_t Size() const - { - return m_size; - } - const VectorType& operator()() const - { - return m_value; - } - VectorType& operator()() - { - return m_value; - } - Record operator+(const Record& record) - { - Record tmp(Size() + record.Size()); - std::copy(m_value.begin(), m_value.end(), tmp().begin()); - std::copy(record().begin(), record().end(), tmp().begin() + Size()); - return tmp; - } + [[nodiscard]] typename VectorType::size_type Size() const { + return m_value.size(); + } + [[nodiscard]] const VectorType &operator()() const { return m_value; } + VectorType &operator()() { return m_value; } + Record operator+(const Record &record) const { + Record tmp(Size() + record.Size()); + std::ranges::copy(m_value, tmp().begin()); + std::ranges::copy(record(), tmp().begin() + Size()); + return tmp; + } - VectorType m_value; - const size_t m_size; - }; + VectorType m_value; +}; - template - std::ostream& operator << (std::ostream &os, Record &r) - { - auto &record = r(); - record.resize(r.Size(), 0); - os.write(record.data(), r.Size() * sizeof(ValT)); - return os; - } - - template - std::istream& operator >> (std::istream &is, Record &r) - { - auto &record = r(); - record.resize(r.Size(), 0); - is.read(&record[0], r.Size() * sizeof(ValT)); - return is; - } +template +std::ostream &operator<<(std::ostream &os, const Record &r) { + const auto &record = r(); + os.write(record.data(), r.Size() * sizeof(ValT)); + return os; +} +template +std::istream &operator>>(std::istream &is, Record &r) { + auto &record = r(); + record.resize(r.Size(), 0); + is.read(&record[0], r.Size() * sizeof(ValT)); + return is; } + +} // namespace edfio diff --git a/include/edfio/core/SampleType.hpp b/include/edfio/core/SampleType.hpp index 17fb5de..bae1494 100644 --- a/include/edfio/core/SampleType.hpp +++ b/include/edfio/core/SampleType.hpp @@ -9,49 +9,33 @@ #pragma once -#include "../core/Record.hpp" -#include "../header/HeaderGeneral.hpp" -#include "../header/HeaderSignal.hpp" - -namespace edfio -{ - - enum class SampleType - { - Physical, - Digital - }; - - namespace impl - { - - template - struct Sample - { - }; - - template <> - struct Sample - { - using type = double; - }; - - template <> - struct Sample - { - using type = int; - }; - - inline Sample::type ConvertSample(double offset, double scaling, Sample::type sample) - { - return static_cast::type>((sample - offset) / scaling); - } - - inline Sample::type ConvertSample(double offset, double scaling, Sample::type sample) - { - return scaling * static_cast::type>(sample) + offset; - } - - } +#include +namespace edfio { + +enum class SampleType { Physical, Digital }; + +template struct Sample {}; + +template <> struct Sample { + using type = double; +}; + +template <> struct Sample { + using type = int32_t; +}; + +[[nodiscard]] constexpr Sample::type +ConvertSample(double offset, double scaling, + Sample::type sample) { + return static_cast::type>((sample - offset) / + scaling); +} + +[[nodiscard]] constexpr Sample::type +ConvertSample(double offset, double scaling, + Sample::type sample) { + return scaling * static_cast::type>(sample) + + offset; } +} // namespace edfio diff --git a/include/edfio/core/StreamIO.hpp b/include/edfio/core/StreamIO.hpp index 6630b84..b8606f8 100644 --- a/include/edfio/core/StreamIO.hpp +++ b/include/edfio/core/StreamIO.hpp @@ -11,20 +11,17 @@ #include -namespace edfio -{ +namespace edfio { - template - struct StreamIO - { - using Stream = StreamT; - using ValueType = CharT; - }; +template struct StreamIO { + using Stream = StreamT; + using ValueType = CharT; +}; - template - using Reader = StreamIO , CharT>; +template +using Reader = StreamIO, CharT>; - template - using Writer = StreamIO , CharT>; +template +using Writer = StreamIO, CharT>; -} +} // namespace edfio diff --git a/include/edfio/header/HeaderExam.hpp b/include/edfio/header/HeaderExam.hpp index 3dc1e7e..5b21adb 100644 --- a/include/edfio/header/HeaderExam.hpp +++ b/include/edfio/header/HeaderExam.hpp @@ -14,13 +14,11 @@ #include -namespace edfio -{ +namespace edfio { - struct HeaderExam - { - HeaderGeneral m_general; - std::vector m_signals; - }; +struct HeaderExam { + HeaderGeneral m_general; + std::vector m_signals; +}; -} +} // namespace edfio diff --git a/include/edfio/header/HeaderGeneral.hpp b/include/edfio/header/HeaderGeneral.hpp index 101515b..7209a39 100644 --- a/include/edfio/header/HeaderGeneral.hpp +++ b/include/edfio/header/HeaderGeneral.hpp @@ -9,63 +9,71 @@ #pragma once +#include + #include "../core/DataFormat.hpp" #include "../core/Field.hpp" #include -#include -namespace edfio -{ +namespace edfio { + +struct Date { + int32_t day = 0; + int32_t month = 0; + int32_t year = 0; +}; + +struct Time { + int32_t hour = 0; + int32_t minute = 0; + int32_t second = 0; +}; - struct HeaderGeneralFields - { - Field<8> m_version; - Field<80> m_patient; - Field<80> m_recording; - Field<8> m_startDate; - Field<8> m_startTime; - Field<8> m_headerSize; - Field<44> m_reserved; - Field<8> m_datarecordsFile; - Field<8> m_datarecordDuration; - Field<4> m_totalSignals; - }; +struct HeaderGeneralFields { + Field<8> m_version; + Field<80> m_patient; + Field<80> m_recording; + Field<8> m_startDate; + Field<8> m_startTime; + Field<8> m_headerSize; + Field<44> m_reserved; + Field<8> m_datarecordsFile; + Field<8> m_datarecordDuration; + Field<4> m_totalSignals; +}; - namespace detail - { - struct HeaderGeneralDetail - { - unsigned int m_recordSize = 0; - double m_fileDuration = 0; +namespace detail { +struct HeaderGeneralDetail { + uint32_t m_recordSize = 0; + double m_fileDuration = 0; - std::string m_patientCode; - std::string m_gender; - std::string m_birthdate; - std::string m_patientName; - std::string m_patientAdditional; - std::string m_admincode; - std::string m_technician; - std::string m_equipment; - std::string m_recordingAdditional; - }; - } + std::string m_patientCode; + std::string m_gender; + std::string m_birthdate; + std::string m_patientName; + std::string m_patientAdditional; + std::string m_admincode; + std::string m_technician; + std::string m_equipment; + std::string m_recordingAdditional; +}; +} // namespace detail - struct HeaderGeneral - { - // Field values - DataFormat m_version = DataFormat::Invalid; - std::string m_patient; - std::string m_recording; - std::tuple m_startDate; - std::tuple m_startTime; - int m_headerSize = 0; - std::string m_reserved; - long long m_datarecordsFile = 0; - double m_datarecordDuration = 0; - int m_totalSignals = 0; - // Extra values - detail::HeaderGeneralDetail m_detail; - }; +struct HeaderGeneral { + // Field values + DataFormat m_version = DataFormat::Invalid; + std::string m_patient; + std::string m_recording; + Date m_startDate; + Time m_startTime; + int32_t m_headerSize = 0; + std::string m_reserved; + int64_t m_datarecordsFile = 0; + double m_datarecordDuration = 0; + int32_t m_totalSignals = 0; + // Extra values + detail::HeaderGeneralDetail m_detail; +}; -} +} // namespace edfio diff --git a/include/edfio/header/HeaderSignal.hpp b/include/edfio/header/HeaderSignal.hpp index 99bd21b..c1f7278 100644 --- a/include/edfio/header/HeaderSignal.hpp +++ b/include/edfio/header/HeaderSignal.hpp @@ -9,53 +9,50 @@ #pragma once +#include + #include "../core/Field.hpp" #include -namespace edfio -{ - - struct HeaderSignalFields - { - Field<16> m_label; - Field<80> m_transducer; - Field<8> m_physDimension; - Field<8> m_physicalMin; - Field<8> m_physicalMax; - Field<8> m_digitalMin; - Field<8> m_digitalMax; - Field<80> m_prefilter; - Field<8> m_samplesInDataRecord; - Field<32> m_reserved; - }; - - namespace detail - { - struct HeaderSignalDetail - { - long m_signalOffset = 0; - double m_scaling = 0; - double m_offset = 0; - bool m_isAnnotation = false; - }; - } - - struct HeaderSignal - { - // Field values - std::string m_label; - std::string m_transducer; - std::string m_physDimension; - double m_physicalMin = 0; - double m_physicalMax = 0; - int m_digitalMin = 0; - int m_digitalMax = 0; - std::string m_prefilter; - int m_samplesInDataRecord = 0; - std::string m_reserved; - // Extra values - detail::HeaderSignalDetail m_detail; - }; - -} +namespace edfio { + +struct HeaderSignalFields { + Field<16> m_label; + Field<80> m_transducer; + Field<8> m_physDimension; + Field<8> m_physicalMin; + Field<8> m_physicalMax; + Field<8> m_digitalMin; + Field<8> m_digitalMax; + Field<80> m_prefilter; + Field<8> m_samplesInDataRecord; + Field<32> m_reserved; +}; + +namespace detail { +struct HeaderSignalDetail { + int64_t m_signalOffset = 0; + double m_scaling = 0; + double m_offset = 0; + bool m_isAnnotation = false; +}; +} // namespace detail + +struct HeaderSignal { + // Field values + std::string m_label; + std::string m_transducer; + std::string m_physDimension; + double m_physicalMin = 0; + double m_physicalMax = 0; + int32_t m_digitalMin = 0; + int32_t m_digitalMax = 0; + std::string m_prefilter; + int32_t m_samplesInDataRecord = 0; + std::string m_reserved; + // Extra values + detail::HeaderSignalDetail m_detail; +}; + +} // namespace edfio diff --git a/include/edfio/header/HeaderUtils.hpp b/include/edfio/header/HeaderUtils.hpp index 21d45ad..0c05a3a 100644 --- a/include/edfio/header/HeaderUtils.hpp +++ b/include/edfio/header/HeaderUtils.hpp @@ -9,137 +9,109 @@ #pragma once -#include "../Defs.hpp" +#include "../Errors.hpp" #include "HeaderGeneral.hpp" #include "HeaderSignal.hpp" -#include +#include +#include #include -namespace edfio -{ - - namespace detail - { - - static HeaderGeneral CreateHeaderGeneral( - DataFormat version, - std::string patient, - std::string recording, - int startDateD, - int startDateM, - int startDateY, - int startTimeH, - int startTimeM, - int startTimeS, - int headerSize, - std::string reserved, - long long datarecordsFile, - double datarecordDuration, - const std::vector& signals - ) - { - HeaderGeneral header; - header.m_version = version; - header.m_patient = patient; - header.m_recording = recording; - header.m_startDate = std::make_tuple(startDateD, startDateM, startDateY); - header.m_startTime = std::make_tuple(startTimeH, startTimeM, startTimeS); - header.m_headerSize = headerSize; - header.m_reserved = reserved; - header.m_datarecordsFile = datarecordsFile; - header.m_datarecordDuration = datarecordDuration; - header.m_totalSignals = signals.size(); - - // Record size - header.m_detail.m_recordSize = 0; - for (auto &signal : signals) - { - header.m_detail.m_recordSize += signal.m_samplesInDataRecord; - } - header.m_detail.m_recordSize *= GetSampleBytes(version); - - return std::move(header); - } - - static HeaderGeneral CreateHeaderGeneralPlus( - DataFormat version, - std::string patientCode, - std::string gender, - std::string birthdate, - std::string patientName, - std::string patientAdditional, - std::string admincode, - std::string technician, - std::string equipment, - std::string recordingAdditional, - int startDateD, - int startDateM, - int startDateY, - int startTimeH, - int startTimeM, - int startTimeS, - int headerSize, - std::string reserved, - long long datarecordsFile, - double datarecordDuration, - const std::vector& signals - ) - { - auto header = std::move(CreateHeaderGeneral( - version, "", "", startDateD, startDateM, startDateY, startTimeH, startTimeM, startTimeS, - headerSize, reserved, datarecordsFile, datarecordDuration, signals - )); - - header.m_detail.m_patientCode = patientCode; - header.m_detail.m_gender = gender; - header.m_detail.m_birthdate = birthdate; - header.m_detail.m_patientName = patientName; - header.m_detail.m_patientAdditional = patientAdditional; - header.m_detail.m_admincode = admincode; - header.m_detail.m_technician = technician; - header.m_detail.m_equipment = equipment; - header.m_detail.m_recordingAdditional = recordingAdditional; - - return std::move(header); - } - - static HeaderSignal CreateHeaderSignal( - std::string label, - int samplesInDataRecord, - double physicalMin, - double physicalMax, - int digitalMin, - int digitalMax, - long signalOffset = 0, - bool annotation = false, - std::string transducer = "", - std::string physDimension = "", - std::string prefilter = "", - std::string reserved = "" - ) - { - HeaderSignal signal; - - signal.m_label = label; - signal.m_transducer = transducer; - signal.m_physDimension = physDimension; - signal.m_physicalMin = physicalMin; - signal.m_physicalMax = physicalMax; - signal.m_digitalMin = digitalMin; - signal.m_digitalMax = digitalMax; - signal.m_prefilter = prefilter; - signal.m_samplesInDataRecord = samplesInDataRecord; - signal.m_reserved = reserved; - - signal.m_detail.m_signalOffset = signalOffset; - signal.m_detail.m_scaling = (signal.m_physicalMax - signal.m_physicalMin) / (signal.m_digitalMax - signal.m_digitalMin); - signal.m_detail.m_offset = signal.m_physicalMin - signal.m_detail.m_scaling * signal.m_digitalMin; - signal.m_detail.m_isAnnotation = annotation; - - return std::move(signal); - } - - } +namespace edfio { + +namespace detail { + +inline HeaderGeneral CreateHeaderGeneral( + DataFormat version, std::string patient, std::string recording, + int32_t startDateD, int32_t startDateM, int32_t startDateY, + int32_t startTimeH, int32_t startTimeM, int32_t startTimeS, + int32_t headerSize, std::string reserved, int64_t datarecordsFile, + double datarecordDuration, std::span signals) { + HeaderGeneral header; + header.m_version = version; + header.m_patient = patient; + header.m_recording = recording; + header.m_startDate = Date{startDateD, startDateM, startDateY}; + header.m_startTime = Time{startTimeH, startTimeM, startTimeS}; + header.m_headerSize = headerSize; + header.m_reserved = reserved; + header.m_datarecordsFile = datarecordsFile; + header.m_datarecordDuration = datarecordDuration; + header.m_totalSignals = static_cast(signals.size()); + + // Record size + header.m_detail.m_recordSize = 0; + for (auto &signal : signals) { + header.m_detail.m_recordSize += signal.m_samplesInDataRecord; + } + header.m_detail.m_recordSize *= GetSampleBytes(version); + + return header; +} + +inline HeaderGeneral CreateHeaderGeneralPlus( + DataFormat version, std::string patientCode, std::string gender, + std::string birthdate, std::string patientName, + std::string patientAdditional, std::string admincode, + std::string technician, std::string equipment, + std::string recordingAdditional, int32_t startDateD, int32_t startDateM, + int32_t startDateY, int32_t startTimeH, int32_t startTimeM, + int32_t startTimeS, int32_t headerSize, std::string reserved, + int64_t datarecordsFile, double datarecordDuration, + std::span signals) { + auto header = CreateHeaderGeneral( + version, "", "", startDateD, startDateM, startDateY, startTimeH, + startTimeM, startTimeS, headerSize, reserved, datarecordsFile, + datarecordDuration, signals); + + header.m_detail.m_patientCode = patientCode; + header.m_detail.m_gender = gender; + header.m_detail.m_birthdate = birthdate; + header.m_detail.m_patientName = patientName; + header.m_detail.m_patientAdditional = patientAdditional; + header.m_detail.m_admincode = admincode; + header.m_detail.m_technician = technician; + header.m_detail.m_equipment = equipment; + header.m_detail.m_recordingAdditional = recordingAdditional; + + return header; +} +inline HeaderSignal +CreateHeaderSignal(std::string label, int32_t samplesInDataRecord, + double physicalMin, double physicalMax, int32_t digitalMin, + int32_t digitalMax, int64_t signalOffset = 0, + bool annotation = false, std::string transducer = "", + std::string physDimension = "", std::string prefilter = "", + std::string reserved = "") { + HeaderSignal signal; + + signal.m_label = label; + signal.m_transducer = transducer; + signal.m_physDimension = physDimension; + signal.m_physicalMin = physicalMin; + signal.m_physicalMax = physicalMax; + signal.m_digitalMin = digitalMin; + signal.m_digitalMax = digitalMax; + signal.m_prefilter = prefilter; + signal.m_samplesInDataRecord = samplesInDataRecord; + signal.m_reserved = reserved; + + signal.m_detail.m_signalOffset = signalOffset; + auto digitalRange = signal.m_digitalMax - signal.m_digitalMin; + if (digitalRange == 0) { + throw std::invalid_argument( + GetError(FileErrc::FileContainsFormatErrors)); + } + signal.m_detail.m_scaling = + (signal.m_physicalMax - signal.m_physicalMin) / digitalRange; + signal.m_detail.m_offset = + signal.m_physicalMin - signal.m_detail.m_scaling * signal.m_digitalMin; + signal.m_detail.m_isAnnotation = annotation; + + return signal; } + +} // namespace detail + +} // namespace edfio diff --git a/include/edfio/processor/ProcessorAnnotation.hpp b/include/edfio/processor/ProcessorAnnotation.hpp index 4b72101..ea1e29b 100644 --- a/include/edfio/processor/ProcessorAnnotation.hpp +++ b/include/edfio/processor/ProcessorAnnotation.hpp @@ -9,17 +9,60 @@ #pragma once -#include "../core/Record.hpp" +#include "../Errors.hpp" #include "../core/Annotation.hpp" +#include "../core/Record.hpp" +#include "ProcessorUtils.hpp" + +#include + +namespace edfio { + +inline Record ProcessAnnotation(Annotation annotation) { + if (annotation.m_annotation.empty()) { + throw std::invalid_argument( + GetError(FileErrc::FileWriteInvalidAnnotations)); + } + + std::string timestamp = (annotation.m_start >= 0 ? "+" : "") + + detail::to_string_decimal(annotation.m_start); + std::string duration; + if (annotation.m_duration > 0) + duration = detail::to_string_decimal(annotation.m_duration); + + size_t size = timestamp.size(); // timestamp + if (!duration.empty()) { + size++; // 21 div + size += duration.size(); // duration + } + + size++; // 20 div + size += annotation.m_annotation.size(); // annotation + size += 2; // 20 div and 0 + + Record record(size); + auto it = record().begin(); + + // timestamp + std::ranges::copy(timestamp, it); + it += timestamp.size(); + + if (!duration.empty()) { + *it++ = 21; // 21 div + // duration + std::ranges::copy(duration, it); + it += duration.size(); + } -namespace edfio -{ + *it++ = 20; // 20 div + // annotation + std::ranges::copy(annotation.m_annotation, it); + it += annotation.m_annotation.size(); - struct ProcessorAnnotation - { - Record operator ()(Annotation annotation); - }; + *it++ = 20; // 20 div + *it++ = 0; // 0 end + return record; } -#include "impl/ProcessorAnnotation.ipp" +} // namespace edfio diff --git a/include/edfio/processor/ProcessorHeaderExam.hpp b/include/edfio/processor/ProcessorHeaderExam.hpp index e4aa4a1..71d9694 100644 --- a/include/edfio/processor/ProcessorHeaderExam.hpp +++ b/include/edfio/processor/ProcessorHeaderExam.hpp @@ -9,16 +9,36 @@ #pragma once +#include "../Errors.hpp" +#include "../core/DataFormat.hpp" #include "../header/HeaderExam.hpp" -namespace edfio -{ +#include - struct ProcessorHeaderExam - { - HeaderExam operator ()(HeaderGeneral header, std::vector signals); - }; +namespace edfio { +inline HeaderExam ProcessHeaderExam(HeaderGeneral header, + std::vector signals) { + // Record size + uint32_t recordsize = 0; + for (auto &signal : signals) { + recordsize += signal.m_samplesInDataRecord; + } + + if (IsBdf(header.m_version)) { + recordsize *= 3; + if (recordsize > 0xF00000) { + throw std::invalid_argument(GetError(FileErrc::FileContainsFormatErrors)); + } + } else { + recordsize *= 2; + if (recordsize > 0xA00000) { + throw std::invalid_argument(GetError(FileErrc::FileContainsFormatErrors)); + } + } + header.m_detail.m_recordSize = recordsize; + + return HeaderExam{std::move(header), std::move(signals)}; } -#include "impl/ProcessorHeaderExam.ipp" +} // namespace edfio diff --git a/include/edfio/processor/ProcessorHeaderGeneral.hpp b/include/edfio/processor/ProcessorHeaderGeneral.hpp index 9b723c5..5a56a32 100644 --- a/include/edfio/processor/ProcessorHeaderGeneral.hpp +++ b/include/edfio/processor/ProcessorHeaderGeneral.hpp @@ -9,16 +9,145 @@ #pragma once +#include "../core/DataFormat.hpp" #include "../header/HeaderGeneral.hpp" +#include "ProcessorUtils.hpp" -namespace edfio -{ +#include +#include +#include +#include - struct ProcessorHeaderGeneral - { - HeaderGeneralFields operator ()(HeaderGeneral in); - }; +namespace edfio { +inline HeaderGeneralFields ProcessHeaderGeneral(HeaderGeneral in) { + HeaderGeneralFields out; + + // Version + { + if (IsEdf(in.m_version)) { + out.m_version("0 "); + } else if (IsBdf(in.m_version)) { + std::string value = "BIOSEMI"; + value.insert(value.begin(), -1); + out.m_version(value); + } + } + // Patient Name + { + out.m_patient(in.m_patient); + } + // Recording + { + out.m_recording(in.m_recording); + } + // Start Date + { + auto [day, month, year] = in.m_startDate; + year -= year > 1999 ? 2000 : 1900; + out.m_startDate(std::format("{:02d}.{:02d}.{:02d}", day, month, year)); + } + // Start Time + { + auto [hour, minute, second] = in.m_startTime; + out.m_startTime(std::format("{:02d}.{:02d}.{:02d}", hour, minute, second)); + } + // Header Size + { + out.m_headerSize(std::to_string(in.m_headerSize)); + } + // Reserved + { + if (!in.m_reserved.empty()) { + out.m_reserved(in.m_reserved); + } else if (IsPlus(in.m_version)) { + out.m_reserved(std::string(detail::GetFormatName(in.m_version))); + } + } + // Datarecords in File + { + out.m_datarecordsFile(std::to_string(in.m_datarecordsFile)); + } + // Datarecord Duration + { + out.m_datarecordDuration( + detail::to_string_decimal(in.m_datarecordDuration)); + } + // Number of signals + { + out.m_totalSignals(std::to_string(in.m_totalSignals)); + } + // Plus Fields + if (IsPlus(in.m_version)) { + // Patient Name + { + std::vector fields; + // Code + fields.push_back( + in.m_detail.m_patientCode.empty() ? "X" : in.m_detail.m_patientCode); + // Sex + fields.push_back(in.m_detail.m_gender.empty() ? "X" + : in.m_detail.m_gender); + // Birthdate in dd-MMM-yyyy format using the English 3-character + // abbreviations of the month in capitals. 02-AUG-1951 is OK, while + // 2-AUG-1951 is not. + fields.push_back( + in.m_detail.m_birthdate.empty() ? "X" : in.m_detail.m_birthdate); + // The patients name. + fields.push_back( + in.m_detail.m_patientName.empty() ? "X" : in.m_detail.m_patientName); + // Additional information. + std::string info; + std::istringstream f(in.m_detail.m_patientAdditional); + while (std::getline(f, info, detail::ADDITIONAL_SEPARATOR)) { + fields.push_back(info); + } + std::string patient = ""; + for (auto &field : fields) { + std::ranges::replace(field, ' ', '_'); // replace all ' ' to '_' + patient += field + " "; + } + patient.pop_back(); // remove last " " + out.m_patient(patient); + } + // Recording + { + std::vector fields; + // The text 'Startdate' + fields.push_back("Startdate"); + // The startdate itself in dd-MMM-yyyy format using the English + // 3-character abbreviations of the month in capitals: dd-MMM-yyyy (MMM = + // 'JAN' | 'FEV' | ...) + auto [day, month, year] = in.m_startDate; + fields.push_back(std::format("{:02d}-{}-{}", day ? day : 1, + detail::GetStringFromMonth(month), + year ? year : 1984)); + // The hospital administration code of the investigation, i.e. EEG number + // or PSG number. + fields.push_back( + in.m_detail.m_admincode.empty() ? "X" : in.m_detail.m_admincode); + // A code specifying the responsible investigator or technician. + fields.push_back( + in.m_detail.m_technician.empty() ? "X" : in.m_detail.m_technician); + // A code specifying the used equipment. + fields.push_back( + in.m_detail.m_equipment.empty() ? "X" : in.m_detail.m_equipment); + // Additional information. + std::string info; + std::istringstream f(in.m_detail.m_recordingAdditional); + while (std::getline(f, info, detail::ADDITIONAL_SEPARATOR)) { + fields.push_back(info); + } + std::string recording = ""; + for (auto &field : fields) { + std::ranges::replace(field, ' ', '_'); // replace all '_' to ' ' + recording += field + " "; + } + recording.pop_back(); // remove last " " + out.m_recording(recording); + } + } + return out; } -#include "impl/ProcessorHeaderGeneral.ipp" +} // namespace edfio diff --git a/include/edfio/processor/ProcessorHeaderGeneralFields.hpp b/include/edfio/processor/ProcessorHeaderGeneralFields.hpp index 7728faf..ff30413 100644 --- a/include/edfio/processor/ProcessorHeaderGeneralFields.hpp +++ b/include/edfio/processor/ProcessorHeaderGeneralFields.hpp @@ -9,16 +9,304 @@ #pragma once +#include "../Errors.hpp" +#include "../core/DataFormat.hpp" #include "../header/HeaderGeneral.hpp" +#include "ProcessorUtils.hpp" -namespace edfio -{ +#include +#include +#include - struct ProcessorHeaderGeneralFields - { - HeaderGeneral operator ()(HeaderGeneralFields in); - }; +namespace edfio { +inline HeaderGeneral ProcessHeaderGeneralFields(HeaderGeneralFields in) { + HeaderGeneral out; + + if (/*detail::CheckFormatErrors(in.m_version()) + ||*/ + detail::CheckFormatErrors(in.m_patient()) || + detail::CheckFormatErrors(in.m_recording()) || + detail::CheckFormatErrors(in.m_startDate()) || + detail::CheckFormatErrors(in.m_startTime()) || + detail::CheckFormatErrors(in.m_headerSize()) || + detail::CheckFormatErrors(in.m_reserved()) || + detail::CheckFormatErrors(in.m_datarecordsFile()) || + detail::CheckFormatErrors(in.m_datarecordDuration()) || + detail::CheckFormatErrors(in.m_totalSignals())) { + throw std::invalid_argument(GetError(FileErrc::FileContainsFormatErrors)); + } + + // Version + { + auto &version = in.m_version(); + if (version.front() == -1) // BDF-file + { + if (version.substr(1) != "BIOSEMI") { + throw std::invalid_argument( + GetError(FileErrc::FileContainsFormatErrors)); + } + out.m_version = DataFormat::Bdf; + } else // EDF-file + { + if (version != "0 ") { + throw std::invalid_argument( + GetError(FileErrc::FileContainsFormatErrors)); + } + out.m_version = DataFormat::Edf; + } + } + // Patient Name + { + out.m_patient = in.m_patient(); + } + // Recording + { + out.m_recording = in.m_recording(); + } + // Start Date + { + auto &startdate = in.m_startDate(); + if ((startdate[2] != '.') || (startdate[5] != '.') || + !std::isdigit(startdate[0]) || !std::isdigit(startdate[1]) || + !std::isdigit(startdate[3]) || !std::isdigit(startdate[4]) || + !std::isdigit(startdate[6]) || !std::isdigit(startdate[7])) { + throw std::invalid_argument(GetError(FileErrc::FileContainsFormatErrors)); + } + { + int32_t day{}, month{}, year{}; + auto [p1, e1] = + std::from_chars(startdate.data(), startdate.data() + 2, day); + auto [p2, e2] = + std::from_chars(startdate.data() + 3, startdate.data() + 5, month); + auto [p3, e3] = + std::from_chars(startdate.data() + 6, startdate.data() + 8, year); + if (e1 != std::errc{} || e2 != std::errc{} || e3 != std::errc{} || + day < 1 || day > 31 || month < 1 || month > 12) { + throw std::invalid_argument( + GetError(FileErrc::FileContainsFormatErrors)); + } + year += year > 84 ? 1900 : 2000; + out.m_startDate = Date{day, month, year}; + } + } + // Start Time + { + auto &starttime = in.m_startTime(); + if ((starttime[2] != '.') || (starttime[5] != '.') || + !std::isdigit(starttime[0]) || !std::isdigit(starttime[1]) || + !std::isdigit(starttime[3]) || !std::isdigit(starttime[4]) || + !std::isdigit(starttime[6]) || !std::isdigit(starttime[7])) { + throw std::invalid_argument(GetError(FileErrc::FileContainsFormatErrors)); + } + { + int32_t hour{}, minute{}, second{}; + auto [p1, e1] = + std::from_chars(starttime.data(), starttime.data() + 2, hour); + auto [p2, e2] = + std::from_chars(starttime.data() + 3, starttime.data() + 5, minute); + auto [p3, e3] = + std::from_chars(starttime.data() + 6, starttime.data() + 8, second); + if (e1 != std::errc{} || e2 != std::errc{} || e3 != std::errc{} || + hour > 23 || minute > 59 || second > 59) { + throw std::invalid_argument( + GetError(FileErrc::FileContainsFormatErrors)); + } + out.m_startTime = Time{hour, minute, second}; + } + } + // Header Size + { + out.m_headerSize = detail::ParseInt( + in.m_headerSize(), GetError(FileErrc::FileContainsFormatErrors)); + } + // Reserved + { + auto &reserved = in.m_reserved(); + if (IsEdf(out.m_version)) { + if (reserved.find("EDF+C") != std::string::npos) { + out.m_version = DataFormat::EdfPlusC; + } else if (reserved.find("EDF+D") != std::string::npos) { + out.m_version = DataFormat::EdfPlusD; + } + } else if (IsBdf(out.m_version)) { + if (reserved.find("BDF+C") != std::string::npos) { + out.m_version = DataFormat::BdfPlusC; + } else if (reserved.find("BDF+D") != std::string::npos) { + out.m_version = DataFormat::BdfPlusD; + } + } + } + // Datarecords in File + { + out.m_datarecordsFile = detail::ParseLongLong( + in.m_datarecordsFile(), GetError(FileErrc::FileContainsFormatErrors)); + if (out.m_datarecordsFile < 0) { + throw std::invalid_argument(GetError(FileErrc::FileContainsFormatErrors)); + } + } + // Datarecord Duration + { + double duration = + detail::ParseDouble(in.m_datarecordDuration(), + GetError(FileErrc::FileContainsFormatErrors)); + out.m_datarecordDuration = duration; + if (duration < 0) { + throw std::invalid_argument(GetError(FileErrc::FileContainsFormatErrors)); + } + out.m_detail.m_fileDuration = + out.m_datarecordDuration * out.m_datarecordsFile; + } + // Number of signals + { + int32_t signals = detail::ParseInt( + in.m_totalSignals(), GetError(FileErrc::FileContainsFormatErrors)); + if (signals <= 0 || (signals * 256 + 256) != out.m_headerSize) { + throw std::invalid_argument(GetError(FileErrc::FileContainsFormatErrors)); + } + out.m_totalSignals = signals; + } + // Plus Fields + if (IsPlus(out.m_version)) { + // Patient Name + { + auto &details = out.m_detail; + std::vector fields; + std::string field; + std::istringstream f(out.m_patient); + while (std::getline(f, field, ' ')) { + fields.push_back(field); + } + if (fields.size() < 4) { + throw std::invalid_argument( + GetError(FileErrc::FileContainsFormatErrors)); + } + + details.m_patientAdditional.clear(); + + for (size_t i = 0; i < fields.size(); i++) { + auto &str = fields[i]; + std::ranges::replace(str, '_', ' '); // replace all '_' to ' ' + switch (i) { + case 0: // The code by which the patient is known in the hospital + // administration. + details.m_patientCode = str; + break; + case 1: // Sex + if (str == "F" || str == "M" || str == "X") { + details.m_gender = str; + } else { + throw std::invalid_argument( + GetError(FileErrc::FileContainsFormatErrors)); + } + break; + case 2: // Birthdate in dd-MMM-yyyy format using the English 3-character + // abbreviations of the month in capitals. 02-AUG-1951 is OK, + // while 2-AUG-1951 is not. + details.m_birthdate = str; + break; + case 3: // The patients name. + details.m_patientName = str; + break; + default: // Additional information. + if (!details.m_patientAdditional.empty()) { + details.m_patientAdditional += detail::ADDITIONAL_SEPARATOR; + } + details.m_patientAdditional.append(str); + break; + } + } + } + // Recording + { + auto &details = out.m_detail; + std::vector fields; + std::string field; + std::istringstream f(out.m_recording); + while (std::getline(f, field, ' ')) { + fields.push_back(field); + } + + if (fields.size() < 5) { + throw std::invalid_argument( + GetError(FileErrc::FileContainsFormatErrors)); + } + + details.m_recordingAdditional.clear(); + + for (size_t i = 0; i < fields.size(); i++) { + auto &str = fields[i]; + std::ranges::replace(str, '_', ' '); // replace all '_' to ' ' + if (str != "X") { + switch (i) { + case 0: // The text 'Startdate'. + if (str != "Startdate") { + throw std::invalid_argument( + GetError(FileErrc::FileContainsFormatErrors)); + } + break; + case 1: // The startdate itself in dd-MMM-yyyy format using the + // English 3-character abbreviations of the month in capitals: + // dd-MMM-yyyy (MMM = 'JAN' | 'FEV' | ...) + if (str.size() == 11 && str[2] == '-' && str[6] == '-') { + { + int32_t day{}, year{}; + auto [p1, e1] = + std::from_chars(str.data(), str.data() + 2, day); + auto [p2, e2] = + std::from_chars(str.data() + 7, str.data() + 11, year); + int32_t month = detail::GetMonthFromString( + std::string_view{str}.substr(3, 3)); + if (e1 != std::errc{} || e2 != std::errc{} || month == 0) { + throw std::invalid_argument( + GetError(FileErrc::FileContainsFormatErrors)); + } + out.m_startDate = Date{day, month, year}; + } + } else { + throw std::invalid_argument( + GetError(FileErrc::FileContainsFormatErrors)); + } + break; + case 2: // The hospital administration code of the investigation, i.e. + // EEG number or PSG number. + details.m_admincode = str; + break; + case 3: // A code specifying the responsible investigator or + // technician. + details.m_technician = str; + break; + case 4: // A code specifying the used equipment. + details.m_equipment = str; + break; + default: // Additional information. + if (!details.m_recordingAdditional.empty()) { + details.m_recordingAdditional += detail::ADDITIONAL_SEPARATOR; + } + details.m_recordingAdditional.append(str); + break; + } + } + } + } + } + + out.m_patient = detail::ReduceString(out.m_patient); + out.m_recording = detail::ReduceString(out.m_recording); + out.m_reserved = detail::ReduceString(out.m_reserved); + out.m_detail.m_patientCode = detail::ReduceString(out.m_detail.m_patientCode); + out.m_detail.m_gender = detail::ReduceString(out.m_detail.m_gender); + out.m_detail.m_birthdate = detail::ReduceString(out.m_detail.m_birthdate); + out.m_detail.m_patientName = detail::ReduceString(out.m_detail.m_patientName); + out.m_detail.m_patientAdditional = + detail::ReduceString(out.m_detail.m_patientAdditional); + out.m_detail.m_admincode = detail::ReduceString(out.m_detail.m_admincode); + out.m_detail.m_technician = detail::ReduceString(out.m_detail.m_technician); + out.m_detail.m_equipment = detail::ReduceString(out.m_detail.m_equipment); + out.m_detail.m_recordingAdditional = + detail::ReduceString(out.m_detail.m_recordingAdditional); + + return out; } -#include "impl/ProcessorHeaderGeneralFields.ipp" +} // namespace edfio diff --git a/include/edfio/processor/ProcessorHeaderSignal.hpp b/include/edfio/processor/ProcessorHeaderSignal.hpp index b6cf110..4b945d7 100644 --- a/include/edfio/processor/ProcessorHeaderSignal.hpp +++ b/include/edfio/processor/ProcessorHeaderSignal.hpp @@ -10,15 +10,33 @@ #pragma once #include "../header/HeaderSignal.hpp" +#include "ProcessorUtils.hpp" -namespace edfio -{ +#include +#include +#include - struct ProcessorHeaderSignal - { - std::vector operator ()(std::vector in); - }; +namespace edfio { +inline std::vector +ProcessHeaderSignal(std::vector in) { + std::vector out(in.size()); + auto &signals = in; + + for (auto &&[outSig, inSig] : std::views::zip(out, signals)) { + outSig.m_label(inSig.m_label); + outSig.m_transducer(inSig.m_transducer); + outSig.m_physDimension(inSig.m_physDimension); + outSig.m_physicalMin(detail::to_string_decimal(inSig.m_physicalMin)); + outSig.m_physicalMax(detail::to_string_decimal(inSig.m_physicalMax)); + outSig.m_digitalMin(std::to_string(inSig.m_digitalMin)); + outSig.m_digitalMax(std::to_string(inSig.m_digitalMax)); + outSig.m_prefilter(inSig.m_prefilter); + outSig.m_samplesInDataRecord(std::to_string(inSig.m_samplesInDataRecord)); + outSig.m_reserved(inSig.m_reserved); + } + + return out; } -#include "impl/ProcessorHeaderSignal.ipp" +} // namespace edfio diff --git a/include/edfio/processor/ProcessorHeaderSignalFields.hpp b/include/edfio/processor/ProcessorHeaderSignalFields.hpp index 5bb6859..cc401c5 100644 --- a/include/edfio/processor/ProcessorHeaderSignalFields.hpp +++ b/include/edfio/processor/ProcessorHeaderSignalFields.hpp @@ -9,24 +9,236 @@ #pragma once +#include "../Errors.hpp" #include "../core/DataFormat.hpp" #include "../header/HeaderSignal.hpp" +#include "ProcessorUtils.hpp" -namespace edfio -{ - - struct ProcessorHeaderSignalFields - { - ProcessorHeaderSignalFields(DataFormat version, double datarecordDuration) - : m_version(version) - , m_datarecordDuration(datarecordDuration) - {} - std::vector operator ()(std::vector in); - private: - DataFormat m_version; - double m_datarecordDuration; - }; +#include +#include +#include +namespace edfio { + +inline std::vector +ProcessHeaderSignalFields(std::vector in, + DataFormat version, + [[maybe_unused]] double datarecordDuration) { + std::vector signals(in.size()); + + for (auto &sigFields : in) { + if (detail::CheckFormatErrors(sigFields.m_label()) || + detail::CheckFormatErrors(sigFields.m_transducer()) || + detail::CheckFormatErrors(sigFields.m_physDimension()) || + detail::CheckFormatErrors(sigFields.m_physicalMin()) || + detail::CheckFormatErrors(sigFields.m_physicalMax()) || + detail::CheckFormatErrors(sigFields.m_digitalMin()) || + detail::CheckFormatErrors(sigFields.m_digitalMax()) || + detail::CheckFormatErrors(sigFields.m_prefilter()) || + detail::CheckFormatErrors(sigFields.m_samplesInDataRecord()) || + detail::CheckFormatErrors(sigFields.m_reserved())) { + throw std::invalid_argument(GetError(FileErrc::FileContainsFormatErrors)); + } + } + + // Labels + { + uint32_t totalAnnotationChannels = 0; + for (auto &&[signal, inSig] : std::views::zip(signals, in)) { + auto &label = inSig.m_label(); + if (IsPlus(version)) { + if (label.find("Annotation") != std::string::npos) { + totalAnnotationChannels++; + signal.m_detail.m_isAnnotation = true; + } else { + signal.m_detail.m_isAnnotation = false; + } + } else { + signal.m_detail.m_isAnnotation = false; + } + signal.m_label = label; + } + if (IsPlus(version) && totalAnnotationChannels == 0) { + throw std::invalid_argument(GetError(FileErrc::FileContainsFormatErrors)); + } + } + // Transducers Types + { + for (auto &&[signal, inSig] : std::views::zip(signals, in)) { + auto &transducer = inSig.m_transducer(); + + signal.m_transducer = transducer; + + if (signal.m_detail.m_isAnnotation) { + if (transducer.find_first_not_of(' ') != std::string::npos) { + throw std::invalid_argument( + GetError(FileErrc::FileContainsFormatErrors)); + } + } + } + } + // Physical Dimensions + { + for (auto &&[signal, inSig] : std::views::zip(signals, in)) { + auto &physDimension = inSig.m_physDimension(); + + signal.m_physDimension = physDimension; + } + } + // Physical Minima + { + for (auto &&[signal, inSig] : std::views::zip(signals, in)) { + auto &physMin = inSig.m_physicalMin(); + signal.m_physicalMin = detail::ParseDouble( + physMin, GetError(FileErrc::FileContainsFormatErrors)); + } + } + // Physical Maxima + { + for (auto &&[signal, inSig] : std::views::zip(signals, in)) { + auto &physMax = inSig.m_physicalMax(); + signal.m_physicalMax = detail::ParseDouble( + physMax, GetError(FileErrc::FileContainsFormatErrors)); + } + } + // Digital Minima + { + for (auto &&[signal, inSig] : std::views::zip(signals, in)) { + auto &digMin = inSig.m_digitalMin(); + int32_t n = detail::ParseInt( + digMin, GetError(FileErrc::FileContainsFormatErrors)); + + if (signal.m_detail.m_isAnnotation) { + if (IsEdf(version) && IsPlus(version)) { + if (n != -32768) { + throw std::invalid_argument( + GetError(FileErrc::FileContainsFormatErrors)); + } + } else if (IsBdf(version) && IsPlus(version)) { + if (n != -8388608) { + throw std::invalid_argument( + GetError(FileErrc::FileContainsFormatErrors)); + } + } + } else if (IsEdf(version)) { + if ((n > 32767) || (n < -32768)) { + throw std::invalid_argument( + GetError(FileErrc::FileContainsFormatErrors)); + } + } else if (IsBdf(version)) { + if ((n > 8388607) || (n < -8388608)) { + throw std::invalid_argument( + GetError(FileErrc::FileContainsFormatErrors)); + } + } + signal.m_digitalMin = n; + } + } + // Digital Maxima + { + for (auto &&[signal, inSig] : std::views::zip(signals, in)) { + auto &digMax = inSig.m_digitalMax(); + int32_t n = detail::ParseInt( + digMax, GetError(FileErrc::FileContainsFormatErrors)); + + if (signal.m_detail.m_isAnnotation) { + if (IsEdf(version) && IsPlus(version)) { + if (n != 32767) { + throw std::invalid_argument( + GetError(FileErrc::FileContainsFormatErrors)); + } + } else if (IsBdf(version) && IsPlus(version)) { + if (n != 8388607) { + throw std::invalid_argument( + GetError(FileErrc::FileContainsFormatErrors)); + } + } + } else if (IsEdf(version)) { + if ((n > 32767) || (n < -32768)) { + throw std::invalid_argument( + GetError(FileErrc::FileContainsFormatErrors)); + } + } else if (IsBdf(version)) { + if ((n > 8388607) || (n < -8388608)) { + throw std::invalid_argument( + GetError(FileErrc::FileContainsFormatErrors)); + } + } + signal.m_digitalMax = n; + if (signal.m_digitalMax < (signal.m_digitalMin + 1)) { + throw std::invalid_argument( + GetError(FileErrc::FileContainsFormatErrors)); + } + } + } + // Prefilter + { + for (auto &&[signal, inSig] : std::views::zip(signals, in)) { + auto &prefilter = inSig.m_prefilter(); + + signal.m_prefilter = prefilter; + + if (signal.m_detail.m_isAnnotation) { + if (prefilter.find_first_not_of(' ') != std::string::npos) { + throw std::invalid_argument( + GetError(FileErrc::FileContainsFormatErrors)); + } + } + } + } + // Samples in each datarecord + { + for (auto &&[signal, inSig] : std::views::zip(signals, in)) { + auto &nrSamples = inSig.m_samplesInDataRecord(); + int32_t n = detail::ParseInt( + nrSamples, GetError(FileErrc::FileContainsFormatErrors)); + + if (n < 1) { + throw std::invalid_argument( + GetError(FileErrc::FileContainsFormatErrors)); + } + signal.m_samplesInDataRecord = n; + } + } + // Reserved + { + for (auto &&[signal, inSig] : std::views::zip(signals, in)) { + auto &reserved = inSig.m_reserved(); + signal.m_reserved = reserved; + } + } + // Details + { + uint64_t n = 0; + for (auto &signal : signals) { + signal.m_detail.m_signalOffset = n; + if (IsBdf(version)) + n += signal.m_samplesInDataRecord * 3; + else if (IsEdf(version)) + n += signal.m_samplesInDataRecord * 2; + + auto digitalRange = signal.m_digitalMax - signal.m_digitalMin; + if (digitalRange == 0) { + throw std::invalid_argument( + GetError(FileErrc::FileContainsFormatErrors)); + } + signal.m_detail.m_scaling = + (signal.m_physicalMax - signal.m_physicalMin) / digitalRange; + signal.m_detail.m_offset = + signal.m_physicalMin - + signal.m_detail.m_scaling * signal.m_digitalMin; + } + } + + for (auto &signal : signals) { + signal.m_label = detail::ReduceString(signal.m_label); + signal.m_transducer = detail::ReduceString(signal.m_transducer); + signal.m_physDimension = detail::ReduceString(signal.m_physDimension); + signal.m_prefilter = detail::ReduceString(signal.m_prefilter); + signal.m_reserved = detail::ReduceString(signal.m_reserved); + } + + return signals; } -#include "impl/ProcessorHeaderSignalFields.ipp" +} // namespace edfio diff --git a/include/edfio/processor/ProcessorSample.hpp b/include/edfio/processor/ProcessorSample.hpp index 46c34ef..846cb8c 100644 --- a/include/edfio/processor/ProcessorSample.hpp +++ b/include/edfio/processor/ProcessorSample.hpp @@ -9,34 +9,46 @@ #pragma once -#include "../core/SampleType.hpp" #include "../core/Record.hpp" +#include "../core/SampleType.hpp" + +#include + +namespace edfio { + +template struct ProcessorSample { + using ProcType = typename Sample::type; + using DigiType = Sample::type; + using PhysType = Sample::type; + + ProcessorSample(double offset, double scaling, uint32_t sampleSize) + : m_offset(offset), m_scaling(scaling), m_sampleSize(sampleSize) {} -namespace edfio -{ + Record operator()(ProcType sample); - template - struct ProcessorSample - { - using ProcType = typename impl::Sample::type; - using DigiType = impl::Sample::type; - using PhysType = impl::Sample::type; +private: + const double m_offset; + const double m_scaling; + uint32_t m_sampleSize; +}; - ProcessorSample(double offset, double scaling, size_t sampleSize) - : m_offset(offset) - , m_scaling(scaling) - , m_sampleSize(sampleSize) - { - } +template +inline Record ProcessorSample::operator()(ProcType sample) { + DigiType value = 0; + if (std::is_same::value) + value = static_cast(sample); + else + value = ConvertSample(m_offset, m_scaling, sample); - Record operator ()(ProcType sample); + Record record(m_sampleSize); + auto it = record().begin(); - private: - const double m_offset; - const double m_scaling; - size_t m_sampleSize; - }; + for (uint32_t count = m_sampleSize; count > 0; count--) { + uint8_t tmp = (value >> (count - 1) * 8); + *it++ = tmp; + } + return record; } -#include "impl/ProcessorSample.ipp" +} // namespace edfio diff --git a/include/edfio/processor/ProcessorSampleRecord.hpp b/include/edfio/processor/ProcessorSampleRecord.hpp index d45b7b5..c2434e2 100644 --- a/include/edfio/processor/ProcessorSampleRecord.hpp +++ b/include/edfio/processor/ProcessorSampleRecord.hpp @@ -9,32 +9,51 @@ #pragma once -#include "../core/SampleType.hpp" #include "../core/Record.hpp" +#include "../core/SampleType.hpp" + +#include + +namespace edfio { + +template struct ProcessorSampleRecord { + using ProcType = typename Sample::type; + using DigiType = Sample::type; + using PhysType = Sample::type; + + ProcessorSampleRecord(double offset, double scaling) + : m_offset(offset), m_scaling(scaling) {} -namespace edfio -{ + ProcType operator()(Record record); - template - struct ProcessorSampleRecord - { - using ProcType = typename impl::Sample::type; - using DigiType = impl::Sample::type; - using PhysType = impl::Sample::type; +private: + const double m_offset; + const double m_scaling; +}; - ProcessorSampleRecord(double offset, double scaling) - : m_offset(offset) - , m_scaling(scaling) - { - } +template +inline typename ProcessorSampleRecord::ProcType +ProcessorSampleRecord::operator()(Record record) { + DigiType sample = 0; + auto const &bytes = record(); + size_t const nbytes = bytes.size(); - ProcType operator ()(Record record); + // Assemble bytes (big-endian order as written by ProcessorSample) + for (uint32_t i = 0; i < nbytes; ++i) { + sample <<= 8; + sample |= static_cast(bytes[i]); + } - private: - const double m_offset; - const double m_scaling; - }; + // Sign-extend: if high bit of the MSB is set, the value is negative + if (nbytes > 0 && nbytes < sizeof(DigiType)) { + uint32_t sign_bit = 1u << (nbytes * 8 - 1); + if (sample & sign_bit) + sample |= ~((int32_t{1} << (nbytes * 8)) - 1); + } + if constexpr (std::is_same_v) + return sample; + return ConvertSample(m_offset, m_scaling, sample); } -#include "impl/ProcessorSampleRecord.ipp" +} // namespace edfio diff --git a/include/edfio/processor/ProcessorTalRecord.hpp b/include/edfio/processor/ProcessorTalRecord.hpp index dda7682..9f27081 100644 --- a/include/edfio/processor/ProcessorTalRecord.hpp +++ b/include/edfio/processor/ProcessorTalRecord.hpp @@ -11,16 +11,64 @@ #include "../core/Annotation.hpp" +#include #include -namespace edfio -{ +namespace edfio { - struct ProcessorTalRecord - { - std::vector operator ()(std::vector record, long long datarecord); - }; +inline std::vector ProcessTalRecord(std::vector record, + int64_t datarecord) { + std::vector out; + // Boundaries + auto first = record.begin(); + auto last = record.end(); + + // TAL MUST start with '+' or '-' + if (*first != '+' && *first != '-') { + throw std::invalid_argument( + GetError(FileErrc::FileContainsInvalidAnnotations)); + } + + double start = 0; + double duration = 0; + bool onset = true; + for (auto it = first; it != last; it++) { + if (std::distance(first, it) > 0) { + // First field is for TAL onset + if (onset) { + if (*it == detail::DURATION_DIV || *it == detail::ANNOTATION_DIV) { + std::string tmp(first, it); + start = detail::ParseDouble( + tmp, GetError(FileErrc::FileContainsInvalidAnnotations)); + onset = false; + + first = it; + } + } else if (*it == detail::ANNOTATION_DIV) { + if (*first == detail::DURATION_DIV) { + std::string tmp(first + 1, it); + duration = detail::ParseDouble( + tmp, GetError(FileErrc::FileContainsInvalidAnnotations)); + first = it; + } else if (*first == detail::ANNOTATION_DIV) { + std::string tmp(first + 1, it); + + // Check if this TAL is in fact just a timestamp, we don't want this + if (!tmp.empty()) { + Annotation annot; + annot.m_start = start; + annot.m_duration = duration; + annot.m_annotation = tmp; + annot.m_datarecord = datarecord; + out.emplace_back(std::move(annot)); + } + first = it; + } + } + } + } + return out; } -#include "impl/ProcessorTalRecord.ipp" +} // namespace edfio diff --git a/include/edfio/processor/ProcessorTimeStamp.hpp b/include/edfio/processor/ProcessorTimeStamp.hpp index afcc63f..daa0f47 100644 --- a/include/edfio/processor/ProcessorTimeStamp.hpp +++ b/include/edfio/processor/ProcessorTimeStamp.hpp @@ -9,17 +9,40 @@ #pragma once -#include "../core/Record.hpp" +#include "../Errors.hpp" #include "../core/Annotation.hpp" +#include "../core/Record.hpp" +#include "ProcessorUtils.hpp" + +#include + +namespace edfio { + +inline Record ProcessTimeStamp(TimeStamp timestamp) { + std::string ts = detail::to_string_decimal(timestamp.m_start); + + if (ts.empty()) { + throw std::invalid_argument( + GetError(FileErrc::FileWriteInvalidAnnotations)); + } + + uint32_t plusSignal = 0; + if (timestamp.m_start >= 0) + plusSignal = 1; -namespace edfio -{ + Record record(plusSignal + ts.size() + 3); // 20 20 0 + auto it = record().begin(); - struct ProcessorTimeStamp - { - Record operator ()(TimeStamp timestamp); - }; + // timestamp + if (plusSignal) + *it++ = '+'; + std::move(ts.begin(), ts.end(), it); + it += ts.size(); + *it++ = 20; // 20 div + *it++ = 20; // 20 div + *it++ = 0; // 0 end + return record; } -#include "impl/ProcessorTimeStamp.ipp" +} // namespace edfio diff --git a/include/edfio/processor/ProcessorTimeStampRecord.hpp b/include/edfio/processor/ProcessorTimeStampRecord.hpp index c71434c..648450f 100644 --- a/include/edfio/processor/ProcessorTimeStampRecord.hpp +++ b/include/edfio/processor/ProcessorTimeStampRecord.hpp @@ -9,18 +9,49 @@ #pragma once -#include "../Defs.hpp" -#include "../core/Record.hpp" +#include "../Errors.hpp" #include "../core/Annotation.hpp" +#include "../core/Record.hpp" + +#include +#include +#include +#include + +namespace edfio { + +inline TimeStamp ProcessTimeStampRecord(Record record, + int64_t datarecord) { + TimeStamp timestamp; + timestamp.m_datarecord = datarecord; + auto &value = record(); -namespace edfio -{ + // TimeStamp MUST start with '+' or '-' + if (value.front() != '+' && value.front() != '-') { + throw std::invalid_argument( + GetError(FileErrc::FileContainsInvalidAnnotations)); + } - struct ProcessorTimeStampRecord - { - TimeStamp operator ()(Record record, long long datarecord); - }; + // Make sure it's a valid timestamp + static constexpr std::array comp = {detail::ANNOTATION_END, + detail::ANNOTATION_DIV}; + auto result = std::ranges::find_first_of(value, comp); + if (result == value.end()) { + throw std::invalid_argument( + GetError(FileErrc::FileContainsInvalidAnnotations)); + } else { + *result = 0; + double start{}; + auto [ptr, ec] = + std::from_chars(value.data(), value.data() + value.size(), start); + if (ec != std::errc{} || ptr == value.data()) { + throw std::invalid_argument( + GetError(FileErrc::FileContainsInvalidAnnotations)); + } + timestamp.m_start = start; + } + return timestamp; } -#include "impl/ProcessorTimeStampRecord.ipp" +} // namespace edfio diff --git a/include/edfio/processor/ProcessorUtils.hpp b/include/edfio/processor/ProcessorUtils.hpp new file mode 100644 index 0000000..66a28d0 --- /dev/null +++ b/include/edfio/processor/ProcessorUtils.hpp @@ -0,0 +1,188 @@ +// +// Copyright(c) 2017-present Iuri Dotta (dotta dot iuri at gmail dot com) +// +// This source code is licensed under the MIT license found in the +// LICENSE file in the root directory of this source tree. +// +// Official repository: https://github.com/idotta/edfio +// + +#pragma once + +#include "../Config.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace edfio { +template +[[nodiscard]] inline bool +CheckFormatErrors(const std::basic_string &str) { + if constexpr (Check == ProcessorErrorCheck::Permissive) { + return false; + } else { + for (auto c : str) { + if (!std::isprint(static_cast(c))) + return true; + } + return false; + } +} + +template +[[nodiscard]] inline bool CheckFormatErrors(std::span str) { + if constexpr (Check == ProcessorErrorCheck::Permissive) { + return false; + } else { + for (auto c : str) { + if (!std::isprint(static_cast(c))) + return true; + } + return false; + } +} + +namespace detail { + +inline constexpr char ADDITIONAL_SEPARATOR = '|'; +inline constexpr std::array MONTHS = { + "JAN", "FEB", "MAR", "APR", "MAY", "JUN", + "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"}; + +template +[[nodiscard]] inline bool +CheckFormatErrors(const std::basic_string &str) { + return edfio::CheckFormatErrors(str); +} + +template +[[nodiscard]] inline bool CheckFormatErrors(std::span str) { + return edfio::CheckFormatErrors(str); +} + +inline int32_t GetMonthFromString(std::string_view str) { + for (size_t idx = 0; idx < MONTHS.size(); idx++) { + if (str == MONTHS[idx]) { + return idx + 1; + } + } + return 0; +} + +inline std::string GetStringFromMonth(size_t idx) { + if (idx >= 1 && idx <= 12) + return std::string{MONTHS[idx - 1]}; + return "JAN"; +} + +inline std::string ReduceString(std::string_view value) { + // Trim leading spaces + auto start = value.find_first_not_of(' '); + if (start == std::string::npos) + return ""; + // Trim trailing spaces + auto end = value.find_last_not_of(' '); + // Collapse interior runs of spaces to single space + std::string result; + result.reserve(end - start + 1); + bool prev_space = false; + for (size_t i = start; i <= end; ++i) { + if (value[i] == ' ') { + if (!prev_space) { + result += ' '; + prev_space = true; + } + } else { + result += value[i]; + prev_space = false; + } + } + return result; +} + +inline std::string_view GetFormatName(DataFormat format) { + if (format == DataFormat::Edf) + return "EDF"; + if (format == DataFormat::EdfPlusC) + return "EDF+C"; + if (format == DataFormat::EdfPlusD) + return "EDF+D"; + if (format == DataFormat::Bdf) + return "BDF"; + if (format == DataFormat::BdfPlusC) + return "BDF+C"; + if (format == DataFormat::BdfPlusD) + return "BDF+D"; + return ""; +} + +inline int32_t ParseInt(std::string_view sv, const char *error_msg) { + while (!sv.empty() && sv.front() == ' ') + sv.remove_prefix(1); + while (!sv.empty() && sv.back() == ' ') + sv.remove_suffix(1); + int32_t value{}; + auto [ptr, ec] = std::from_chars(sv.data(), sv.data() + sv.size(), value); + if (ec != std::errc{}) + throw std::invalid_argument(error_msg); + return value; +} + +inline int64_t ParseLongLong(std::string_view sv, const char *error_msg) { + while (!sv.empty() && sv.front() == ' ') + sv.remove_prefix(1); + while (!sv.empty() && sv.back() == ' ') + sv.remove_suffix(1); + int64_t value{}; + auto [ptr, ec] = std::from_chars(sv.data(), sv.data() + sv.size(), value); + if (ec != std::errc{}) + throw std::invalid_argument(error_msg); + return value; +} + +inline double ParseDouble(std::string_view sv, const char *error_msg) { + while (!sv.empty() && sv.front() == ' ') + sv.remove_prefix(1); + while (!sv.empty() && sv.back() == ' ') + sv.remove_suffix(1); + // std::from_chars accepts '-' but not '+' by standard; strip leading '+' + if (!sv.empty() && sv.front() == '+') + sv.remove_prefix(1); + double value{}; + auto [ptr, ec] = std::from_chars(sv.data(), sv.data() + sv.size(), value); + if (ec != std::errc{}) + throw std::invalid_argument(error_msg); + return value; +} + +template inline std::string to_string_decimal(const T &t) { + // Use std::to_chars for locale-independent conversion (always uses '.') + std::array buf; + auto [ptr, ec] = std::to_chars(buf.data(), buf.data() + buf.size(), t); + if (ec != std::errc{}) + return "0"; + std::string str(buf.data(), ptr); + + // Trim trailing zeros after the decimal point + auto dot = str.find('.'); + if (dot != std::string::npos) { + auto last_nonzero = str.find_last_not_of('0'); + if (last_nonzero == dot) { + // All fractional digits are zero; remove the dot entirely + str.erase(dot); + } else { + // Remove trailing zeros only + str.erase(last_nonzero + 1); + } + } + return str; +} +} // namespace detail + +} // namespace edfio diff --git a/include/edfio/processor/detail/ProcessorUtils.hpp b/include/edfio/processor/detail/ProcessorUtils.hpp deleted file mode 100644 index 41039d9..0000000 --- a/include/edfio/processor/detail/ProcessorUtils.hpp +++ /dev/null @@ -1,142 +0,0 @@ -// -// Copyright(c) 2017-present Iuri Dotta (dotta dot iuri at gmail dot com) -// -// This source code is licensed under the MIT license found in the -// LICENSE file in the root directory of this source tree. -// -// Official repository: https://github.com/idotta/edfio -// - -#pragma once - -#include "../../Config.hpp" - -#include -#include -#include -#include - -namespace edfio -{ - - namespace impl - { - - template - static bool CheckFormatErrors(const typename std::enable_if>::type &str) - { - for (auto& c : str) - { - if (!std::isprint(c)) - { - return true; - } - } - return false; - } - - template - static bool CheckFormatErrors(const typename std::enable_if>::type &str) - { - return false; - } - - template - static bool CheckFormatErrors(const typename std::enable_if>::type &str) - { - for (auto& c : str) - { - if (!std::isprint(c)) - { - return true; - } - } - return false; - } - - template - static bool CheckFormatErrors(const typename std::enable_if>::type &str) - { - return false; - } - - } - - namespace detail - { - - static const char ADDITIONAL_SEPARATOR = '|'; - - template - static bool CheckFormatErrors(const std::basic_string &str) - { - return impl::CheckFormatErrors(str); - } - - template - static bool CheckFormatErrors(const std::vector &str) - { - return impl::CheckFormatErrors(str); - } - - static int GetMonthFromString(const std::string &str) - { - static const std::vector months = { "JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC" }; - for (size_t idx = 0; idx < months.size(); idx++) - { - if (str == months[idx]) - { - return idx + 1; - } - } - return 0; - } - - static std::string GetStringFromMonth(size_t idx) - { - idx--; - static const std::vector months = { "JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC" }; - if (idx >= 0 && idx < months.size()) - return months[idx]; - return "JAN"; - } - - static std::string ReduceString(const std::string &value) - { - return std::regex_replace(value, std::regex("^ +| +$|( ) +"), "$1"); - } - - static std::string GetFormatName(DataFormat format) - { - if (format == DataFormat::Edf) - return "EDF"; - if (format == DataFormat::EdfPlusC) - return "EDF+C"; - if (format == DataFormat::EdfPlusD) - return "EDF+D"; - if (format == DataFormat::Bdf) - return "BDF"; - if (format == DataFormat::BdfPlusC) - return "BDF+C"; - if (format == DataFormat::BdfPlusD) - return "BDF+D"; - return ""; - } - - template - std::string to_string_decimal(const T& t) - { - std::string str{ std::to_string(t) }; - std::replace(str.begin(), str.end(), ',', '.'); - int offset{ 1 }; - if (str.find_last_not_of('0') == str.find('.')) - { - offset = 0; - } - str.erase(str.find_last_not_of('0') + offset, std::string::npos); - return str; - } - - } - -} diff --git a/include/edfio/processor/impl/ProcessorAnnotation.ipp b/include/edfio/processor/impl/ProcessorAnnotation.ipp deleted file mode 100644 index 182d714..0000000 --- a/include/edfio/processor/impl/ProcessorAnnotation.ipp +++ /dev/null @@ -1,69 +0,0 @@ -// -// Copyright(c) 2017-present Iuri Dotta (dotta dot iuri at gmail dot com) -// -// This source code is licensed under the MIT license found in the -// LICENSE file in the root directory of this source tree. -// -// Official repository: https://github.com/idotta/edfio -// - -#pragma once - -#include "../../Utils.hpp" -#include "../../core/Record.hpp" -#include "../../core/Annotation.hpp" -#include "../detail/ProcessorUtils.hpp" - -namespace edfio -{ - - inline Record ProcessorAnnotation::operator()(Annotation annotation) - { - if (annotation.m_annotation.empty()) - { - throw std::invalid_argument(detail::GetError(FileErrc::FileWriteInvalidAnnotations)); - } - - std::string timestamp = (annotation.m_start >= 0 ? "+" : "") + detail::to_string_decimal(annotation.m_start); - std::string duration; - if (annotation.m_duration > 0) - duration = detail::to_string_decimal(annotation.m_duration); - - size_t size = timestamp.size(); // timestamp - if (!duration.empty()) - { - size++; // 21 div - size += duration.size(); // duration - } - - size++; // 20 div - size += annotation.m_annotation.size(); // annotation - size += 2; // 20 div and 0 - - Record record(size); - auto it = record().begin(); - - // timestamp - std::move(timestamp.begin(), timestamp.end(), it); - it += timestamp.size(); - - if (!duration.empty()) - { - *it++ = 21; // 21 div - // duration - std::move(duration.begin(), duration.end(), it); - it += duration.size(); - } - - *it++ = 20; // 20 div - // annotation - std::move(annotation.m_annotation.begin(), annotation.m_annotation.end(), it); - it += annotation.m_annotation.size(); - - *it++ = 20; // 20 div - *it++ = 0; // 0 end - - return record; - } - -} diff --git a/include/edfio/processor/impl/ProcessorHeaderExam.ipp b/include/edfio/processor/impl/ProcessorHeaderExam.ipp deleted file mode 100644 index 278db7b..0000000 --- a/include/edfio/processor/impl/ProcessorHeaderExam.ipp +++ /dev/null @@ -1,48 +0,0 @@ -// -// Copyright(c) 2017-present Iuri Dotta (dotta dot iuri at gmail dot com) -// -// This source code is licensed under the MIT license found in the -// LICENSE file in the root directory of this source tree. -// -// Official repository: https://github.com/idotta/edfio -// - -#pragma once - -#include "../../Utils.hpp" -#include "../../core/DataFormat.hpp" - -namespace edfio -{ - - inline HeaderExam edfio::ProcessorHeaderExam::operator()(HeaderGeneral header, std::vector signals) - { - // Record size - size_t recordsize = 0; - for (auto &signal : signals) - { - recordsize += signal.m_samplesInDataRecord; - } - - if (IsBdf(header.m_version)) - { - recordsize *= 3; - if (recordsize > 0xF00000) - { - throw std::invalid_argument(detail::GetError(FileErrc::FileContainsFormatErrors)); - } - } - else - { - recordsize *= 2; - if (recordsize > 0xA00000) - { - throw std::invalid_argument(detail::GetError(FileErrc::FileContainsFormatErrors)); - } - } - header.m_detail.m_recordSize = recordsize; - - return std::move(HeaderExam{ std::move(header), std::move(signals) }); - } - -} diff --git a/include/edfio/processor/impl/ProcessorHeaderGeneral.ipp b/include/edfio/processor/impl/ProcessorHeaderGeneral.ipp deleted file mode 100644 index 18c1d01..0000000 --- a/include/edfio/processor/impl/ProcessorHeaderGeneral.ipp +++ /dev/null @@ -1,164 +0,0 @@ -// -// Copyright(c) 2017-present Iuri Dotta (dotta dot iuri at gmail dot com) -// -// This source code is licensed under the MIT license found in the -// LICENSE file in the root directory of this source tree. -// -// Official repository: https://github.com/idotta/edfio -// - -#pragma once - -#include "../../Defs.hpp" -#include "../../core/DataFormat.hpp" -#include "../detail/ProcessorUtils.hpp" - -#include -#include - -namespace edfio -{ - - inline HeaderGeneralFields ProcessorHeaderGeneral::operator()(HeaderGeneral in) - { - HeaderGeneralFields out; - - // Version - { - if (IsEdf(in.m_version)) - { - out.m_version("0 "); - } - else if (IsBdf(in.m_version)) - { - std::string value = "BIOSEMI"; - value.insert(value.begin(), -1); - out.m_version(value); - } - } - // Patient Name - { - out.m_patient(in.m_patient); - } - // Recording - { - out.m_recording(in.m_recording); - } - // Start Date - { - int day = std::get<0>(in.m_startDate); - int month = std::get<1>(in.m_startDate); - int year = std::get<2>(in.m_startDate); - year -= year > 1999 ? 2000 : 1900; - std::ostringstream oss; - oss << std::setw(2) << std::setfill('0') << day << "."; - oss << std::setw(2) << std::setfill('0') << month << "."; - oss << std::setw(2) << std::setfill('0') << year; - out.m_startDate(oss.str()); - } - // Start Time - { - int hour = std::get<0>(in.m_startTime); - int minute = std::get<1>(in.m_startTime); - int second = std::get<2>(in.m_startTime); - std::ostringstream oss; - oss << std::setw(2) << std::setfill('0') << hour << "."; - oss << std::setw(2) << std::setfill('0') << minute << "."; - oss << std::setw(2) << std::setfill('0') << second; - out.m_startTime(oss.str()); - } - // Header Size - { - out.m_headerSize(std::to_string(in.m_headerSize)); - } - // Reserved - { - if (!in.m_reserved.empty()) - { - out.m_reserved(in.m_reserved); - } - else if (IsPlus(in.m_version)) - { - out.m_reserved(detail::GetFormatName(in.m_version)); - } - } - // Datarecords in File - { - out.m_datarecordsFile(std::to_string(in.m_datarecordsFile)); - } - // Datarecord Duration - { - out.m_datarecordDuration(detail::to_string_decimal(in.m_datarecordDuration)); - } - // Number of signals - { - out.m_totalSignals(std::to_string(in.m_totalSignals)); - } - // Plus Fields - if (IsPlus(in.m_version)) - { - // Patient Name - { - std::vector fields; - // Code - fields.push_back(in.m_detail.m_patientCode.empty() ? "X" : in.m_detail.m_patientCode); - // Sex - fields.push_back(in.m_detail.m_gender.empty() ? "X" : in.m_detail.m_gender); - // Birthdate in dd-MMM-yyyy format using the English 3-character abbreviations of the month in capitals. 02-AUG-1951 is OK, while 2-AUG-1951 is not. - fields.push_back(in.m_detail.m_birthdate.empty() ? "X" : in.m_detail.m_birthdate); - // The patients name. - fields.push_back(in.m_detail.m_patientName.empty() ? "X" : in.m_detail.m_patientName); - // Additional information. - std::string info; - std::istringstream f(in.m_detail.m_patientAdditional); - while (std::getline(f, info, detail::ADDITIONAL_SEPARATOR)) - { - fields.push_back(info); - } - std::string patient = ""; - for (auto& field : fields) - { - std::replace(field.begin(), field.end(), ' ', '_'); // replace all ' ' to '_' - patient += field + " "; - } - patient.pop_back(); // remove last " " - out.m_patient(patient); - } - // Recording - { - std::vector fields; - // The text 'Startdate' - fields.push_back("Startdate"); - // The startdate itself in dd-MMM-yyyy format using the English 3-character abbreviations of the month in capitals: dd-MMM-yyyy (MMM = 'JAN' | 'FEV' | ...) - std::ostringstream oss; - int day = std::get<0>(in.m_startDate); - int month = std::get<1>(in.m_startDate); - int year = std::get<2>(in.m_startDate); - oss << std::setw(2) << std::setfill('0') << (day ? day : 1) << "-" << detail::GetStringFromMonth(month) << "-" << (year ? year : 1984); - fields.push_back(oss.str()); - // The hospital administration code of the investigation, i.e. EEG number or PSG number. - fields.push_back(in.m_detail.m_admincode.empty() ? "X" : in.m_detail.m_admincode); - // A code specifying the responsible investigator or technician. - fields.push_back(in.m_detail.m_technician.empty() ? "X" : in.m_detail.m_technician); - // A code specifying the used equipment. - fields.push_back(in.m_detail.m_equipment.empty() ? "X" : in.m_detail.m_equipment); - // Additional information. - std::string info; - std::istringstream f(in.m_detail.m_recordingAdditional); - while (std::getline(f, info, detail::ADDITIONAL_SEPARATOR)) - { - fields.push_back(info); - } - std::string recording = ""; - for (auto& field : fields) - { - std::replace(field.begin(), field.end(), ' ', '_'); // replace all '_' to ' ' - recording += field + " "; - } - recording.pop_back(); // remove last " " - out.m_recording(recording); - } - } - return std::move(out); - } -} diff --git a/include/edfio/processor/impl/ProcessorHeaderGeneralFields.ipp b/include/edfio/processor/impl/ProcessorHeaderGeneralFields.ipp deleted file mode 100644 index d64f865..0000000 --- a/include/edfio/processor/impl/ProcessorHeaderGeneralFields.ipp +++ /dev/null @@ -1,361 +0,0 @@ -// -// Copyright(c) 2017-present Iuri Dotta (dotta dot iuri at gmail dot com) -// -// This source code is licensed under the MIT license found in the -// LICENSE file in the root directory of this source tree. -// -// Official repository: https://github.com/idotta/edfio -// - -#pragma once - -#include "../../Utils.hpp" -#include "../../core/DataFormat.hpp" -#include "../detail/ProcessorUtils.hpp" - -#include -#include - -namespace edfio -{ - - inline HeaderGeneral ProcessorHeaderGeneralFields::operator()(HeaderGeneralFields in) - { - HeaderGeneral out; - - if (/*detail::CheckFormatErrors(in.m_version()) - ||*/ detail::CheckFormatErrors(in.m_patient()) - || detail::CheckFormatErrors(in.m_recording()) - || detail::CheckFormatErrors(in.m_startDate()) - || detail::CheckFormatErrors(in.m_startTime()) - || detail::CheckFormatErrors(in.m_headerSize()) - || detail::CheckFormatErrors(in.m_reserved()) - || detail::CheckFormatErrors(in.m_datarecordsFile()) - || detail::CheckFormatErrors(in.m_datarecordDuration()) - || detail::CheckFormatErrors(in.m_totalSignals())) - { - throw std::invalid_argument(detail::GetError(FileErrc::FileContainsFormatErrors)); - } - - - // Version - { - auto &version = in.m_version(); - if (version.front() == -1) // BDF-file - { - if (version.substr(1) != "BIOSEMI") - { - throw std::invalid_argument(detail::GetError(FileErrc::FileContainsFormatErrors)); - } - out.m_version = DataFormat::Bdf; - } - else // EDF-file - { - if (version != "0 ") - { - throw std::invalid_argument(detail::GetError(FileErrc::FileContainsFormatErrors)); - } - out.m_version = DataFormat::Edf; - } - } - // Patient Name - { - out.m_patient = in.m_patient(); - } - // Recording - { - out.m_recording = in.m_recording(); - } - // Start Date - { - auto& startdate = in.m_startDate(); - if ((startdate[2] != '.') || (startdate[5] != '.') - || !std::isdigit(startdate[0]) || !std::isdigit(startdate[1]) - || !std::isdigit(startdate[3]) || !std::isdigit(startdate[4]) - || !std::isdigit(startdate[6]) || !std::isdigit(startdate[7])) - { - throw std::invalid_argument(detail::GetError(FileErrc::FileContainsFormatErrors)); - } - try - { - int day = std::stoi(startdate); - int month = std::stoi(startdate.substr(3)); - int year = std::stoi(startdate.substr(6)); - - if (day < 1 || day > 31 || month < 1 || month > 12) - { - throw std::invalid_argument(detail::GetError(FileErrc::FileContainsFormatErrors)); - } - year += year > 84 ? 1900 : 2000; - - out.m_startDate = std::make_tuple(day, month, year); - } - catch (...) - { - throw std::invalid_argument(detail::GetError(FileErrc::FileContainsFormatErrors)); - } - } - // Start Time - { - auto& starttime = in.m_startTime(); - if ((starttime[2] != '.') || (starttime[5] != '.') - || !std::isdigit(starttime[0]) || !std::isdigit(starttime[1]) - || !std::isdigit(starttime[3]) || !std::isdigit(starttime[4]) - || !std::isdigit(starttime[6]) || !std::isdigit(starttime[7])) - { - throw std::invalid_argument(detail::GetError(FileErrc::FileContainsFormatErrors)); - } - try - { - int hour = std::stoi(starttime); - int minute = std::stoi(starttime.substr(3)); - int second = std::stoi(starttime.substr(6)); - - if (hour > 23 || minute > 59 || second > 59) - { - throw std::invalid_argument(detail::GetError(FileErrc::FileContainsFormatErrors)); - } - out.m_startTime = std::make_tuple(hour, minute, second); - } - catch (...) - { - throw std::invalid_argument(detail::GetError(FileErrc::FileContainsFormatErrors)); - } - } - // Header Size - { - try - { - out.m_headerSize = std::stoi(in.m_headerSize()); - } - catch (...) - { - throw std::invalid_argument(detail::GetError(FileErrc::FileContainsFormatErrors)); - } - } - // Reserved - { - auto &reserved = in.m_reserved(); - if (IsEdf(out.m_version)) - { - if (reserved.find("EDF+C") != std::string::npos) - { - out.m_version = DataFormat::EdfPlusC; - } - else if (reserved.find("EDF+D") != std::string::npos) - { - out.m_version = DataFormat::EdfPlusD; - } - } - else if (IsBdf(out.m_version)) - { - if (reserved.find("BDF+C") != std::string::npos) - { - out.m_version = DataFormat::BdfPlusC; - } - else if (reserved.find("BDF+D") != std::string::npos) - { - out.m_version = DataFormat::BdfPlusD; - } - } - } - // Datarecords in File - { - try - { - out.m_datarecordsFile = std::stoll(in.m_datarecordsFile()); - } - catch (...) - { - throw std::invalid_argument(detail::GetError(FileErrc::FileContainsFormatErrors)); - } - if (out.m_datarecordsFile < 0) - { - throw std::invalid_argument(detail::GetError(FileErrc::FileContainsFormatErrors)); - } - } - // Datarecord Duration - { - double duration = -1; - try - { - duration = std::stod(in.m_datarecordDuration()); - out.m_datarecordDuration = duration; - } - catch (...) - { - throw std::invalid_argument(detail::GetError(FileErrc::FileContainsFormatErrors)); - } - if (duration < 0) - { - throw std::invalid_argument(detail::GetError(FileErrc::FileContainsFormatErrors)); - } - out.m_detail.m_fileDuration = out.m_datarecordDuration * out.m_datarecordsFile; - } - // Number of signals - { - int signals = 0; - try - { - signals = std::stoi(in.m_totalSignals()); - } - catch (...) - { - throw std::invalid_argument(detail::GetError(FileErrc::FileContainsFormatErrors)); - } - if (signals <= 0 || (signals * 256 + 256) != out.m_headerSize) - { - throw std::invalid_argument(detail::GetError(FileErrc::FileContainsFormatErrors)); - } - out.m_totalSignals = signals; - } - // Plus Fields - if (IsPlus(out.m_version)) - { - // Patient Name - { - auto &details = out.m_detail; - std::vector fields; - std::string field; - std::istringstream f(out.m_patient); - while (std::getline(f, field, ' ')) - { - fields.push_back(field); - } - if (fields.size() < 4) - { - throw std::invalid_argument(detail::GetError(FileErrc::FileContainsFormatErrors)); - } - - details.m_patientAdditional.clear(); - - for (size_t i = 0; i < fields.size(); i++) - { - auto& str = fields[i]; - std::replace(str.begin(), str.end(), '_', ' '); // replace all '_' to ' ' - switch (i) - { - case 0: // The code by which the patient is known in the hospital administration. - details.m_patientCode = str; - break; - case 1: // Sex - if (str == "F" || str == "M" || str == "X") - { - details.m_gender = str; - } - else - { - throw std::invalid_argument(detail::GetError(FileErrc::FileContainsFormatErrors)); - } - break; - case 2: // Birthdate in dd-MMM-yyyy format using the English 3-character abbreviations of the month in capitals. 02-AUG-1951 is OK, while 2-AUG-1951 is not. - details.m_birthdate = str; - break; - case 3: // The patients name. - details.m_patientName = str; - break; - default: // Additional information. - if (!details.m_patientAdditional.empty()) - { - details.m_patientAdditional += detail::ADDITIONAL_SEPARATOR; - } - details.m_patientAdditional.append(str); - break; - } - } - } - // Recording - { - auto &details = out.m_detail; - std::vector fields; - std::string field; - std::istringstream f(out.m_recording); - while (std::getline(f, field, ' ')) - { - fields.push_back(field); - } - - if (fields.size() < 5) - { - throw std::invalid_argument(detail::GetError(FileErrc::FileContainsFormatErrors)); - } - - details.m_recordingAdditional.clear(); - - for (size_t i = 0; i < fields.size(); i++) - { - auto& str = fields[i]; - std::replace(str.begin(), str.end(), '_', ' '); // replace all '_' to ' ' - if (str != "X") - { - switch (i) - { - case 0: // The text 'Startdate'. - if (str != "Startdate") - { - throw std::invalid_argument(detail::GetError(FileErrc::FileContainsFormatErrors)); - } - break; - case 1: // The startdate itself in dd-MMM-yyyy format using the English 3-character abbreviations of the month in capitals: dd-MMM-yyyy (MMM = 'JAN' | 'FEV' | ...) - if (str.size() == 11 && str[2] == '-' && str[6] == '-') - { - try - { - int day = std::stoi(str.substr(0, 2)); - int year = std::stoi(str.substr(7, 4)); - int month = detail::GetMonthFromString(str.substr(3, 3)); - if (month == 0) - { - throw std::invalid_argument("Invalid Month"); - } - out.m_startDate = std::make_tuple(day, month, year); - } - catch (...) - { - throw std::invalid_argument(detail::GetError(FileErrc::FileContainsFormatErrors)); - } - } - else - { - throw std::invalid_argument(detail::GetError(FileErrc::FileContainsFormatErrors)); - } - break; - case 2: // The hospital administration code of the investigation, i.e. EEG number or PSG number. - details.m_admincode = str; - break; - case 3: // A code specifying the responsible investigator or technician. - details.m_technician = str; - break; - case 4: // A code specifying the used equipment. - details.m_equipment = str; - break; - default: // Additional information. - if (!details.m_recordingAdditional.empty()) - { - details.m_recordingAdditional += detail::ADDITIONAL_SEPARATOR; - } - details.m_recordingAdditional.append(str); - break; - } - } - } - } - } - - out.m_patient = detail::ReduceString(out.m_patient); - out.m_recording = detail::ReduceString(out.m_recording); - out.m_reserved = detail::ReduceString(out.m_reserved); - out.m_detail.m_patientCode = detail::ReduceString(out.m_detail.m_patientCode); - out.m_detail.m_gender = detail::ReduceString(out.m_detail.m_gender); - out.m_detail.m_birthdate = detail::ReduceString(out.m_detail.m_birthdate); - out.m_detail.m_patientName = detail::ReduceString(out.m_detail.m_patientName); - out.m_detail.m_patientAdditional = detail::ReduceString(out.m_detail.m_patientAdditional); - out.m_detail.m_admincode = detail::ReduceString(out.m_detail.m_admincode); - out.m_detail.m_technician = detail::ReduceString(out.m_detail.m_technician); - out.m_detail.m_equipment = detail::ReduceString(out.m_detail.m_equipment); - out.m_detail.m_recordingAdditional = detail::ReduceString(out.m_detail.m_recordingAdditional); - - return std::move(out); - } - -} diff --git a/include/edfio/processor/impl/ProcessorHeaderSignal.ipp b/include/edfio/processor/impl/ProcessorHeaderSignal.ipp deleted file mode 100644 index ef70f5a..0000000 --- a/include/edfio/processor/impl/ProcessorHeaderSignal.ipp +++ /dev/null @@ -1,101 +0,0 @@ -// -// Copyright(c) 2017-present Iuri Dotta (dotta dot iuri at gmail dot com) -// -// This source code is licensed under the MIT license found in the -// LICENSE file in the root directory of this source tree. -// -// Official repository: https://github.com/idotta/edfio -// - -#pragma once - -#include "../../Utils.hpp" -#include "../../core/DataFormat.hpp" -#include "../detail/ProcessorUtils.hpp" - -#include -#include - -namespace edfio -{ - - inline std::vector ProcessorHeaderSignal::operator()(std::vector in) - { - std::vector out(in.size()); - auto &signals = in; - - // Labels - { - for (size_t idx = 0; idx < signals.size(); idx++) - { - out[idx].m_label(signals[idx].m_label); - } - } - // Transducers Types - { - for (size_t idx = 0; idx < signals.size(); idx++) - { - out[idx].m_transducer(signals[idx].m_transducer); - } - } - // Physical Dimensions - { - for (size_t idx = 0; idx < signals.size(); idx++) - { - out[idx].m_physDimension(signals[idx].m_physDimension); - } - } - // Physical Minima - { - for (size_t idx = 0; idx < signals.size(); idx++) - { - out[idx].m_physicalMin(detail::to_string_decimal(signals[idx].m_physicalMin)); - } - } - // Physical Maxima - { - for (size_t idx = 0; idx < signals.size(); idx++) - { - out[idx].m_physicalMax(detail::to_string_decimal(signals[idx].m_physicalMax)); - } - } - // Digital Minima - { - for (size_t idx = 0; idx < signals.size(); idx++) - { - out[idx].m_digitalMin(std::to_string(signals[idx].m_digitalMin)); - } - } - // Digital Maxima - { - for (size_t idx = 0; idx < signals.size(); idx++) - { - out[idx].m_digitalMax(std::to_string(signals[idx].m_digitalMax)); - } - } - // Prefilter - { - for (size_t idx = 0; idx < signals.size(); idx++) - { - out[idx].m_prefilter(signals[idx].m_prefilter); - } - } - // Samples in each datarecord - { - for (size_t idx = 0; idx < signals.size(); idx++) - { - out[idx].m_samplesInDataRecord(std::to_string(signals[idx].m_samplesInDataRecord)); - } - } - // Reserved - { - for (size_t idx = 0; idx < signals.size(); idx++) - { - out[idx].m_reserved(signals[idx].m_reserved); - } - } - - return std::move(out); - } - -} diff --git a/include/edfio/processor/impl/ProcessorHeaderSignalFields.ipp b/include/edfio/processor/impl/ProcessorHeaderSignalFields.ipp deleted file mode 100644 index 4aabdab..0000000 --- a/include/edfio/processor/impl/ProcessorHeaderSignalFields.ipp +++ /dev/null @@ -1,329 +0,0 @@ -// -// Copyright(c) 2017-present Iuri Dotta (dotta dot iuri at gmail dot com) -// -// This source code is licensed under the MIT license found in the -// LICENSE file in the root directory of this source tree. -// -// Official repository: https://github.com/idotta/edfio -// - -#pragma once - -#include "../../Utils.hpp" -#include "../../core/DataFormat.hpp" -#include "../detail/ProcessorUtils.hpp" - -namespace edfio -{ - - inline std::vector ProcessorHeaderSignalFields::operator()(std::vector in) - { - std::vector signals(in.size()); - - for (auto& sigFields : in) - { - if (detail::CheckFormatErrors(sigFields.m_label()) - || detail::CheckFormatErrors(sigFields.m_transducer()) - || detail::CheckFormatErrors(sigFields.m_physDimension()) - || detail::CheckFormatErrors(sigFields.m_physicalMin()) - || detail::CheckFormatErrors(sigFields.m_physicalMax()) - || detail::CheckFormatErrors(sigFields.m_digitalMin()) - || detail::CheckFormatErrors(sigFields.m_digitalMax()) - || detail::CheckFormatErrors(sigFields.m_prefilter()) - || detail::CheckFormatErrors(sigFields.m_samplesInDataRecord()) - || detail::CheckFormatErrors(sigFields.m_reserved())) - { - throw std::invalid_argument(detail::GetError(FileErrc::FileContainsFormatErrors)); - } - - } - - // Labels - { - size_t totalAnnotationChannels = 0; - for (size_t idx = 0; idx < signals.size(); idx++) - { - auto &signal = signals[idx]; - auto& label = in[idx].m_label(); - if (IsPlus(m_version)) - { - if (label.find("Annotation") != std::string::npos) - { - totalAnnotationChannels++; - signal.m_detail.m_isAnnotation = true; - } - else - { - signal.m_detail.m_isAnnotation = false; - } - } - else - { - signal.m_detail.m_isAnnotation = false; - } - signal.m_label = label; - } - if (IsPlus(m_version) && totalAnnotationChannels == 0) - { - throw std::invalid_argument(detail::GetError(FileErrc::FileContainsFormatErrors)); - } - // TODO: check if this is true - /*if (m_datarecordDuration < 1) - { - if (signals.size() != totalAnnotationChannels || !IsPlus(m_version)) - { - throw std::invalid_argument(detail::GetError(FileErrc::FileContainsFormatErrors)); - } - }*/ - } - // Transducers Types - { - for (size_t idx = 0; idx < signals.size(); idx++) - { - auto &signal = signals[idx]; - auto& transducer = in[idx].m_transducer(); - - signal.m_transducer = transducer; - - if (signal.m_detail.m_isAnnotation) - { - if (transducer.find_first_not_of(' ') != std::string::npos) - { - throw std::invalid_argument(detail::GetError(FileErrc::FileContainsFormatErrors)); - } - } - } - } - // Physical Dimensions - { - for (size_t idx = 0; idx < signals.size(); idx++) - { - auto &signal = signals[idx]; - auto& physDimension = in[idx].m_physDimension(); - - signal.m_physDimension = physDimension; - } - } - // Physical Minima - { - for (size_t idx = 0; idx < signals.size(); idx++) - { - auto &signal = signals[idx]; - auto& physMin = in[idx].m_physicalMin(); - - try - { - signal.m_physicalMin = std::stod(physMin); - } - catch (...) - { - throw std::invalid_argument(detail::GetError(FileErrc::FileContainsFormatErrors)); - } - } - } - // Physical Maxima - { - for (size_t idx = 0; idx < signals.size(); idx++) - { - auto &signal = signals[idx]; - auto& physMax = in[idx].m_physicalMax(); - - try - { - signal.m_physicalMax = std::stod(physMax); - } - catch (...) - { - throw std::invalid_argument(detail::GetError(FileErrc::FileContainsFormatErrors)); - } - } - } - // Digital Minima - { - for (size_t idx = 0; idx < signals.size(); idx++) - { - auto &signal = signals[idx]; - auto& digMin = in[idx].m_digitalMin(); - - int n = 0; - try - { - n = std::stoi(digMin); - } - catch (...) - { - throw std::invalid_argument(detail::GetError(FileErrc::FileContainsFormatErrors)); - } - - if (signal.m_detail.m_isAnnotation) - { - if (IsEdf(m_version) && IsPlus(m_version)) - { - if (n != -32768) - { - throw std::invalid_argument(detail::GetError(FileErrc::FileContainsFormatErrors)); - } - } - else if (IsBdf(m_version) && IsPlus(m_version)) - { - if (n != -8388608) - { - throw std::invalid_argument(detail::GetError(FileErrc::FileContainsFormatErrors)); - } - } - } - else if (IsEdf(m_version)) - { - if ((n > 32767) || (n < -32768)) - { - throw std::invalid_argument(detail::GetError(FileErrc::FileContainsFormatErrors)); - } - } - else if (IsBdf(m_version)) - { - if ((n > 8388607) || (n < -8388608)) - { - throw std::invalid_argument(detail::GetError(FileErrc::FileContainsFormatErrors)); - } - } - signal.m_digitalMin = n; - } - } - // Digital Maxima - { - for (size_t idx = 0; idx < signals.size(); idx++) - { - auto &signal = signals[idx]; - auto& digMax = in[idx].m_digitalMax(); - - int n = 0; - try - { - n = std::stoi(digMax); - } - catch (...) - { - throw std::invalid_argument(detail::GetError(FileErrc::FileContainsFormatErrors)); - } - - if (signal.m_detail.m_isAnnotation) - { - if (IsEdf(m_version) && IsPlus(m_version)) - { - if (n != 32767) - { - throw std::invalid_argument(detail::GetError(FileErrc::FileContainsFormatErrors)); - } - } - else if (IsBdf(m_version) && IsPlus(m_version)) - { - if (n != 8388607) - { - throw std::invalid_argument(detail::GetError(FileErrc::FileContainsFormatErrors)); - } - } - } - else if (IsEdf(m_version)) - { - if ((n > 32767) || (n < -32768)) - { - throw std::invalid_argument(detail::GetError(FileErrc::FileContainsFormatErrors)); - } - } - else if (IsBdf(m_version)) - { - if ((n > 8388607) || (n < -8388608)) - { - throw std::invalid_argument(detail::GetError(FileErrc::FileContainsFormatErrors)); - } - } - signal.m_digitalMax = n; - if (signal.m_digitalMax < (signal.m_digitalMin + 1)) - { - throw std::invalid_argument(detail::GetError(FileErrc::FileContainsFormatErrors)); - } - } - } - // Prefilter - { - for (size_t idx = 0; idx < signals.size(); idx++) - { - auto &signal = signals[idx]; - auto& prefilter = in[idx].m_prefilter(); - - signal.m_prefilter = prefilter; - - if (signal.m_detail.m_isAnnotation) - { - if (prefilter.find_first_not_of(' ') != std::string::npos) - { - throw std::invalid_argument(detail::GetError(FileErrc::FileContainsFormatErrors)); - } - } - } - } - // Samples in each datarecord - { - for (size_t idx = 0; idx < signals.size(); idx++) - { - auto &signal = signals[idx]; - auto& nrSamples = in[idx].m_samplesInDataRecord(); - - int n = 0; - try - { - n = std::stoi(nrSamples); - } - catch (...) - { - throw std::invalid_argument(detail::GetError(FileErrc::FileContainsFormatErrors)); - } - - if (n < 1) - { - throw std::invalid_argument(detail::GetError(FileErrc::FileContainsFormatErrors)); - } - signal.m_samplesInDataRecord = n; - } - } - // Reserved - { - for (size_t idx = 0; idx < signals.size(); idx++) - { - auto &signal = signals[idx]; - auto& reserved = in[idx].m_reserved(); - signal.m_reserved = reserved; - } - } - // Details - { - size_t n = 0; - for (size_t idx = 0; idx < signals.size(); idx++) - { - auto &signal = signals[idx]; - - signal.m_detail.m_signalOffset = n; - if (IsBdf(m_version)) - n += signal.m_samplesInDataRecord * 3; - else if (IsEdf(m_version)) - n += signal.m_samplesInDataRecord * 2; - - signal.m_detail.m_scaling = (signal.m_physicalMax - signal.m_physicalMin) / (signal.m_digitalMax - signal.m_digitalMin); - signal.m_detail.m_offset = signal.m_physicalMin - signal.m_detail.m_scaling * signal.m_digitalMin; - } - } - - - for (auto &signal : signals) - { - signal.m_label = detail::ReduceString(signal.m_label); - signal.m_transducer = detail::ReduceString(signal.m_transducer); - signal.m_physDimension = detail::ReduceString(signal.m_physDimension); - signal.m_prefilter = detail::ReduceString(signal.m_prefilter); - signal.m_reserved = detail::ReduceString(signal.m_reserved); - } - - return std::move(signals); - } - -} diff --git a/include/edfio/processor/impl/ProcessorSample.ipp b/include/edfio/processor/impl/ProcessorSample.ipp deleted file mode 100644 index 07a9417..0000000 --- a/include/edfio/processor/impl/ProcessorSample.ipp +++ /dev/null @@ -1,37 +0,0 @@ -// -// Copyright(c) 2017-present Iuri Dotta (dotta dot iuri at gmail dot com) -// -// This source code is licensed under the MIT license found in the -// LICENSE file in the root directory of this source tree. -// -// Official repository: https://github.com/idotta/edfio -// - -#pragma once - -namespace edfio -{ - - template - inline Record ProcessorSample::operator()(ProcType sample) - { - DigiType value = 0; - if (std::is_same::value) - value = static_cast(sample); - else - value = impl::ConvertSample(m_offset, m_scaling, sample); - - Record record(m_sampleSize); - auto it = record().begin(); - - for (int count = m_sampleSize; count > 0; count--) - { - unsigned char tmp = (value >> (count - 1) * 8); - *it++ = tmp; - } - - return std::move(record); - } - -} - diff --git a/include/edfio/processor/impl/ProcessorSampleRecord.ipp b/include/edfio/processor/impl/ProcessorSampleRecord.ipp deleted file mode 100644 index e1a9a31..0000000 --- a/include/edfio/processor/impl/ProcessorSampleRecord.ipp +++ /dev/null @@ -1,35 +0,0 @@ -// -// Copyright(c) 2017-present Iuri Dotta (dotta dot iuri at gmail dot com) -// -// This source code is licensed under the MIT license found in the -// LICENSE file in the root directory of this source tree. -// -// Official repository: https://github.com/idotta/edfio -// - -#pragma once - -namespace edfio -{ - - template - inline typename ProcessorSampleRecord::ProcType ProcessorSampleRecord::operator()(Record record) - { - DigiType sample = 0; - size_t idx = 0; - for (unsigned char r : record()) - { - if (r < 0 && idx++) - sample = -1; - sample <<= 8; - sample |= r; - idx++; - } - - if (std::is_same::value) - return sample; - return impl::ConvertSample(m_offset, m_scaling, sample); - } - -} - diff --git a/include/edfio/processor/impl/ProcessorTalRecord.ipp b/include/edfio/processor/impl/ProcessorTalRecord.ipp deleted file mode 100644 index 6690461..0000000 --- a/include/edfio/processor/impl/ProcessorTalRecord.ipp +++ /dev/null @@ -1,99 +0,0 @@ -// -// Copyright(c) 2017-present Iuri Dotta (dotta dot iuri at gmail dot com) -// -// This source code is licensed under the MIT license found in the -// LICENSE file in the root directory of this source tree. -// -// Official repository: https://github.com/idotta/edfio -// - -#pragma once - -#include "../../Utils.hpp" -#include "../../core/Record.hpp" -#include "../../core/Annotation.hpp" - -#include - -namespace edfio -{ - - inline std::vector ProcessorTalRecord::operator()(std::vector record, long long datarecord) - { - std::vector out; - - // Boundaries - auto first = record.begin(); - auto last = record.end(); - - // TAL MUST start with '+' or '-' - if (*first != '+' && *first != '-') - { - throw std::invalid_argument(detail::GetError(FileErrc::FileContainsInvalidAnnotations)); - } - - double start = 0; - double duration = 0; - bool onset = true; - for (auto it = first; it != last; it++) - { - if (std::distance(first, it) > 0) - { - // First field is for TAL onset - if (onset) - { - if (*it == detail::DURATION_DIV || *it == detail::ANNOTATION_DIV) - { - std::string tmp(first, it); - try - { - start = std::stod(tmp); - } - catch (...) - { - throw std::invalid_argument(detail::GetError(FileErrc::FileContainsInvalidAnnotations)); - } - onset = false; - - first = it; - } - } - else if (*it == detail::ANNOTATION_DIV) - { - if (*first == detail::DURATION_DIV) - { - std::string tmp(first + 1, it); - try - { - duration = std::stod(tmp); - } - catch (...) - { - throw std::invalid_argument(detail::GetError(FileErrc::FileContainsInvalidAnnotations)); - } - first = it; - } - else if (*first == detail::ANNOTATION_DIV) - { - std::string tmp(first + 1, it); - - // Check if this TAL is in fact just a timestamp, we don't want this - if (!tmp.empty()) - { - Annotation annot; - annot.m_start = start; - annot.m_duration = duration; - annot.m_annotation = tmp; - annot.m_dararecord = datarecord; - out.emplace_back(std::move(annot)); - } - first = it; - } - } - } - - } - return std::move(out); - } - -} diff --git a/include/edfio/processor/impl/ProcessorTimeStamp.ipp b/include/edfio/processor/impl/ProcessorTimeStamp.ipp deleted file mode 100644 index b0893cb..0000000 --- a/include/edfio/processor/impl/ProcessorTimeStamp.ipp +++ /dev/null @@ -1,50 +0,0 @@ -// -// Copyright(c) 2017-present Iuri Dotta (dotta dot iuri at gmail dot com) -// -// This source code is licensed under the MIT license found in the -// LICENSE file in the root directory of this source tree. -// -// Official repository: https://github.com/idotta/edfio -// - -#pragma once - -#include "../../Utils.hpp" -#include "../../core/Record.hpp" -#include "../../core/Annotation.hpp" -#include "../detail/ProcessorUtils.hpp" - -#include - -namespace edfio -{ - - inline Record ProcessorTimeStamp::operator()(TimeStamp timestamp) - { - std::string ts = detail::to_string_decimal(timestamp.m_start); - - if (ts.empty()) - { - throw std::invalid_argument(detail::GetError(FileErrc::FileWriteInvalidAnnotations)); - } - - size_t plusSignal = 0; - if (timestamp.m_start >= 0) - plusSignal = 1; - - Record record(plusSignal + ts.size() + 3); // 20 20 0 - auto it = record().begin(); - - // timestamp - if (plusSignal) - *it++ = '+'; - std::move(ts.begin(), ts.end(), it); - it += ts.size(); - *it++ = 20; // 20 div - *it++ = 20; // 20 div - *it++ = 0; // 0 end - - return record; - } - -} diff --git a/include/edfio/processor/impl/ProcessorTimeStampRecord.ipp b/include/edfio/processor/impl/ProcessorTimeStampRecord.ipp deleted file mode 100644 index b6d89b8..0000000 --- a/include/edfio/processor/impl/ProcessorTimeStampRecord.ipp +++ /dev/null @@ -1,59 +0,0 @@ -// -// Copyright(c) 2017-present Iuri Dotta (dotta dot iuri at gmail dot com) -// -// This source code is licensed under the MIT license found in the -// LICENSE file in the root directory of this source tree. -// -// Official repository: https://github.com/idotta/edfio -// - -#pragma once - -#include "../../Utils.hpp" -#include "../../core/Record.hpp" -#include "../../core/Annotation.hpp" - -#include - -namespace edfio -{ - - inline TimeStamp edfio::ProcessorTimeStampRecord::operator()(Record record, long long datarecord) - { - TimeStamp timestamp; - timestamp.m_dararecord = datarecord; - auto& value = record(); - - // TimeStamp MUST start with '+' or '-' - if (value.front() != '+' && value.front() != '-') - { - throw std::invalid_argument(detail::GetError(FileErrc::FileContainsInvalidAnnotations)); - } - - // Make sure it's a valid timestamp - static const std::vector comp = { detail::ANNOTATION_END , detail::ANNOTATION_DIV }; - auto result = std::find_first_of(value.begin(), value.end(), comp.begin(), comp.end()); - - if (result == value.end()) - { - throw std::invalid_argument(detail::GetError(FileErrc::FileContainsInvalidAnnotations)); - } - else - { - *result = 0; - char* end; - double start = std::strtod(value.data(), &end); - // On error - if (end == value.data()) - { - throw std::invalid_argument(detail::GetError(FileErrc::FileContainsInvalidAnnotations)); - } - else - { - timestamp.m_start = start; - } - } - return std::move(timestamp); - } - -} diff --git a/include/edfio/reader/ReaderHeaderExam.hpp b/include/edfio/reader/ReaderHeaderExam.hpp index 306eda8..a20721a 100644 --- a/include/edfio/reader/ReaderHeaderExam.hpp +++ b/include/edfio/reader/ReaderHeaderExam.hpp @@ -9,17 +9,53 @@ #pragma once +#include "../Errors.hpp" #include "../core/StreamIO.hpp" #include "../header/HeaderExam.hpp" +#include "../processor/ProcessorHeaderExam.hpp" +#include "../processor/ProcessorHeaderGeneralFields.hpp" +#include "../processor/ProcessorHeaderSignalFields.hpp" +#include "ReaderHeaderGeneral.hpp" +#include "ReaderHeaderSignal.hpp" -namespace edfio -{ +#include +#include - struct ReaderHeaderExam : Reader - { - HeaderExam operator ()(Stream &stream); - }; +namespace edfio { +inline HeaderExam ReadHeaderExam(Reader::Stream &stream) { + // Read general fields + auto generalFields = ReadHeaderGeneral(stream); + // Process general fields + auto general = ProcessHeaderGeneralFields(std::move(generalFields)); + + // Read signal fields + auto signalFields = ReadHeaderSignal(stream, general.m_totalSignals); + // Process signal fields + auto signals = ProcessHeaderSignalFields( + std::move(signalFields), general.m_version, general.m_datarecordDuration); + + // Process header exam + auto header = ProcessHeaderExam(std::move(general), std::move(signals)); + + // File size + { + // get current position + auto position = stream.tellg(); + // get length of file + stream.seekg(0, stream.end); + int64_t length = stream.tellg(); + // send back to previous position + stream.seekg(position, stream.beg); + + if (length != (header.m_general.m_detail.m_recordSize * + header.m_general.m_datarecordsFile + + header.m_general.m_headerSize)) { + throw std::invalid_argument(GetError(FileErrc::FileContainsFormatErrors)); + } + } + + return header; } -#include "impl/ReaderHeaderExam.ipp" +} // namespace edfio diff --git a/include/edfio/reader/ReaderHeaderGeneral.hpp b/include/edfio/reader/ReaderHeaderGeneral.hpp index 2dc1a6f..2945cd0 100644 --- a/include/edfio/reader/ReaderHeaderGeneral.hpp +++ b/include/edfio/reader/ReaderHeaderGeneral.hpp @@ -9,17 +9,37 @@ #pragma once +#include "../Errors.hpp" #include "../core/StreamIO.hpp" #include "../header/HeaderGeneral.hpp" -namespace edfio -{ +#include - struct ReaderHeaderGeneral : Reader - { - HeaderGeneralFields operator ()(Stream &stream); - }; +namespace edfio { +inline HeaderGeneralFields ReadHeaderGeneral(Reader::Stream &stream) { + HeaderGeneralFields hdr; + if (!stream || !stream.is_open()) + throw std::invalid_argument(GetError(FileErrc::FileNotOpened)); + + stream.clear(); + stream.seekg(0, std::ios::beg); + + try { + stream >> hdr.m_version; + stream >> hdr.m_patient; + stream >> hdr.m_recording; + stream >> hdr.m_startDate; + stream >> hdr.m_startTime; + stream >> hdr.m_headerSize; + stream >> hdr.m_reserved; + stream >> hdr.m_datarecordsFile; + stream >> hdr.m_datarecordDuration; + stream >> hdr.m_totalSignals; + } catch (const std::exception &) { + throw std::invalid_argument(GetError(FileErrc::FileReadError)); + } + return hdr; } -#include "impl/ReaderHeaderGeneral.ipp" +} // namespace edfio diff --git a/include/edfio/reader/ReaderHeaderSignal.hpp b/include/edfio/reader/ReaderHeaderSignal.hpp index 0054a8c..6c21376 100644 --- a/include/edfio/reader/ReaderHeaderSignal.hpp +++ b/include/edfio/reader/ReaderHeaderSignal.hpp @@ -9,24 +9,51 @@ #pragma once +#include "../Errors.hpp" +#include "../core/StreamIO.hpp" #include "../header/HeaderGeneral.hpp" #include "../header/HeaderSignal.hpp" -#include "../core/StreamIO.hpp" +#include +#include #include -namespace edfio -{ - - struct ReaderHeaderSignal : Reader - { - ReaderHeaderSignal(size_t totalSignals) : m_totalSignals(totalSignals) {} - - std::vector operator ()(Stream &stream); - private: - size_t m_totalSignals = 0; - }; - +namespace edfio { + +inline std::vector +ReadHeaderSignal(Reader::Stream &stream, uint32_t totalSignals) { + std::vector signals(totalSignals); + if (!stream || !stream.is_open()) + throw std::invalid_argument(GetError(FileErrc::FileNotOpened)); + + stream.clear(); + stream.seekg(256, std::ios::beg); + + try { + for (auto &s : signals) + stream >> s.m_label; + for (auto &s : signals) + stream >> s.m_transducer; + for (auto &s : signals) + stream >> s.m_physDimension; + for (auto &s : signals) + stream >> s.m_physicalMin; + for (auto &s : signals) + stream >> s.m_physicalMax; + for (auto &s : signals) + stream >> s.m_digitalMin; + for (auto &s : signals) + stream >> s.m_digitalMax; + for (auto &s : signals) + stream >> s.m_prefilter; + for (auto &s : signals) + stream >> s.m_samplesInDataRecord; + for (auto &s : signals) + stream >> s.m_reserved; + } catch (const std::exception &) { + throw std::invalid_argument(GetError(FileErrc::FileReadError)); + } + return signals; } -#include "impl/ReaderHeaderSignal.ipp" +} // namespace edfio diff --git a/include/edfio/reader/impl/ReaderHeaderExam.ipp b/include/edfio/reader/impl/ReaderHeaderExam.ipp deleted file mode 100644 index b49f7c5..0000000 --- a/include/edfio/reader/impl/ReaderHeaderExam.ipp +++ /dev/null @@ -1,65 +0,0 @@ -// -// Copyright(c) 2017-present Iuri Dotta (dotta dot iuri at gmail dot com) -// -// This source code is licensed under the MIT license found in the -// LICENSE file in the root directory of this source tree. -// -// Official repository: https://github.com/idotta/edfio -// - -#pragma once - -#include "../../Utils.hpp" -#include "../../header/HeaderExam.hpp" -#include "../ReaderHeaderGeneral.hpp" -#include "../ReaderHeaderSignal.hpp" -#include "../../processor/ProcessorHeaderGeneralFields.hpp" -#include "../../processor/ProcessorHeaderSignalFields.hpp" -#include "../../processor/ProcessorHeaderExam.hpp" - -#include -#include - -namespace edfio -{ - - inline HeaderExam ReaderHeaderExam::operator ()(Stream &stream) - { - // Read general fields - ReaderHeaderGeneral readerGeneral; - auto generalFields = readerGeneral(stream); - // Process general fields - ProcessorHeaderGeneralFields procGeneralFields; - auto general = std::move(procGeneralFields(std::move(generalFields))); - - // Read signal fields - ReaderHeaderSignal readerSignals(general.m_totalSignals); - auto signalFields = readerSignals(stream); - // Process signal fields - ProcessorHeaderSignalFields procSignalFields(general.m_version, general.m_datarecordDuration); - auto signals = std::move(procSignalFields(std::move(signalFields))); - - // Process header exam - ProcessorHeaderExam procHeader; - auto header = std::move(procHeader(std::move(general), std::move(signals))); - - // File size - { - // get current position - auto position = stream.tellg(); - // get length of file - stream.seekg(0, stream.end); - long long length = stream.tellg(); - // send back to previous position - stream.seekg(position, stream.beg); - - if (length != (header.m_general.m_detail.m_recordSize * header.m_general.m_datarecordsFile + header.m_general.m_headerSize)) - { - throw std::invalid_argument(detail::GetError(FileErrc::FileContainsFormatErrors)); - } - } - - return std::move(header); - } - -} diff --git a/include/edfio/reader/impl/ReaderHeaderGeneral.ipp b/include/edfio/reader/impl/ReaderHeaderGeneral.ipp deleted file mode 100644 index 166f115..0000000 --- a/include/edfio/reader/impl/ReaderHeaderGeneral.ipp +++ /dev/null @@ -1,50 +0,0 @@ -// -// Copyright(c) 2017-present Iuri Dotta (dotta dot iuri at gmail dot com) -// -// This source code is licensed under the MIT license found in the -// LICENSE file in the root directory of this source tree. -// -// Official repository: https://github.com/idotta/edfio -// - -#pragma once - -#include "../../Utils.hpp" -#include "../../header/HeaderGeneral.hpp" - -#include -#include - -namespace edfio -{ - - inline HeaderGeneralFields ReaderHeaderGeneral::operator ()(Stream &stream) - { - HeaderGeneralFields hdr; - if (!stream || !stream.is_open()) - throw std::invalid_argument(detail::GetError(FileErrc::FileNotOpened)); - - stream.clear(); - stream.seekg(0, std::ios::beg); - - try - { - stream >> hdr.m_version; - stream >> hdr.m_patient; - stream >> hdr.m_recording; - stream >> hdr.m_startDate; - stream >> hdr.m_startTime; - stream >> hdr.m_headerSize; - stream >> hdr.m_reserved; - stream >> hdr.m_datarecordsFile; - stream >> hdr.m_datarecordDuration; - stream >> hdr.m_totalSignals; - } - catch (std::exception e) - { - throw std::invalid_argument(detail::GetError(FileErrc::FileReadError)); - } - return std::move(hdr); - } - -} diff --git a/include/edfio/reader/impl/ReaderHeaderSignal.ipp b/include/edfio/reader/impl/ReaderHeaderSignal.ipp deleted file mode 100644 index 9e5a86f..0000000 --- a/include/edfio/reader/impl/ReaderHeaderSignal.ipp +++ /dev/null @@ -1,62 +0,0 @@ -// -// Copyright(c) 2017-present Iuri Dotta (dotta dot iuri at gmail dot com) -// -// This source code is licensed under the MIT license found in the -// LICENSE file in the root directory of this source tree. -// -// Official repository: https://github.com/idotta/edfio -// - -#pragma once - -#include "../../Utils.hpp" -#include "../../header/HeaderGeneral.hpp" -#include "../../header/HeaderSignal.hpp" - -#include -#include -#include - -namespace edfio -{ - - inline std::vector ReaderHeaderSignal::operator ()(Stream &stream) - { - std::vector signals(m_totalSignals); - if (!stream || !stream.is_open()) - throw std::invalid_argument(detail::GetError(FileErrc::FileNotOpened)); - - stream.clear(); - stream.seekg(256, std::ios::beg); - - try - { - for (auto &s : signals) - stream >> s.m_label; - for (auto &s : signals) - stream >> s.m_transducer; - for (auto &s : signals) - stream >> s.m_physDimension; - for (auto &s : signals) - stream >> s.m_physicalMin; - for (auto &s : signals) - stream >> s.m_physicalMax; - for (auto &s : signals) - stream >> s.m_digitalMin; - for (auto &s : signals) - stream >> s.m_digitalMax; - for (auto &s : signals) - stream >> s.m_prefilter; - for (auto &s : signals) - stream >> s.m_samplesInDataRecord; - for (auto &s : signals) - stream >> s.m_reserved; - } - catch (std::exception e) - { - throw std::invalid_argument(detail::GetError(FileErrc::FileReadError)); - } - return std::move(signals); - } - -} diff --git a/include/edfio/sink/DataRecordSink.hpp b/include/edfio/sink/DataRecordSink.hpp index b630618..c9dc3a9 100644 --- a/include/edfio/sink/DataRecordSink.hpp +++ b/include/edfio/sink/DataRecordSink.hpp @@ -11,54 +11,46 @@ #include "RecordSink.hpp" -namespace edfio -{ - - class DataRecordSink : public RecordSink - { - public: - - typedef RecordSink::iterator iterator; - typedef iterator const const_iterator; - typedef std::reverse_iterator reverse_iterator; - typedef std::reverse_iterator const_reverse_iterator; - - DataRecordSink() = delete; - - DataRecordSink(stream_type &stream, size_type recordSize, size_type storeSize, std::streamoff headerOffset) - : RecordSink(stream, recordSize, storeSize, headerOffset) - { - measure(); - } - - protected: - void measure() override - { - auto pos = m_stream.tellp(); - m_stream.seekp(0, std::ios::end); - size_type sz = m_stream.tellp(); - m_stream.seekp(pos); - if (sz < m_headerOffset) - throw std::invalid_argument("Invalid header"); - m_sinkSize = (sz - m_headerOffset) / m_recordSize; - } - - void save(size_type off, value_type value) override - { - measure(); - if (off >= m_sinkSize || off == -1) - { - m_stream.seekp(0, std::ios::end); - m_sinkSize++; - } - else - { - off = m_headerOffset + off * m_recordSize; - m_stream.seekp(off, std::ios::beg); - } - m_value() = std::move(value()); - m_stream << m_value; - } - }; - -} +namespace edfio { + +class DataRecordSink : public RecordSink { +public: + using iterator = RecordSink::iterator; + using const_iterator = iterator; + using reverse_iterator = std::reverse_iterator; + using const_reverse_iterator = std::reverse_iterator; + + DataRecordSink() = delete; + + DataRecordSink(stream_type &stream, size_type recordSize, size_type storeSize, + std::streamoff headerOffset) + : RecordSink(stream, recordSize, storeSize, headerOffset) { + measure(); + } + +protected: + void measure() override { + auto pos = m_stream.tellp(); + m_stream.seekp(0, std::ios::end); + size_type sz = m_stream.tellp(); + m_stream.seekp(pos); + if (sz < static_cast(m_headerOffset)) + throw std::invalid_argument("Invalid header"); + m_sinkSize = (sz - static_cast(m_headerOffset)) / m_recordSize; + } + + void save(size_type off, value_type value) override { + measure(); + if (off >= m_sinkSize) { + m_stream.seekp(0, std::ios::end); + m_sinkSize++; + } else { + off = m_headerOffset + off * m_recordSize; + m_stream.seekp(off, std::ios::beg); + } + m_value() = std::move(value()); + m_stream << m_value; + } +}; + +} // namespace edfio diff --git a/include/edfio/sink/RecordSink.hpp b/include/edfio/sink/RecordSink.hpp index 5b4c049..2e77c61 100644 --- a/include/edfio/sink/RecordSink.hpp +++ b/include/edfio/sink/RecordSink.hpp @@ -9,277 +9,191 @@ #pragma once -#include "Sink.hpp" #include "../core/Record.hpp" +#include "Sink.hpp" -#include +#include #include - -namespace edfio -{ - - class RecordSink : public Sink, Record*, Record&, std::ofstream, std::output_iterator_tag> - { - public: - - class iterator : public sink_type::iterator - { - size_type m_offset = -1; // Default is end - RecordSink *m_context = nullptr; - public: - - // Construction - iterator() = default; - - iterator(RecordSink *context, size_type offset = -1) - : m_offset(offset) - , m_context(context) - { - } - - iterator(const iterator &it) - : m_offset(it.m_offset) - , m_context(it.m_context) - { - } - - // Assignment - iterator& operator=(value_type value) - { - if (!m_context) - throw std::invalid_argument("Invalid context"); - m_context->save(m_offset, std::move(value)); - return *this; - } - - // Equality - bool operator==(const iterator &it) const - { - return (m_offset == it.m_offset && m_context == it.m_context); - } - bool operator!=(const iterator &it) const - { - return !(*this == it); - } - - // Relation - bool operator<(const iterator &it) const - { - if (m_context != it.m_context) - throw std::invalid_argument("Iterators incompatible"); - return (m_offset < it.m_offset); - } - bool operator>(const iterator &it) const - { - if (m_context != it.m_context) - throw std::invalid_argument("Iterators incompatible"); - return (m_offset > it.m_offset); - } - bool operator<=(const iterator &it) const - { - if (m_context != it.m_context) - throw std::invalid_argument("Iterators incompatible"); - return (m_offset <= it.m_offset); - } - bool operator>=(const iterator &it) const - { - if (m_context != it.m_context) - throw std::invalid_argument("Iterators incompatible"); - return (m_offset >= it.m_offset); - } - - // Pre-increment - iterator& operator++() - { - if (!m_context) - throw std::invalid_argument("Invalid context"); - if (m_offset == -1) - throw std::length_error("Iterator not incrementable"); - if (++m_offset >= m_context->size()) - m_offset = -1; - return *this; - } - // Post-increment - iterator operator++(int) - { - if (!m_context) - throw std::invalid_argument("Invalid context"); - iterator tmp = *this; - ++*this; - return tmp; - } - // Pre-decrement - iterator& operator--() - { - if (!m_context) - throw std::invalid_argument("Invalid context"); - if (m_offset == 0) - throw std::length_error("Iterator not decrementable"); - if (m_offset == -1) - m_offset = m_context->size() - 1; - else - m_offset--; - return *this; - } - // Post-decrement - iterator operator--(int) - { - if (!m_context) - throw std::invalid_argument("Invalid context"); - iterator tmp = *this; - --*this; - return tmp; - } - // Compound addition assignment - iterator& operator+=(size_type off) - { - if (!m_context) - throw std::invalid_argument("Invalid context"); - if (m_offset == -1) - throw std::length_error("Iterator not incrementable"); - if (m_offset + off > m_context->size()) - throw std::length_error("Iterator + offset out of range"); - if (m_offset + off == m_context->size()) - m_offset = -1; - else - m_offset += off; - return *this; - } - // Addition - iterator operator+(size_type off) const - { - if (!m_context) - throw std::invalid_argument("Invalid context"); - iterator tmp = *this; - tmp += off; - return tmp; - } - // Compound subtraction assignment - iterator& operator-=(size_type off) - { - if (!m_context) - throw std::invalid_argument("Invalid context"); - if (m_offset == 0) - throw std::length_error("Iterator not decrementable"); - if (m_offset != -1 && m_offset < off) - throw std::length_error("Iterator - offset out of range"); - if (m_offset == -1) - m_offset = m_context->size() - off; - else - m_offset -= off; - return *this; - } - // Subtraction - iterator operator-(size_type off) const - { - if (!m_context) - throw std::invalid_argument("Invalid context"); - iterator tmp = *this; - tmp -= off; - return tmp; - } - difference_type operator-(iterator it) const - { - if (!m_context) - throw std::invalid_argument("Invalid context"); - if (m_context != it.m_context) - throw std::invalid_argument("Iterators incompatible"); - return difference_type(it.m_offset - m_offset); - } - - // Dereference - iterator& operator*() - { - return *this; - } - iterator* operator->() - { - return this; - } - - // Subscripting - iterator& operator[](size_type) - { - return *this; - } - }; - - typedef iterator const const_iterator; - typedef std::reverse_iterator reverse_iterator; - typedef std::reverse_iterator const_reverse_iterator; - - RecordSink() = delete; - - RecordSink(stream_type &stream, size_type recordSize, size_type sinkSize, std::streamoff headerOffset) - : sink_type(stream) - , m_recordSize(recordSize) - , m_headerOffset(headerOffset) - , m_value(recordSize) - { - } - - iterator begin() - { - return iterator(this, 0); - } - const_iterator begin() const - { - return const_iterator(const_cast(this), 0); - } - const_iterator cbegin() const - { - return const_iterator(const_cast(this), 0); - } - iterator end() - { - return iterator(this); - } - const_iterator end() const - { - return const_iterator(const_cast(this)); - } - const_iterator cend() const - { - return const_iterator(const_cast(this)); - } - reverse_iterator rbegin() - { - return reverse_iterator(end()); - } - const_reverse_iterator rbegin() const - { - return const_reverse_iterator(end()); - } - const_reverse_iterator crbegin() const - { - return const_reverse_iterator(cend()); - } - reverse_iterator rend() - { - return reverse_iterator(begin()); - } - const_reverse_iterator rend() const - { - return const_reverse_iterator(begin()); - } - const_reverse_iterator crend() const - { - return const_reverse_iterator(cbegin()); - } - - size_type size() const - { - return m_sinkSize; - } - - protected: - virtual void measure() = 0; - virtual void save(size_type off, value_type value) = 0; - - size_type m_recordSize; - size_type m_sinkSize; - std::streamoff m_headerOffset; - value_type m_value; - }; - -} +#include + +namespace edfio { + +class RecordSink : public Sink, Record *, Record &, + std::ofstream, std::output_iterator_tag> { + using base_sink = Sink, Record *, Record &, + std::ofstream, std::output_iterator_tag>; + +public: + using typename base_sink::difference_type; + using typename base_sink::pointer; + using typename base_sink::reference; + using typename base_sink::size_type; + using typename base_sink::stream_type; + using typename base_sink::value_type; + + virtual ~RecordSink() = default; + + class iterator : public base_sink::iterator { + std::optional m_offset; // nullopt = end + RecordSink *m_context = nullptr; + + public: + // Construction + iterator() = default; + + iterator(RecordSink *context, + std::optional offset = std::nullopt) + : m_offset(offset), m_context(context) {} + + iterator(const iterator &it) + : m_offset(it.m_offset), m_context(it.m_context) {} + + // Assignment + iterator &operator=(value_type value) { + if (!m_context) + throw std::invalid_argument("Invalid context"); + if (!m_offset) + throw std::length_error("Cannot assign to end iterator"); + m_context->save(*m_offset, std::move(value)); + return *this; + } + + // Equality (!= auto-generated) + bool operator==(const iterator &it) const { + return (m_offset == it.m_offset && m_context == it.m_context); + } + + // Three-way comparison (<, >, <=, >= auto-generated) + std::strong_ordering operator<=>(const iterator &it) const { + if (m_context != it.m_context) + throw std::invalid_argument("Iterators incompatible"); + auto lhs = m_offset.value_or(m_context->size()); + auto rhs = it.m_offset.value_or(it.m_context->size()); + return lhs <=> rhs; + } + + // Pre-increment + iterator &operator++() { + if (!m_context) + throw std::invalid_argument("Invalid context"); + if (!m_offset) + throw std::length_error("Iterator not incrementable"); + if (++(*m_offset) >= m_context->size()) + m_offset = std::nullopt; + return *this; + } + // Post-increment + iterator operator++(int) { + if (!m_context) + throw std::invalid_argument("Invalid context"); + iterator tmp = *this; + ++*this; + return tmp; + } + // Pre-decrement + iterator &operator--() { + if (!m_context) + throw std::invalid_argument("Invalid context"); + if (m_offset && *m_offset == 0) + throw std::length_error("Iterator not decrementable"); + if (!m_offset) + m_offset = m_context->size() - 1; + else + (*m_offset)--; + return *this; + } + // Post-decrement + iterator operator--(int) { + if (!m_context) + throw std::invalid_argument("Invalid context"); + iterator tmp = *this; + --*this; + return tmp; + } + // Compound addition assignment + iterator &operator+=(size_type off) { + if (!m_context) + throw std::invalid_argument("Invalid context"); + if (!m_offset) + throw std::length_error("Iterator not incrementable"); + if (*m_offset + off > m_context->size()) + throw std::length_error("Iterator + offset out of range"); + if (*m_offset + off == m_context->size()) + m_offset = std::nullopt; + else + *m_offset += off; + return *this; + } + // Addition + iterator operator+(size_type off) const { + if (!m_context) + throw std::invalid_argument("Invalid context"); + iterator tmp = *this; + tmp += off; + return tmp; + } + // Compound subtraction assignment + iterator &operator-=(size_type off) { + if (!m_context) + throw std::invalid_argument("Invalid context"); + auto pos = m_offset.value_or(m_context->size()); + if (pos < off) + throw std::length_error("Iterator - offset out of range"); + m_offset = pos - off; + return *this; + } + // Subtraction + iterator operator-(size_type off) const { + if (!m_context) + throw std::invalid_argument("Invalid context"); + iterator tmp = *this; + tmp -= off; + return tmp; + } + difference_type operator-(iterator it) const { + if (!m_context) + throw std::invalid_argument("Invalid context"); + if (m_context != it.m_context) + throw std::invalid_argument("Iterators incompatible"); + auto lhs = + static_cast(m_offset.value_or(m_context->size())); + auto rhs = static_cast( + it.m_offset.value_or(it.m_context->size())); + return lhs - rhs; + } + + // Dereference + iterator &operator*() { return *this; } + iterator *operator->() { return this; } + + // Subscripting + iterator &operator[](size_type) { return *this; } + }; + + using reverse_iterator = std::reverse_iterator; + + RecordSink() = delete; + + RecordSink(stream_type &stream, size_type recordSize, size_type sinkSize, + std::streamoff headerOffset) + : sink_type(stream), m_recordSize(recordSize), m_sinkSize(sinkSize), + m_headerOffset(headerOffset), m_value(recordSize) {} + + iterator begin() { return iterator(this, 0); } + iterator end() { return iterator(this); } + reverse_iterator rbegin() { return reverse_iterator(end()); } + reverse_iterator rend() { return reverse_iterator(begin()); } + + [[nodiscard]] size_type size() const { return m_sinkSize; } + +protected: + virtual void measure() = 0; + virtual void save(size_type off, value_type value) = 0; + + size_type m_recordSize; + size_type m_sinkSize; + std::streamoff m_headerOffset; + value_type m_value; +}; + +} // namespace edfio diff --git a/include/edfio/sink/SignalRecordSink.hpp b/include/edfio/sink/SignalRecordSink.hpp index 9a7cd90..8218715 100644 --- a/include/edfio/sink/SignalRecordSink.hpp +++ b/include/edfio/sink/SignalRecordSink.hpp @@ -11,69 +11,65 @@ #include "RecordSink.hpp" -namespace edfio -{ +namespace edfio { - class SignalRecordSink : public RecordSink - { - public: +class SignalRecordSink : public RecordSink { +public: + using iterator = RecordSink::iterator; + using const_iterator = iterator; + using reverse_iterator = std::reverse_iterator; + using const_reverse_iterator = std::reverse_iterator; - typedef RecordSink::iterator iterator; - typedef iterator const const_iterator; - typedef std::reverse_iterator reverse_iterator; - typedef std::reverse_iterator const_reverse_iterator; + SignalRecordSink() = delete; - SignalRecordSink() = delete; + SignalRecordSink(stream_type &stream, size_type recordSize, + size_type storeSize, std::streamoff headerOffset, + size_type datarecordSize, std::streamoff signalOffset) + : RecordSink(stream, recordSize, storeSize, headerOffset), + m_datarecordSize(datarecordSize), m_signalOffset(signalOffset) { + measure(); + } - SignalRecordSink(stream_type &stream, size_type recordSize, size_type storeSize, std::streamoff headerOffset, size_type datarecordSize, std::streamoff signalOffset) - : RecordSink(stream, recordSize, storeSize, headerOffset) - , m_datarecordSize(datarecordSize) - , m_signalOffset(signalOffset) - { - measure(); - } +protected: + void measure() override { + auto pos = m_stream.tellp(); + m_stream.seekp(0, std::ios::end); + size_type sz = m_stream.tellp(); + m_stream.seekp(pos); + if (sz < static_cast(m_headerOffset)) + throw std::invalid_argument("Invalid header"); - protected: - void measure() override - { - auto pos = m_stream.tellp(); - m_stream.seekp(0, std::ios::end); - size_type sz = m_stream.tellp(); - m_stream.seekp(pos); - if (sz < m_headerOffset) - throw std::invalid_argument("Invalid header"); - - size_type datarecords = (sz - m_headerOffset) / m_datarecordSize; - size_type offset = (sz - m_headerOffset) % m_datarecordSize;; - - m_sinkSize = datarecords; - if (offset >= m_signalOffset) - m_sinkSize++; - } + size_type hdrOff = static_cast(m_headerOffset); + size_type sigOff = static_cast(m_signalOffset); + size_type datarecords = (sz - hdrOff) / m_datarecordSize; + size_type offset = (sz - hdrOff) % m_datarecordSize; - void save(size_type off, value_type value) override - { - measure(); - if (off >= m_sinkSize || off == -1) - { - m_stream.seekp(0, std::ios::end); - size_type sz = m_stream.tellp(); - size_type offset = (sz - m_headerOffset) % m_datarecordSize;; - if (offset < m_signalOffset) - throw std::invalid_argument("Invalid signal order"); - m_sinkSize++; - } - else - { - off = m_headerOffset + off * m_datarecordSize + m_signalOffset; - m_stream.seekp(off, std::ios::beg); - } - m_value() = std::move(value()); - m_stream << m_value; - } + m_sinkSize = datarecords; + if (offset >= sigOff) + m_sinkSize++; + } - size_type m_datarecordSize; - std::streamoff m_signalOffset; - }; + void save(size_type off, value_type value) override { + measure(); + if (off >= m_sinkSize) { + m_stream.seekp(0, std::ios::end); + size_type sz = m_stream.tellp(); + size_type hdrOff = static_cast(m_headerOffset); + size_type sigOff = static_cast(m_signalOffset); + size_type offset = (sz - hdrOff) % m_datarecordSize; + if (offset < sigOff) + throw std::invalid_argument("Invalid signal order"); + m_sinkSize++; + } else { + off = m_headerOffset + off * m_datarecordSize + m_signalOffset; + m_stream.seekp(off, std::ios::beg); + } + m_value() = std::move(value()); + m_stream << m_value; + } -} + size_type m_datarecordSize; + std::streamoff m_signalOffset; +}; + +} // namespace edfio diff --git a/include/edfio/sink/Sink.hpp b/include/edfio/sink/Sink.hpp index 18ae717..5b70972 100644 --- a/include/edfio/sink/Sink.hpp +++ b/include/edfio/sink/Sink.hpp @@ -11,24 +11,27 @@ #include "../core/Device.hpp" -namespace edfio -{ +namespace edfio { - // A class created in order to have an easier way to write streams - // of specific data through their respective iterators. - template - class Sink : public Device - { - public: - typedef Sink sink_type; - typedef device_type::iterator iterator; +// A class created in order to have an easier way to write streams +// of specific data through their respective iterators. +template +class Sink : public Device { +public: + using device_type = Device; + using sink_type = Sink; + using typename device_type::difference_type; + using typename device_type::pointer; + using typename device_type::reference; + using typename device_type::size_type; + using typename device_type::stream_type; + using typename device_type::value_type; + using iterator = typename device_type::iterator; - Sink() = delete; + Sink() = delete; - Sink(stream_type &stream) - : device_type(stream) - { - } - }; + Sink(stream_type &stream) : device_type(stream) {} +}; -} +} // namespace edfio diff --git a/include/edfio/sink/SinkUtils.hpp b/include/edfio/sink/SinkUtils.hpp new file mode 100644 index 0000000..687163e --- /dev/null +++ b/include/edfio/sink/SinkUtils.hpp @@ -0,0 +1,47 @@ +// +// Copyright(c) 2017-present Iuri Dotta (dotta dot iuri at gmail dot com) +// +// This source code is licensed under the MIT license found in the +// LICENSE file in the root directory of this source tree. +// +// Official repository: https://github.com/idotta/edfio +// + +#pragma once + +#include "../header/HeaderGeneral.hpp" +#include "../header/HeaderSignal.hpp" +#include "DataRecordSink.hpp" +#include "SignalRecordSink.hpp" + + +namespace edfio { + +namespace detail { + +template +inline DataRecordSink CreateDataRecordSink(Stream &stream, + const HeaderGeneral &general) { + DataRecordSink::size_type recordSize = general.m_detail.m_recordSize; + DataRecordSink::size_type sinkSize = general.m_datarecordsFile; + std::streamoff headerSize = general.m_headerSize; + return DataRecordSink{stream, recordSize, sinkSize, headerSize}; +} + +template +inline SignalRecordSink CreateSignalRecordSink(Stream &stream, + const HeaderGeneral &general, + const HeaderSignal &signal) { + SignalRecordSink::size_type recordSize = general.m_detail.m_recordSize; + SignalRecordSink::size_type sinkSize = general.m_datarecordsFile; + std::streamoff headerSize = general.m_headerSize; + SignalRecordSink::size_type signalSize = + signal.m_samplesInDataRecord * GetSampleBytes(general.m_version); + std::streamoff signalOff = signal.m_detail.m_signalOffset; + return SignalRecordSink{stream, signalSize, sinkSize, + headerSize, recordSize, signalOff}; +} + +} // namespace detail + +} // namespace edfio \ No newline at end of file diff --git a/include/edfio/sink/detail/SinkUtils.hpp b/include/edfio/sink/detail/SinkUtils.hpp deleted file mode 100644 index fcbba58..0000000 --- a/include/edfio/sink/detail/SinkUtils.hpp +++ /dev/null @@ -1,47 +0,0 @@ -// -// Copyright(c) 2017-present Iuri Dotta (dotta dot iuri at gmail dot com) -// -// This source code is licensed under the MIT license found in the -// LICENSE file in the root directory of this source tree. -// -// Official repository: https://github.com/idotta/edfio -// - -#pragma once - -#include "../DataRecordSink.hpp" -#include "../SignalRecordSink.hpp" -#include "../../header/HeaderGeneral.hpp" -#include "../../header/HeaderSignal.hpp" - -#include - -namespace edfio -{ - - namespace detail - { - - template - static DataRecordSink CreateDataRecordSink(Stream &stream, const HeaderGeneral &general) - { - DataRecordSink::size_type recordSize = general.m_detail.m_recordSize; - DataRecordSink::size_type sinkSize = general.m_datarecordsFile; - std::streamoff headerSize = general.m_headerSize; - return std::move(DataRecordSink{ stream, recordSize, sinkSize, headerSize }); - } - - template - static SignalRecordSink CreateSignalRecordSink(Stream &stream, const HeaderGeneral &general, const HeaderSignal &signal) - { - SignalRecordSink::size_type recordSize = general.m_detail.m_recordSize; - SignalRecordSink::size_type sinkSize = general.m_datarecordsFile; - std::streamoff headerSize = general.m_headerSize; - SignalRecordSink::size_type signalSize = signal.m_samplesInDataRecord * GetSampleBytes(general.m_version); - std::streamoff signalOff = signal.m_detail.m_signalOffset; - return std::move(SignalRecordSink{ stream, signalSize, sinkSize, headerSize, recordSize, signalOff }); - } - - } - -} \ No newline at end of file diff --git a/include/edfio/store/DatarecordStore.hpp b/include/edfio/store/DatarecordStore.hpp index 47fa58b..22acff4 100644 --- a/include/edfio/store/DatarecordStore.hpp +++ b/include/edfio/store/DatarecordStore.hpp @@ -11,46 +11,37 @@ #include "RecordStore.hpp" -namespace edfio -{ - - class DataRecordStore : public RecordStore - { - public: - - typedef RecordStore::iterator iterator; - typedef iterator const const_iterator; - typedef std::reverse_iterator reverse_iterator; //optional - typedef std::reverse_iterator const_reverse_iterator; //optional - - DataRecordStore() = delete; - - DataRecordStore(stream_type &stream, size_type recordSize, size_type storeSize, std::streamoff headerOffset) - : RecordStore(stream, recordSize, storeSize, headerOffset) - { - } - - protected: - - void load(size_type off) override - { - if (off < 0 || off >= size()) - { - throw std::out_of_range("Iterator not dereferenceable"); - } - - if (!m_stream.good()) - m_stream.clear(); - - auto currentPos = m_stream.tellg(); - auto destPos = m_headerOffset + m_recordSize * off; - if (destPos != currentPos) - { - m_stream.seekg(destPos, std::ios::beg); - } - m_stream >> m_value; - - } - }; - -} +namespace edfio { + +class DataRecordStore : public RecordStore { +public: + using iterator = RecordStore::iterator; + using const_iterator = iterator; + using reverse_iterator = std::reverse_iterator; + using const_reverse_iterator = std::reverse_iterator; + + DataRecordStore() = delete; + + DataRecordStore(stream_type &stream, size_type recordSize, + size_type storeSize, std::streamoff headerOffset) + : RecordStore(stream, recordSize, storeSize, headerOffset) {} + +protected: + void load(size_type off) const override { + if (off >= size()) { + throw std::out_of_range("Iterator not dereferenceable"); + } + + if (!m_stream.good()) + m_stream.clear(); + + auto currentPos = m_stream.tellg(); + auto destPos = m_headerOffset + m_recordSize * off; + if (destPos != currentPos) { + m_stream.seekg(destPos, std::ios::beg); + } + m_stream >> m_value; + } +}; + +} // namespace edfio diff --git a/include/edfio/store/RecordStore.hpp b/include/edfio/store/RecordStore.hpp index 8a74370..8c79c32 100644 --- a/include/edfio/store/RecordStore.hpp +++ b/include/edfio/store/RecordStore.hpp @@ -9,284 +9,212 @@ #pragma once -#include "Store.hpp" #include "../core/Record.hpp" +#include "Store.hpp" -#include +#include #include #include -namespace edfio -{ - - class RecordStore : public Store, Record const*, Record const&, std::ifstream, std::random_access_iterator_tag> - { - public: - - class iterator : public store_type::iterator - { - size_type m_offset = 0; // Relative to total of Stores - RecordStore *m_context = nullptr; - public: - - // Construction - iterator() = default; - - iterator(RecordStore *context, size_type offset = 0) - : m_offset(offset) - , m_context(context) - { - } - - iterator(const iterator &it) - : m_offset(it.m_offset) - , m_context(it.m_context) - { - } - - // Assignment - iterator& operator=(const iterator &it) - { - m_offset = it.m_offset; - m_context = it.m_context; - return *this; - } - - // Equality - bool operator==(const iterator &it) const - { - return (m_offset == it.m_offset && m_context == it.m_context); - } - bool operator!=(const iterator &it) const - { - return !(*this == it); - } - - // Relation - bool operator<(const iterator &it) const - { - if (m_context != it.m_context) - throw std::invalid_argument("Iterators incompatible"); - return (m_offset < it.m_offset); - } - bool operator>(const iterator &it) const - { - if (m_context != it.m_context) - throw std::invalid_argument("Iterators incompatible"); - return (m_offset > it.m_offset); - } - bool operator<=(const iterator &it) const - { - if (m_context != it.m_context) - throw std::invalid_argument("Iterators incompatible"); - return (m_offset <= it.m_offset); - } - bool operator>=(const iterator &it) const - { - if (m_context != it.m_context) - throw std::invalid_argument("Iterators incompatible"); - return (m_offset >= it.m_offset); - } - - // Pre-increment - iterator& operator++() - { - if (!m_context) - throw std::invalid_argument("Invalid context"); - if (m_context->size() <= 0 || m_offset + 1 > m_context->size()) - throw std::length_error("Iterator not incrementable"); - m_offset++; - return *this; - } - // Post-increment - iterator operator++(int) - { - if (!m_context) - throw std::invalid_argument("Invalid context"); - iterator tmp = *this; - ++*this; - return tmp; - } - // Pre-decrement - iterator& operator--() - { - if (!m_context) - throw std::invalid_argument("Invalid context"); - if (m_context->size() <= 0 || m_offset == 0) - throw std::length_error("Iterator not decrementable"); - m_offset--; - return *this; - } - // Post-decrement - iterator operator--(int) - { - if (!m_context) - throw std::invalid_argument("Invalid context"); - iterator tmp = *this; - --*this; - return tmp; - } - // Compound addition assignment - iterator& operator+=(size_type off) - { - if (!m_context) - throw std::invalid_argument("Invalid context"); - if (m_context->size() <= 0 || m_offset + off > m_context->size()) - throw std::length_error("Iterator + offset out of range"); - m_offset += off; - return *this; - } - // Addition - iterator operator+(size_type off) const - { - if (!m_context) - throw std::invalid_argument("Invalid context"); - iterator tmp = *this; - tmp += off; - return tmp; - } - // Compound subtraction assignment - iterator& operator-=(size_type off) - { - if (!m_context) - throw std::invalid_argument("Invalid context"); - if (m_context->size() <= 0 || m_offset < off) - throw std::length_error("Iterator - offset out of range"); - m_offset -= off; - return *this; - } - // Subtraction - iterator operator-(size_type off) const - { - if (!m_context) - throw std::invalid_argument("Invalid context"); - iterator tmp = *this; - tmp -= off; - return tmp; - } - difference_type operator-(iterator it) const - { - if (!m_context) - throw std::invalid_argument("Invalid context"); - if (m_context != it.m_context) - throw std::invalid_argument("Iterators incompatible"); - return difference_type(it.m_offset - m_offset); - } - - // Dereference - reference operator*() const - { - if (!m_context) - throw std::invalid_argument("Invalid context"); - return m_context->getR(m_offset); - } - pointer operator->() const - { - if (!m_context) - throw std::invalid_argument("Invalid context"); - return m_context->getP(m_offset); - } - - // Subscripting - reference operator[](size_type off) const - { - if (!m_context) - throw std::invalid_argument("Invalid context"); - iterator tmp = *this; - tmp += off; - return *tmp; - } - }; - - typedef iterator const const_iterator; - typedef std::reverse_iterator reverse_iterator; - typedef std::reverse_iterator const_reverse_iterator; - - RecordStore() = delete; - - RecordStore(stream_type &stream, size_type recordSize, size_type storeSize, std::streamoff headerOffset) - : store_type(stream) - , m_recordSize(recordSize) - , m_storeSize(storeSize) - , m_headerOffset(headerOffset) - , m_value(recordSize) - { - } - - iterator begin() - { - return iterator(this); - } - const_iterator begin() const - { - return const_iterator(const_cast(this)); - } - const_iterator cbegin() const - { - return const_iterator(const_cast(this)); - } - iterator end() - { - return iterator(this, size()); - } - const_iterator end() const - { - return const_iterator(const_cast(this), size()); - } - const_iterator cend() const - { - return const_iterator(const_cast(this), size()); - } - reverse_iterator rbegin() - { - return reverse_iterator(end()); - } - const_reverse_iterator rbegin() const - { - return const_reverse_iterator(end()); - } - const_reverse_iterator crbegin() const - { - return const_reverse_iterator(cend()); - } - reverse_iterator rend() - { - return reverse_iterator(begin()); - } - const_reverse_iterator rend() const - { - return const_reverse_iterator(begin()); - } - const_reverse_iterator crend() const - { - return const_reverse_iterator(cbegin()); - } - - // Overrides - virtual size_type size() const - { - return m_storeSize; - } - - protected: - virtual reference getR(size_type off) - { - load(off); - return m_value; - } - - virtual pointer getP(size_type off) - { - load(off); - return &m_value; - } - - virtual void load(size_type off) = 0; - - size_type m_recordSize; - size_type m_storeSize; - std::streamoff m_headerOffset; - value_type m_value; - }; -} +namespace edfio { + +class RecordStore + : public Store, Record const *, Record const &, + std::ifstream, std::random_access_iterator_tag> { + using base_store = + Store, Record const *, Record const &, + std::ifstream, std::random_access_iterator_tag>; + +public: + using typename base_store::difference_type; + using typename base_store::pointer; + using typename base_store::reference; + using typename base_store::size_type; + using typename base_store::stream_type; + using typename base_store::value_type; + + virtual ~RecordStore() = default; + + class iterator : public base_store::iterator { + size_type m_offset = 0; // Relative to total of Stores + const RecordStore *m_context = nullptr; + + public: + // Construction + iterator() = default; + + iterator(const RecordStore *context, size_type offset = 0) + : m_offset(offset), m_context(context) {} + + iterator(const iterator &it) = default; + iterator &operator=(const iterator &it) = default; + + // Equality (!= auto-generated) + bool operator==(const iterator &it) const { + return (m_offset == it.m_offset && m_context == it.m_context); + } + + // Three-way comparison (<, >, <=, >= auto-generated) + std::strong_ordering operator<=>(const iterator &it) const { + if (m_context != it.m_context) + throw std::invalid_argument("Iterators incompatible"); + return m_offset <=> it.m_offset; + } + + // Pre-increment + iterator &operator++() { + if (!m_context) + throw std::invalid_argument("Invalid context"); + if (m_context->size() <= 0 || m_offset + 1 > m_context->size()) + throw std::length_error("Iterator not incrementable"); + m_offset++; + return *this; + } + // Post-increment + iterator operator++(int) { + if (!m_context) + throw std::invalid_argument("Invalid context"); + iterator tmp = *this; + ++*this; + return tmp; + } + // Pre-decrement + iterator &operator--() { + if (!m_context) + throw std::invalid_argument("Invalid context"); + if (m_context->size() <= 0 || m_offset == 0) + throw std::length_error("Iterator not decrementable"); + m_offset--; + return *this; + } + // Post-decrement + iterator operator--(int) { + if (!m_context) + throw std::invalid_argument("Invalid context"); + iterator tmp = *this; + --*this; + return tmp; + } + // Compound addition assignment + iterator &operator+=(difference_type n) { + if (!m_context) + throw std::invalid_argument("Invalid context"); + if (n < 0) + return *this -= static_cast(-n); + auto off = static_cast(n); + if (m_offset + off > m_context->size()) + throw std::length_error("Iterator + offset out of range"); + m_offset += off; + return *this; + } + // Addition + iterator operator+(difference_type n) const { + if (!m_context) + throw std::invalid_argument("Invalid context"); + iterator tmp = *this; + tmp += n; + return tmp; + } + // Compound subtraction assignment + iterator &operator-=(difference_type n) { + if (!m_context) + throw std::invalid_argument("Invalid context"); + if (n < 0) + return *this += static_cast(-n); + auto off = static_cast(n); + if (m_offset < off) + throw std::length_error("Iterator - offset out of range"); + m_offset -= off; + return *this; + } + // Subtraction + iterator operator-(difference_type n) const { + if (!m_context) + throw std::invalid_argument("Invalid context"); + iterator tmp = *this; + tmp -= n; + return tmp; + } + difference_type operator-(iterator it) const { + if (!m_context) + throw std::invalid_argument("Invalid context"); + if (m_context != it.m_context) + throw std::invalid_argument("Iterators incompatible"); + return difference_type(m_offset - it.m_offset); + } + + // Dereference + reference operator*() const { + if (!m_context) + throw std::invalid_argument("Invalid context"); + return m_context->getR(m_offset); + } + pointer operator->() const { + if (!m_context) + throw std::invalid_argument("Invalid context"); + return m_context->getP(m_offset); + } + + // Subscripting + reference operator[](difference_type n) const { + if (!m_context) + throw std::invalid_argument("Invalid context"); + iterator tmp = *this; + tmp += n; + return *tmp; + } + + // n + it (required for random_access_iterator) + friend iterator operator+(difference_type n, const iterator &it) { + return it + n; + } + }; + + using const_iterator = iterator; + using reverse_iterator = std::reverse_iterator; + using const_reverse_iterator = std::reverse_iterator; + + RecordStore() = delete; + + RecordStore(stream_type &stream, size_type recordSize, size_type storeSize, + std::streamoff headerOffset) + : store_type(stream), m_recordSize(recordSize), m_storeSize(storeSize), + m_headerOffset(headerOffset), m_value(recordSize) {} + + iterator begin() const { return iterator(this); } + const_iterator cbegin() const { return begin(); } + iterator end() const { return iterator(this, size()); } + const_iterator cend() const { return end(); } + reverse_iterator rbegin() const { return reverse_iterator(end()); } + const_reverse_iterator crbegin() const { + return const_reverse_iterator(cend()); + } + reverse_iterator rend() const { return reverse_iterator(begin()); } + const_reverse_iterator crend() const { + return const_reverse_iterator(cbegin()); + } + + // Overrides + [[nodiscard]] virtual size_type size() const { return m_storeSize; } + +protected: + virtual reference getR(size_type off) const { + load(off); + return m_value; + } + + virtual pointer getP(size_type off) const { + load(off); + return &m_value; + } + + virtual void load(size_type off) const = 0; + + size_type m_recordSize; + size_type m_storeSize; + std::streamoff m_headerOffset; + mutable value_type m_value; +}; + +} // namespace edfio diff --git a/include/edfio/store/SignalSampleStore.hpp b/include/edfio/store/SignalSampleStore.hpp index afabe80..8515a4b 100644 --- a/include/edfio/store/SignalSampleStore.hpp +++ b/include/edfio/store/SignalSampleStore.hpp @@ -11,74 +11,69 @@ #include "RecordStore.hpp" -namespace edfio -{ - - class SignalSampleStore : public RecordStore - { - public: - - typedef RecordStore::iterator iterator; - typedef iterator const const_iterator; - typedef std::reverse_iterator reverse_iterator; //optional - typedef std::reverse_iterator const_reverse_iterator; //optional - - SignalSampleStore() = delete; - - SignalSampleStore(stream_type &stream, size_type recordSize, size_type storeSize, - std::streamoff headerOffset, size_type datarecordSize, - size_type signalrecordSize, std::streamoff signalOffset) - : RecordStore(stream, recordSize, storeSize, headerOffset) - , m_datarecordSize(datarecordSize) - , m_signalrecordSize(signalrecordSize) - , m_signalOffset(signalOffset) - , m_buffer(recordSize * signalrecordSize) - , m_bufferPos(-1) - { - } - - protected: - - void load(size_type off) override - { - if (off < 0 || off >= size()) - { - throw std::out_of_range("Iterator not dereferenceable"); - } - - std::streamoff dataRecordOffset = off / m_signalrecordSize; - std::streamoff sampleOffset = off % m_signalrecordSize; - std::streamoff destPos = m_headerOffset + dataRecordOffset * m_datarecordSize + m_signalOffset + sampleOffset * m_recordSize; - - if (m_bufferPos < 0 || (destPos < m_bufferPos || destPos >= m_bufferPos + m_buffer.Size())) - { - readStream(destPos); - m_bufferPos = m_headerOffset + dataRecordOffset * m_datarecordSize + m_signalOffset; - } - - auto first = m_buffer().begin() + sampleOffset * m_recordSize; - std::copy(first, first + m_value.Size(), m_value().begin()); - } - - void readStream(long long newPos) - { - if (!m_stream.good()) - m_stream.clear(); - - auto oldPos = m_stream.tellg(); - if (newPos != oldPos) - { - m_stream.seekg(newPos, std::ios::beg); - } - m_stream >> m_buffer; - } - - size_type m_datarecordSize; - size_type m_signalrecordSize; - std::streamoff m_signalOffset; - // Samples buffer to decrease read requests - value_type m_buffer; - std::streamoff m_bufferPos; - }; - -} +#include +#include + +namespace edfio { + +class SignalSampleStore : public RecordStore { +public: + using iterator = RecordStore::iterator; + using const_iterator = iterator; + using reverse_iterator = std::reverse_iterator; + using const_reverse_iterator = std::reverse_iterator; + + SignalSampleStore() = delete; + + SignalSampleStore(stream_type &stream, size_type recordSize, + size_type storeSize, std::streamoff headerOffset, + size_type datarecordSize, size_type signalrecordSize, + std::streamoff signalOffset) + : RecordStore(stream, recordSize, storeSize, headerOffset), + m_datarecordSize(datarecordSize), m_signalrecordSize(signalrecordSize), + m_signalOffset(signalOffset), m_buffer(recordSize * signalrecordSize), + m_bufferPos(-1) {} + +protected: + void load(size_type off) const override { + if (off >= size()) { + throw std::out_of_range("Iterator not dereferenceable"); + } + + std::streamoff dataRecordOffset = off / m_signalrecordSize; + std::streamoff sampleOffset = off % m_signalrecordSize; + std::streamoff destPos = m_headerOffset + + dataRecordOffset * m_datarecordSize + + m_signalOffset + sampleOffset * m_recordSize; + + if (m_bufferPos < 0 || + (destPos < m_bufferPos || destPos >= m_bufferPos + static_cast(m_buffer.Size()))) { + readStream(destPos); + m_bufferPos = + m_headerOffset + dataRecordOffset * m_datarecordSize + m_signalOffset; + } + + auto first = m_buffer().begin() + sampleOffset * m_recordSize; + std::ranges::copy_n(first, m_value.Size(), m_value().begin()); + } + + void readStream(int64_t newPos) const { + if (!m_stream.good()) + m_stream.clear(); + + auto oldPos = m_stream.tellg(); + if (newPos != oldPos) { + m_stream.seekg(newPos, std::ios::beg); + } + m_stream >> m_buffer; + } + + size_type m_datarecordSize; + size_type m_signalrecordSize; + std::streamoff m_signalOffset; + // Samples buffer to decrease read requests + mutable value_type m_buffer; + mutable std::streamoff m_bufferPos; +}; + +} // namespace edfio diff --git a/include/edfio/store/SignalrecordStore.hpp b/include/edfio/store/SignalrecordStore.hpp index 042bd28..531b520 100644 --- a/include/edfio/store/SignalrecordStore.hpp +++ b/include/edfio/store/SignalrecordStore.hpp @@ -11,52 +11,42 @@ #include "RecordStore.hpp" -namespace edfio -{ - - class SignalRecordStore : public RecordStore - { - public: - - typedef RecordStore::iterator iterator; - typedef iterator const const_iterator; - typedef std::reverse_iterator reverse_iterator; //optional - typedef std::reverse_iterator const_reverse_iterator; //optional - - SignalRecordStore() = delete; - - SignalRecordStore(stream_type &stream, size_type recordSize, size_type storeSize, - std::streamoff headerOffset, size_type datarecordSize, std::streamoff signalOffset) - : RecordStore(stream, recordSize, storeSize, headerOffset) - , m_datarecordSize(datarecordSize) - , m_signalOffset(signalOffset) - { - } - - protected: - - void load(size_type off) override - { - if (off < 0 || off >= size()) - { - throw std::out_of_range("Iterator not dereferenceable"); - } - - if (!m_stream.good()) - m_stream.clear(); - - auto currentPos = m_stream.tellg(); - auto destPos = m_headerOffset + m_datarecordSize * off + m_signalOffset; - if (destPos != currentPos) - { - m_stream.seekg(destPos, std::ios::beg); - } - m_stream >> m_value; - - } - - size_type m_datarecordSize; - std::streamoff m_signalOffset; - }; - -} +namespace edfio { + +class SignalRecordStore : public RecordStore { +public: + using iterator = RecordStore::iterator; + using const_iterator = iterator; + using reverse_iterator = std::reverse_iterator; + using const_reverse_iterator = std::reverse_iterator; + + SignalRecordStore() = delete; + + SignalRecordStore(stream_type &stream, size_type recordSize, + size_type storeSize, std::streamoff headerOffset, + size_type datarecordSize, std::streamoff signalOffset) + : RecordStore(stream, recordSize, storeSize, headerOffset), + m_datarecordSize(datarecordSize), m_signalOffset(signalOffset) {} + +protected: + void load(size_type off) const override { + if (off >= size()) { + throw std::out_of_range("Iterator not dereferenceable"); + } + + if (!m_stream.good()) + m_stream.clear(); + + auto currentPos = m_stream.tellg(); + auto destPos = m_headerOffset + m_datarecordSize * off + m_signalOffset; + if (destPos != currentPos) { + m_stream.seekg(destPos, std::ios::beg); + } + m_stream >> m_value; + } + + size_type m_datarecordSize; + std::streamoff m_signalOffset; +}; + +} // namespace edfio diff --git a/include/edfio/store/Store.hpp b/include/edfio/store/Store.hpp index 08eda9b..8608f6a 100644 --- a/include/edfio/store/Store.hpp +++ b/include/edfio/store/Store.hpp @@ -11,25 +11,28 @@ #include "../core/Device.hpp" -namespace edfio -{ +namespace edfio { - // A class created in order to have an easier way to read streams - // of specific data through their respective iterators. - template - class Store : public Device - { - public: - typedef Store store_type; - typedef device_type::iterator iterator; - typedef iterator const const_iterator; +// A class created in order to have an easier way to read streams +// of specific data through their respective iterators. +template +class Store : public Device { +public: + using device_type = Device; + using store_type = Store; + using typename device_type::difference_type; + using typename device_type::pointer; + using typename device_type::reference; + using typename device_type::size_type; + using typename device_type::stream_type; + using typename device_type::value_type; + using iterator = typename device_type::iterator; + using const_iterator = iterator; - Store() = delete; + Store() = delete; - Store(stream_type &stream) - : device_type(stream) - { - } - }; + Store(stream_type &stream) : device_type(stream) {} +}; -} +} // namespace edfio diff --git a/include/edfio/store/StoreUtils.hpp b/include/edfio/store/StoreUtils.hpp new file mode 100644 index 0000000..386fe84 --- /dev/null +++ b/include/edfio/store/StoreUtils.hpp @@ -0,0 +1,78 @@ +// +// Copyright(c) 2017-present Iuri Dotta (dotta dot iuri at gmail dot com) +// +// This source code is licensed under the MIT license found in the +// LICENSE file in the root directory of this source tree. +// +// Official repository: https://github.com/idotta/edfio +// + +#pragma once + +#include "../header/HeaderGeneral.hpp" +#include "../header/HeaderSignal.hpp" +#include "DataRecordStore.hpp" +#include "SignalRecordStore.hpp" +#include "SignalSampleStore.hpp" +#include "TimeStampStore.hpp" + + +namespace edfio { + +namespace detail { + +template +inline DataRecordStore CreateDataRecordStore(Stream &stream, + const HeaderGeneral &general) { + DataRecordStore::size_type recordSize = general.m_detail.m_recordSize; + DataRecordStore::size_type storeSize = general.m_datarecordsFile; + std::streamoff headerSize = general.m_headerSize; + return DataRecordStore{stream, recordSize, storeSize, headerSize}; +} + +template +inline SignalRecordStore CreateSignalRecordStore(Stream &stream, + const HeaderGeneral &general, + const HeaderSignal &signal) { + SignalRecordStore::size_type recordSize = general.m_detail.m_recordSize; + SignalRecordStore::size_type storeSize = general.m_datarecordsFile; + std::streamoff headerSize = general.m_headerSize; + SignalRecordStore::size_type signalSize = + signal.m_samplesInDataRecord * GetSampleBytes(general.m_version); + std::streamoff signalOff = signal.m_detail.m_signalOffset; + return SignalRecordStore{stream, signalSize, storeSize, + headerSize, recordSize, signalOff}; +} + +template +inline SignalSampleStore CreateSignalSampleStore(Stream &stream, + const HeaderGeneral &general, + const HeaderSignal &signal) { + SignalSampleStore::size_type recordSize = general.m_detail.m_recordSize; + SignalSampleStore::size_type storeSize = + general.m_datarecordsFile * signal.m_samplesInDataRecord; + std::streamoff headerSize = general.m_headerSize; + SignalSampleStore::size_type sampleSize = GetSampleBytes(general.m_version); + SignalSampleStore::size_type signalSize = signal.m_samplesInDataRecord; + std::streamoff signalOff = signal.m_detail.m_signalOffset; + return SignalSampleStore{stream, sampleSize, storeSize, headerSize, + recordSize, signalSize, signalOff}; +} + +template +inline TimeStampStore CreateTimeStampStore(Stream &stream, + const HeaderGeneral &general, + const HeaderSignal &signal) { + TimeStampStore::size_type recordSize = general.m_detail.m_recordSize; + TimeStampStore::size_type storeSize = general.m_datarecordsFile; + std::streamoff headerSize = general.m_headerSize; + TimeStampStore::size_type signalSize = + signal.m_samplesInDataRecord * GetSampleBytes(general.m_version); + std::streamoff signalOff = signal.m_detail.m_signalOffset; + return TimeStampStore{stream, signalSize, storeSize, + headerSize, recordSize, signalOff}; +} + +} // namespace detail + +} // namespace edfio \ No newline at end of file diff --git a/include/edfio/store/TalStore.hpp b/include/edfio/store/TalStore.hpp index b6c9a5a..85eefe1 100644 --- a/include/edfio/store/TalStore.hpp +++ b/include/edfio/store/TalStore.hpp @@ -9,255 +9,188 @@ #pragma once -#include "Store.hpp" #include "../core/Record.hpp" +#include "Store.hpp" -#include #include -namespace edfio -{ - - // TAL - Timestamped Annotation List - // TalStore is a particular kind of Store which iterates - // through a SignalRecordStore corresponding to an Annotation signal - // and dereferences a TAL - class TalStore : public Store::VectorType, Record::VectorType const*, Record::VectorType const&, const Record, std::bidirectional_iterator_tag> - { - public: - - class iterator : public store_type::iterator - { - friend class TalStore; - size_type m_offset = 0; // Absolute position in current Store - TalStore *m_context = nullptr; - public: - - // Construction - iterator() = default; - - protected: - iterator(TalStore *context, size_type off) - : m_context(context) - , m_offset(off) - { - if (m_offset == 0) - ++*this; - } - - public: - iterator(const iterator &it) - : m_context(it.m_context) - , m_offset(it.m_offset) - { - } - - // Assignment - iterator& operator=(const iterator &it) - { - m_context = it.m_context; - m_offset = it.m_offset; - return *this; - } - - // Equality - bool operator==(const iterator &it) const - { - return (m_offset == it.m_offset && m_context == it.m_context); - } - bool operator!=(const iterator &it) const - { - return !(*this == it); - } - - // Pre-increment - iterator& operator++() - { - if (!m_context) - throw std::invalid_argument("Invalid context"); - - m_offset = m_context->next(m_offset); - return *this; - } - // Post-increment - iterator operator++(int) - { - if (!m_context) - throw std::invalid_argument("Invalid context"); - iterator tmp = *this; - ++*this; - return tmp; - } - // Pre-decrement - iterator& operator--() - { - if (!m_context) - throw std::invalid_argument("Invalid context"); - - m_offset = m_context->prev(m_offset); - return *this; - } - // Post-decrement - iterator operator--(int) - { - if (!m_context) - throw std::invalid_argument("Invalid context"); - iterator tmp = *this; - --*this; - return tmp; - } - - // Dereference - reference operator*() const - { - if (!m_context) - throw std::invalid_argument("Invalid context"); - return m_context->getR(); - } - pointer operator->() const - { - if (!m_context) - throw std::invalid_argument("Invalid context"); - return m_context->getP(); - } - }; - - typedef iterator const const_iterator; - typedef std::reverse_iterator reverse_iterator; - typedef std::reverse_iterator const_reverse_iterator; - - TalStore() = delete; - - TalStore(stream_type &stream) - : store_type(stream) - { - } - - iterator begin() - { - return iterator(this, 0); - } - const_iterator begin() const - { - return const_iterator(const_cast(this), 0); - } - const_iterator cbegin() const - { - return const_iterator(const_cast(this), 0); - } - iterator end() - { - return iterator(this, m_stream.Size()); - } - const_iterator end() const - { - return const_iterator(const_cast(this), m_stream.Size()); - } - const_iterator cend() const - { - return const_iterator(const_cast(this), m_stream.Size()); - } - reverse_iterator rbegin() - { - return reverse_iterator(end()); - } - const_reverse_iterator rbegin() const - { - return const_reverse_iterator(end()); - } - const_reverse_iterator crbegin() const - { - return const_reverse_iterator(cend()); - } - reverse_iterator rend() - { - return reverse_iterator(begin()); - } - const_reverse_iterator rend() const - { - return const_reverse_iterator(begin()); - } - const_reverse_iterator crend() const - { - return const_reverse_iterator(cbegin()); - } - - protected: - reference getR() - { - return m_value; - } - - pointer getP() - { - return &m_value; - } - - size_type next(size_type off) - { - if (off >= m_stream().size()) - throw std::length_error("Iterator not incrementable"); - - if (off < m_stream().size()) - { - auto first = m_stream().begin() + off; - auto last = m_stream().end(); - - while (first != last && *first == 0) - { - first++; - off++; - } - - if (first != last) - { - size_type offOld = off; - for (auto it = first; *it != 0 && it != last; it++) - { - off++; - } - if (offOld != off) - { - m_value.assign(first, first + (off - offOld)); - } - } - } - return off; - } - - size_type prev(size_type off) - { - if (off <= 0) - throw std::length_error("Iterator not decrementable"); - - if (off > 0) - { - auto first = m_stream().rend() + off; - auto last = m_stream().rend(); - - while (*first == 0 && first != last) - { - first++; - off--; - } - - if (first != last) - { - size_type offOld = off; - for (auto it = first; *it != 0 && it != last; it++) - { - off--; - } - if (offOld != off) - { - m_value.assign(first + offOld, first + off); - } - } - } - return off; - } - - value_type m_value; - }; - -} +namespace edfio { + +// TAL - Timestamped Annotation List +// TalStore is a particular kind of Store which iterates +// through a SignalRecordStore corresponding to an Annotation signal +// and dereferences a TAL +class TalStore + : public Store::VectorType, Record::VectorType const *, + Record::VectorType const &, const Record, + std::bidirectional_iterator_tag> { + using base_store = + Store::VectorType, Record::VectorType const *, + Record::VectorType const &, const Record, + std::bidirectional_iterator_tag>; + +public: + using typename base_store::difference_type; + using typename base_store::pointer; + using typename base_store::reference; + using typename base_store::size_type; + using typename base_store::stream_type; + using typename base_store::value_type; + + class iterator : public base_store::iterator { + friend class TalStore; + size_type m_offset = 0; // Absolute position in current Store + const TalStore *m_context = nullptr; + + public: + // Construction + iterator() = default; + + protected: + iterator(const TalStore *context, size_type off) + : m_offset(off), m_context(context) { + if (m_offset == 0) + ++*this; + } + + public: + iterator(const iterator &it) + : m_offset(it.m_offset), m_context(it.m_context) {} + + // Assignment + iterator &operator=(const iterator &it) { + m_context = it.m_context; + m_offset = it.m_offset; + return *this; + } + + // Equality (!= auto-generated) + bool operator==(const iterator &it) const { + return (m_offset == it.m_offset && m_context == it.m_context); + } + + // Pre-increment + iterator &operator++() { + if (!m_context) + throw std::invalid_argument("Invalid context"); + + m_offset = m_context->next(m_offset); + return *this; + } + // Post-increment + iterator operator++(int) { + if (!m_context) + throw std::invalid_argument("Invalid context"); + iterator tmp = *this; + ++*this; + return tmp; + } + // Pre-decrement + iterator &operator--() { + if (!m_context) + throw std::invalid_argument("Invalid context"); + + m_offset = m_context->prev(m_offset); + return *this; + } + // Post-decrement + iterator operator--(int) { + if (!m_context) + throw std::invalid_argument("Invalid context"); + iterator tmp = *this; + --*this; + return tmp; + } + + // Dereference + reference operator*() const { + if (!m_context) + throw std::invalid_argument("Invalid context"); + return m_context->getR(); + } + pointer operator->() const { + if (!m_context) + throw std::invalid_argument("Invalid context"); + return m_context->getP(); + } + }; + + using const_iterator = iterator; + using reverse_iterator = std::reverse_iterator; + using const_reverse_iterator = std::reverse_iterator; + + TalStore() = delete; + + TalStore(stream_type &stream) : store_type(stream) {} + + iterator begin() const { return iterator(this, 0); } + const_iterator cbegin() const { return begin(); } + iterator end() const { return iterator(this, m_stream.Size()); } + const_iterator cend() const { return end(); } + reverse_iterator rbegin() const { return reverse_iterator(end()); } + const_reverse_iterator crbegin() const { + return const_reverse_iterator(cend()); + } + reverse_iterator rend() const { return reverse_iterator(begin()); } + const_reverse_iterator crend() const { + return const_reverse_iterator(cbegin()); + } + +protected: + reference getR() const { return m_value; } + + pointer getP() const { return &m_value; } + + size_type next(size_type off) const { + if (off >= m_stream().size()) + throw std::length_error("Iterator not incrementable"); + + if (off < m_stream().size()) { + auto first = m_stream().begin() + off; + auto last = m_stream().end(); + + while (first != last && *first == 0) { + first++; + off++; + } + + if (first != last) { + size_type offOld = off; + for (auto it = first; *it != 0 && it != last; it++) { + off++; + } + if (offOld != off) { + m_value.assign(first, first + (off - offOld)); + } + } + } + return off; + } + + size_type prev(size_type off) const { + if (off == 0) + throw std::length_error("Iterator not decrementable"); + + auto const &data = m_stream(); + + // Walk backward from position (off - 1), skipping zeros + size_type pos = off; + while (pos > 0 && data[pos - 1] == 0) + --pos; + + if (pos == 0) + throw std::length_error("Iterator not decrementable"); + + // Find the start of the previous non-zero TAL + size_type end_of_tal = pos; + while (pos > 0 && data[pos - 1] != 0) + --pos; + + m_value.assign(data.begin() + pos, data.begin() + end_of_tal); + return pos; + } + + mutable value_type m_value; +}; + +} // namespace edfio diff --git a/include/edfio/store/TimeStampStore.hpp b/include/edfio/store/TimeStampStore.hpp index fae7a71..2a5311d 100644 --- a/include/edfio/store/TimeStampStore.hpp +++ b/include/edfio/store/TimeStampStore.hpp @@ -11,51 +11,42 @@ #include "RecordStore.hpp" -namespace edfio -{ - - class TimeStampStore : public RecordStore - { - public: - - typedef RecordStore::iterator iterator; - typedef iterator const const_iterator; - typedef std::reverse_iterator reverse_iterator; //optional - typedef std::reverse_iterator const_reverse_iterator; //optional - - TimeStampStore() = delete; - - TimeStampStore(stream_type &stream, size_type recordSize, size_type storeSize, - std::streamoff headerOffset, size_type datarecordSize, std::streamoff signalOffset) - : RecordStore(stream, recordSize, storeSize, headerOffset) - , m_datarecordSize(datarecordSize) - , m_signalOffset(signalOffset) - { - } - - protected: - - void load(size_type off) override - { - if (off < 0 || off >= size()) - { - throw std::out_of_range("Iterator not dereferenceable"); - } - - if (!m_stream.good()) - m_stream.clear(); - - auto currentPos = m_stream.tellg(); - auto destPos = m_headerOffset + m_datarecordSize * off + m_signalOffset; - if (destPos != currentPos) - { - m_stream.seekg(destPos, std::ios::beg); - } - m_stream.getline(m_value().data(), m_datarecordSize, 20); - } - - size_type m_datarecordSize; - std::streamoff m_signalOffset; - }; - -} +namespace edfio { + +class TimeStampStore : public RecordStore { +public: + using iterator = RecordStore::iterator; + using const_iterator = iterator; + using reverse_iterator = std::reverse_iterator; + using const_reverse_iterator = std::reverse_iterator; + + TimeStampStore() = delete; + + TimeStampStore(stream_type &stream, size_type recordSize, size_type storeSize, + std::streamoff headerOffset, size_type datarecordSize, + std::streamoff signalOffset) + : RecordStore(stream, recordSize, storeSize, headerOffset), + m_datarecordSize(datarecordSize), m_signalOffset(signalOffset) {} + +protected: + void load(size_type off) const override { + if (off >= size()) { + throw std::out_of_range("Iterator not dereferenceable"); + } + + if (!m_stream.good()) + m_stream.clear(); + + auto currentPos = m_stream.tellg(); + auto destPos = m_headerOffset + m_datarecordSize * off + m_signalOffset; + if (destPos != currentPos) { + m_stream.seekg(destPos, std::ios::beg); + } + m_stream.getline(m_value().data(), m_datarecordSize, 20); + } + + size_type m_datarecordSize; + std::streamoff m_signalOffset; +}; + +} // namespace edfio diff --git a/include/edfio/store/detail/StoreUtils.hpp b/include/edfio/store/detail/StoreUtils.hpp deleted file mode 100644 index 2569541..0000000 --- a/include/edfio/store/detail/StoreUtils.hpp +++ /dev/null @@ -1,72 +0,0 @@ -// -// Copyright(c) 2017-present Iuri Dotta (dotta dot iuri at gmail dot com) -// -// This source code is licensed under the MIT license found in the -// LICENSE file in the root directory of this source tree. -// -// Official repository: https://github.com/idotta/edfio -// - -#pragma once - -#include "../DataRecordStore.hpp" -#include "../SignalRecordStore.hpp" -#include "../SignalSampleStore.hpp" -#include "../TimeStampStore.hpp" -#include "../../header/HeaderGeneral.hpp" -#include "../../header/HeaderSignal.hpp" - -#include - -namespace edfio -{ - - namespace detail - { - - template - static DataRecordStore CreateDataRecordStore(Stream &stream, const HeaderGeneral &general) - { - DataRecordStore::size_type recordSize = general.m_detail.m_recordSize; - DataRecordStore::size_type storeSize = general.m_datarecordsFile; - std::streamoff headerSize = general.m_headerSize; - return std::move(DataRecordStore{ stream, recordSize, storeSize, headerSize }); - } - - template - static SignalRecordStore CreateSignalRecordStore(Stream &stream, const HeaderGeneral &general, const HeaderSignal &signal) - { - SignalRecordStore::size_type recordSize = general.m_detail.m_recordSize; - SignalRecordStore::size_type storeSize = general.m_datarecordsFile; - std::streamoff headerSize = general.m_headerSize; - SignalRecordStore::size_type signalSize = signal.m_samplesInDataRecord * GetSampleBytes(general.m_version); - std::streamoff signalOff = signal.m_detail.m_signalOffset; - return std::move(SignalRecordStore{ stream, signalSize, storeSize, headerSize, recordSize, signalOff }); - } - - template - static SignalSampleStore CreateSignalSampleStore(Stream &stream, const HeaderGeneral &general, const HeaderSignal &signal) - { - SignalSampleStore::size_type recordSize = general.m_detail.m_recordSize; - SignalSampleStore::size_type storeSize = general.m_datarecordsFile * signal.m_samplesInDataRecord; - std::streamoff headerSize = general.m_headerSize; - SignalSampleStore::size_type sampleSize = GetSampleBytes(general.m_version); - SignalSampleStore::size_type signalSize = signal.m_samplesInDataRecord; - std::streamoff signalOff = signal.m_detail.m_signalOffset; - return std::move(SignalSampleStore{ stream, sampleSize, storeSize, headerSize, recordSize, signalSize, signalOff }); - } - - template - static TimeStampStore CreateTimeStampStore(Stream &stream, const HeaderGeneral &general, const HeaderSignal &signal) - { - TimeStampStore::size_type recordSize = general.m_detail.m_recordSize; - TimeStampStore::size_type storeSize = general.m_datarecordsFile; - std::streamoff headerSize = general.m_headerSize; - TimeStampStore::size_type signalSize = signal.m_samplesInDataRecord * GetSampleBytes(general.m_version); - std::streamoff signalOff = signal.m_detail.m_signalOffset; - return std::move(TimeStampStore{ stream, signalSize, storeSize, headerSize, recordSize, signalOff }); - } - - } - -} \ No newline at end of file diff --git a/include/edfio/writer/WriterHeaderExam.hpp b/include/edfio/writer/WriterHeaderExam.hpp index 9741af6..9c90931 100644 --- a/include/edfio/writer/WriterHeaderExam.hpp +++ b/include/edfio/writer/WriterHeaderExam.hpp @@ -9,19 +9,30 @@ #pragma once -#include "../header/HeaderExam.hpp" +#include "../Errors.hpp" #include "../core/StreamIO.hpp" +#include "../header/HeaderExam.hpp" +#include "../processor/ProcessorHeaderGeneral.hpp" +#include "../processor/ProcessorHeaderSignal.hpp" +#include "WriterHeaderGeneral.hpp" +#include "WriterHeaderSignals.hpp" #include -namespace edfio -{ +namespace edfio { + +inline void WriteHeaderExam(Writer::Stream &stream, const HeaderExam &input) { + // Process header general + auto general = ProcessHeaderGeneral(input.m_general); + + // Process signal fields + auto signals = ProcessHeaderSignal(input.m_signals); - struct WriterHeaderExam : Writer - { - void operator ()(Stream &stream, HeaderExam &input); - }; + // Write general + WriteHeaderGeneral(stream, general); + // Write signals + WriteHeaderSignals(stream, signals); } -#include "impl/WriterHeaderExam.ipp" +} // namespace edfio diff --git a/include/edfio/writer/WriterHeaderGeneral.hpp b/include/edfio/writer/WriterHeaderGeneral.hpp index 3fe0dc3..b25e078 100644 --- a/include/edfio/writer/WriterHeaderGeneral.hpp +++ b/include/edfio/writer/WriterHeaderGeneral.hpp @@ -9,19 +9,37 @@ #pragma once -#include "../header/HeaderGeneral.hpp" +#include "../Errors.hpp" #include "../core/StreamIO.hpp" +#include "../header/HeaderGeneral.hpp" +#include #include -namespace edfio -{ +namespace edfio { + +inline void WriteHeaderGeneral(Writer::Stream &stream, const HeaderGeneralFields &input) { + auto &hdr = input; + if (!stream || !stream.is_open()) + throw std::invalid_argument(GetError(FileErrc::FileNotOpened)); - struct WriterHeaderGeneral : Writer - { - void operator ()(Stream &stream, HeaderGeneralFields &input); - }; + stream.clear(); + stream.seekp(0, std::ios::beg); + try { + stream << hdr.m_version; + stream << hdr.m_patient; + stream << hdr.m_recording; + stream << hdr.m_startDate; + stream << hdr.m_startTime; + stream << hdr.m_headerSize; + stream << hdr.m_reserved; + stream << hdr.m_datarecordsFile; + stream << hdr.m_datarecordDuration; + stream << hdr.m_totalSignals; + } catch (const std::exception &) { + throw std::invalid_argument(GetError(FileErrc::FileWriteError)); + } } -#include "impl/WriterHeaderGeneral.ipp" +} // namespace edfio diff --git a/include/edfio/writer/WriterHeaderSignals.hpp b/include/edfio/writer/WriterHeaderSignals.hpp index 9550deb..82df7a0 100644 --- a/include/edfio/writer/WriterHeaderSignals.hpp +++ b/include/edfio/writer/WriterHeaderSignals.hpp @@ -9,19 +9,46 @@ #pragma once +#include "../Errors.hpp" #include "../core/StreamIO.hpp" #include "../header/HeaderSignal.hpp" -#include +#include +#include -namespace edfio -{ +namespace edfio { - struct WriterHeaderSignals : Writer - { - void operator ()(Stream &stream, std::vector &signals); - }; +inline void WriteHeaderSignals(Writer::Stream &stream, + std::span signals) { + if (!stream || !stream.is_open()) + throw std::invalid_argument(GetError(FileErrc::FileNotOpened)); + try { + stream.clear(); + stream.seekp(256, std::ios::beg); + for (auto &s : signals) + stream << s.m_label; + for (auto &s : signals) + stream << s.m_transducer; + for (auto &s : signals) + stream << s.m_physDimension; + for (auto &s : signals) + stream << s.m_physicalMin; + for (auto &s : signals) + stream << s.m_physicalMax; + for (auto &s : signals) + stream << s.m_digitalMin; + for (auto &s : signals) + stream << s.m_digitalMax; + for (auto &s : signals) + stream << s.m_prefilter; + for (auto &s : signals) + stream << s.m_samplesInDataRecord; + for (auto &s : signals) + stream << s.m_reserved; + } catch (const std::exception &) { + throw std::invalid_argument(GetError(FileErrc::FileWriteError)); + } } -#include "impl/WriterHeaderSignals.ipp" +} // namespace edfio diff --git a/include/edfio/writer/WriterRecord.hpp b/include/edfio/writer/WriterRecord.hpp deleted file mode 100644 index e685380..0000000 --- a/include/edfio/writer/WriterRecord.hpp +++ /dev/null @@ -1,25 +0,0 @@ -// -// Copyright(c) 2017-present Iuri Dotta (dotta dot iuri at gmail dot com) -// -// This source code is licensed under the MIT license found in the -// LICENSE file in the root directory of this source tree. -// -// Official repository: https://github.com/idotta/edfio -// - -#pragma once - -#include "../core/StreamIO.hpp" -#include "../core/Record.hpp" - -namespace edfio -{ - - struct WriterRecord : Writer - { - void operator ()(Stream &stream, Record &record); - }; - -} - -#include "impl/WriterRecord.ipp" diff --git a/include/edfio/writer/impl/WriterHeaderExam.ipp b/include/edfio/writer/impl/WriterHeaderExam.ipp deleted file mode 100644 index 62031cc..0000000 --- a/include/edfio/writer/impl/WriterHeaderExam.ipp +++ /dev/null @@ -1,40 +0,0 @@ -// -// Copyright(c) 2017-present Iuri Dotta (dotta dot iuri at gmail dot com) -// -// This source code is licensed under the MIT license found in the -// LICENSE file in the root directory of this source tree. -// -// Official repository: https://github.com/idotta/edfio -// - -#pragma once - -#include "../../Utils.hpp" -#include "../../header/HeaderExam.hpp" -#include "../WriterHeaderGeneral.hpp" -#include "../WriterHeaderSignals.hpp" -#include "../../processor/ProcessorHeaderGeneral.hpp" -#include "../../processor/ProcessorHeaderSignal.hpp" - -#include -#include - -namespace edfio -{ - - inline void WriterHeaderExam::operator ()(Stream &stream, HeaderExam &input) - { - // Process header general - auto general = std::move(ProcessorHeaderGeneral{}(input.m_general)); - - // Process signal fields - auto signals = std::move(ProcessorHeaderSignal{}(input.m_signals)); - - // Write general - WriterHeaderGeneral{}(stream, std::move(general)); - - // Write signals - WriterHeaderSignals{}(stream, std::move(signals)); - } - -} diff --git a/include/edfio/writer/impl/WriterHeaderGeneral.ipp b/include/edfio/writer/impl/WriterHeaderGeneral.ipp deleted file mode 100644 index 4e1bfa3..0000000 --- a/include/edfio/writer/impl/WriterHeaderGeneral.ipp +++ /dev/null @@ -1,50 +0,0 @@ -// -// Copyright(c) 2017-present Iuri Dotta (dotta dot iuri at gmail dot com) -// -// This source code is licensed under the MIT license found in the -// LICENSE file in the root directory of this source tree. -// -// Official repository: https://github.com/idotta/edfio -// - -#pragma once - -#include "../../Utils.hpp" -#include "../../header/HeaderGeneral.hpp" - -#include -#include -#include - -namespace edfio -{ - - inline void WriterHeaderGeneral::operator()(Stream & stream, HeaderGeneralFields & input) - { - auto &hdr = input; - if (!stream || !stream.is_open()) - throw std::invalid_argument(detail::GetError(FileErrc::FileNotOpened)); - - stream.clear(); - stream.seekp(0, std::ios::beg); - - try - { - stream << hdr.m_version; - stream << hdr.m_patient; - stream << hdr.m_recording; - stream << hdr.m_startDate; - stream << hdr.m_startTime; - stream << hdr.m_headerSize; - stream << hdr.m_reserved; - stream << hdr.m_datarecordsFile; - stream << hdr.m_datarecordDuration; - stream << hdr.m_totalSignals; - } - catch (std::exception e) - { - throw std::invalid_argument(detail::GetError(FileErrc::FileWriteError)); - } - } - -} diff --git a/include/edfio/writer/impl/WriterHeaderSignals.ipp b/include/edfio/writer/impl/WriterHeaderSignals.ipp deleted file mode 100644 index 425e448..0000000 --- a/include/edfio/writer/impl/WriterHeaderSignals.ipp +++ /dev/null @@ -1,58 +0,0 @@ -// -// Copyright(c) 2017-present Iuri Dotta (dotta dot iuri at gmail dot com) -// -// This source code is licensed under the MIT license found in the -// LICENSE file in the root directory of this source tree. -// -// Official repository: https://github.com/idotta/edfio -// - -#pragma once - -#include "../../Utils.hpp" -#include "../../header/HeaderSignal.hpp" - -#include -#include -#include - -namespace edfio -{ - - inline void WriterHeaderSignals::operator()(Stream &stream, std::vector &signals) - { - if (!stream || !stream.is_open()) - throw std::invalid_argument(detail::GetError(FileErrc::FileNotOpened)); - try - { - stream.clear(); - stream.seekp(256, std::ios::beg); - - for (auto &s : signals) - stream << s.m_label; - for (auto &s : signals) - stream << s.m_transducer; - for (auto &s : signals) - stream << s.m_physDimension; - for (auto &s : signals) - stream << s.m_physicalMin; - for (auto &s : signals) - stream << s.m_physicalMax; - for (auto &s : signals) - stream << s.m_digitalMin; - for (auto &s : signals) - stream << s.m_digitalMax; - for (auto &s : signals) - stream << s.m_prefilter; - for (auto &s : signals) - stream << s.m_samplesInDataRecord; - for (auto &s : signals) - stream << s.m_reserved; - } - catch (std::exception e) - { - throw std::invalid_argument(detail::GetError(FileErrc::FileWriteError)); - } - } - -} diff --git a/include/edfio/writer/impl/WriterRecord.ipp b/include/edfio/writer/impl/WriterRecord.ipp deleted file mode 100644 index 7bf425a..0000000 --- a/include/edfio/writer/impl/WriterRecord.ipp +++ /dev/null @@ -1,35 +0,0 @@ -// -// Copyright(c) 2017-present Iuri Dotta (dotta dot iuri at gmail dot com) -// -// This source code is licensed under the MIT license found in the -// LICENSE file in the root directory of this source tree. -// -// Official repository: https://github.com/idotta/edfio -// - -#pragma once - -#include "../../Utils.hpp" -#include "../../core/Record.hpp" - -#include - -namespace edfio -{ - - inline void WriterRecord::operator()(Stream &stream, Record &record) - { - if (!stream || !stream.is_open()) - throw std::invalid_argument(detail::GetError(FileErrc::FileNotOpened)); - - try - { - stream << record; - } - catch (std::exception e) - { - throw std::invalid_argument(detail::GetError(FileErrc::FileWriteError)); - } - } - -} diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt new file mode 100644 index 0000000..7fee75d --- /dev/null +++ b/tests/CMakeLists.txt @@ -0,0 +1,51 @@ +# doctest as a header-only INTERFACE library from third_party/ +add_library(doctest INTERFACE) +target_include_directories(doctest INTERFACE ${CMAKE_SOURCE_DIR}/third_party) + +# Convenience function: one call per test source file +function(edfio_add_test name) + add_executable(${name} ${name}.cpp) + target_link_libraries(${name} PRIVATE edfio doctest) + if(MSVC) + target_compile_options(${name} PRIVATE /W4 /permissive-) + else() + target_compile_options(${name} PRIVATE + -Wall -Wextra -Wpedantic -Wno-c++98-compat + ) + endif() + add_test(NAME ${name} COMMAND ${name}) +endfunction() + +# Copy test fixtures from files/ directory +configure_file( + ${CMAKE_SOURCE_DIR}/files/Calib5.edf + ${CMAKE_CURRENT_BINARY_DIR}/Calib5.edf + COPYONLY +) +configure_file( + ${CMAKE_SOURCE_DIR}/files/test_generator_2.edf + ${CMAKE_CURRENT_BINARY_DIR}/test_generator_2.edf + COPYONLY +) +configure_file( + ${CMAKE_SOURCE_DIR}/files/test_generator_2.bdf + ${CMAKE_CURRENT_BINARY_DIR}/test_generator_2.bdf + COPYONLY +) +configure_file( + ${CMAKE_SOURCE_DIR}/files/SC4001EC-Hypnogram.edf + ${CMAKE_CURRENT_BINARY_DIR}/SC4001EC-Hypnogram.edf + COPYONLY +) + +# --- Test executables --- +edfio_add_test(test_record) +edfio_add_test(test_reader) +edfio_add_test(test_processor_sample) +edfio_add_test(test_iterators) +edfio_add_test(test_writer) +edfio_add_test(test_processor_utils) +edfio_add_test(test_bdf_reader) +edfio_add_test(test_processors) +edfio_add_test(test_edfplus) +edfio_add_test(test_edffile) diff --git a/tests/test_bdf_reader.cpp b/tests/test_bdf_reader.cpp new file mode 100644 index 0000000..a019a6a --- /dev/null +++ b/tests/test_bdf_reader.cpp @@ -0,0 +1,307 @@ +#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN +#include +#include +#include +#include + +using namespace edfio; + +// BDF 24-bit signed integer limits +static constexpr int32_t BDF_DIGITAL_MIN = -8388608; // -(2^23) +static constexpr int32_t BDF_DIGITAL_MAX = 8388607; // (2^23) - 1 + +// --------------------------------------------------------------------------- +// 1. Read BDF header successfully +// --------------------------------------------------------------------------- +TEST_CASE("Read BDF header successfully") { + std::ifstream stream("test_generator_2.bdf", std::ios::binary); + REQUIRE(stream.is_open()); + + auto header = ReadHeaderExam(stream); + + CHECK(header.m_general.m_totalSignals > 0); + CHECK(header.m_general.m_headerSize > 0); + CHECK(header.m_general.m_datarecordsFile > 0); + CHECK(header.m_general.m_datarecordDuration > 0.0); + CHECK(header.m_signals.size() == + static_cast(header.m_general.m_totalSignals)); +} + +// --------------------------------------------------------------------------- +// 2. BDF format detection +// --------------------------------------------------------------------------- +TEST_CASE("BDF format detection") { + std::ifstream stream("test_generator_2.bdf", std::ios::binary); + REQUIRE(stream.is_open()); + + auto header = ReadHeaderExam(stream); + + CHECK(IsBdf(header.m_general.m_version)); + CHECK_FALSE(IsEdf(header.m_general.m_version)); + CHECK(GetSampleBytes(header.m_general.m_version) == 3); +} + +// --------------------------------------------------------------------------- +// 3. BDF signal headers valid +// --------------------------------------------------------------------------- +TEST_CASE("BDF signal headers valid") { + std::ifstream stream("test_generator_2.bdf", std::ios::binary); + REQUIRE(stream.is_open()); + + auto header = ReadHeaderExam(stream); + REQUIRE(header.m_signals.size() > 0); + + for (auto const &sig : header.m_signals) { + CHECK(sig.m_samplesInDataRecord > 0); + CHECK(sig.m_digitalMax > sig.m_digitalMin); + // BDF digital range must fit within 24-bit signed bounds + CHECK(sig.m_digitalMin >= BDF_DIGITAL_MIN); + CHECK(sig.m_digitalMax <= BDF_DIGITAL_MAX); + // Physical range must be valid + CHECK(sig.m_physicalMax > sig.m_physicalMin); + // Label should not be empty + CHECK_FALSE(sig.m_label.empty()); + } +} + +// --------------------------------------------------------------------------- +// 4. BDF data record iteration +// --------------------------------------------------------------------------- +TEST_CASE("BDF data record iteration") { + std::ifstream stream("test_generator_2.bdf", std::ios::binary); + REQUIRE(stream.is_open()); + + auto header = ReadHeaderExam(stream); + auto store = detail::CreateDataRecordStore(stream, header.m_general); + + CHECK(store.size() == + static_cast(header.m_general.m_datarecordsFile)); + CHECK(store.size() > 0); + + // Iterate the first few data records and verify they have content + uint32_t count = 0; + auto limit = std::min(store.size(), + static_cast(5)); + for (auto it = store.begin(); it != store.begin() + static_cast(limit); ++it) { + auto const &rec = *it; + CHECK(rec.Size() > 0); + // Each data record should be recordSize bytes + CHECK(rec.Size() == header.m_general.m_detail.m_recordSize); + ++count; + } + CHECK(count == limit); +} + +// --------------------------------------------------------------------------- +// 5. BDF signal record iteration +// --------------------------------------------------------------------------- +TEST_CASE("BDF signal record iteration") { + std::ifstream stream("test_generator_2.bdf", std::ios::binary); + REQUIRE(stream.is_open()); + + auto header = ReadHeaderExam(stream); + REQUIRE(header.m_signals.size() > 0); + + auto const &sig = header.m_signals[0]; + auto store = detail::CreateSignalRecordStore(stream, header.m_general, sig); + + CHECK(store.size() == + static_cast(header.m_general.m_datarecordsFile)); + + // Iterate first few signal records + uint32_t count = 0; + auto limit = std::min(store.size(), + static_cast(5)); + for (auto it = store.begin(); it != store.begin() + static_cast(limit); ++it) { + auto const &rec = *it; + CHECK(rec.Size() > 0); + // Signal record size = samplesInDataRecord * sampleBytes + auto expectedSize = static_cast(sig.m_samplesInDataRecord) * + static_cast(GetSampleBytes(header.m_general.m_version)); + CHECK(rec.Size() == expectedSize); + ++count; + } + CHECK(count == limit); +} + +// --------------------------------------------------------------------------- +// 6. BDF signal sample store +// --------------------------------------------------------------------------- +TEST_CASE("BDF signal sample store") { + std::ifstream stream("test_generator_2.bdf", std::ios::binary); + REQUIRE(stream.is_open()); + + auto header = ReadHeaderExam(stream); + REQUIRE(header.m_signals.size() > 0); + + auto const &sig = header.m_signals[0]; + auto sampleStore = detail::CreateSignalSampleStore(stream, header.m_general, sig); + + auto expectedSize = static_cast(header.m_general.m_datarecordsFile) * + static_cast(sig.m_samplesInDataRecord); + CHECK(sampleStore.size() == expectedSize); + CHECK(sampleStore.size() > 0); +} + +// --------------------------------------------------------------------------- +// 7. BDF sample reading - digital values in valid 24-bit signed range +// --------------------------------------------------------------------------- +TEST_CASE("BDF sample reading - digital values in 24-bit range") { + std::ifstream stream("test_generator_2.bdf", std::ios::binary); + REQUIRE(stream.is_open()); + + auto header = ReadHeaderExam(stream); + REQUIRE(header.m_signals.size() > 0); + + auto const &sig = header.m_signals[0]; + auto sampleStore = detail::CreateSignalSampleStore(stream, header.m_general, sig); + REQUIRE(sampleStore.size() > 0); + + // Digital processor: offset=0, scaling=1 gives raw digital value + ProcessorSampleRecord proc(0.0, 1.0); + + // Read the first N samples and verify they are within 24-bit signed range + auto limit = std::min(sampleStore.size(), + static_cast(100)); + for (auto it = sampleStore.begin(); + it != sampleStore.begin() + static_cast(limit); ++it) { + auto const &sampleRec = *it; + CHECK(sampleRec.Size() == 3); // BDF: 3 bytes per sample + + int32_t digitalVal = proc(sampleRec); + CHECK(digitalVal >= BDF_DIGITAL_MIN); + CHECK(digitalVal <= BDF_DIGITAL_MAX); + } +} + +// --------------------------------------------------------------------------- +// 8. BDF physical sample conversion +// --------------------------------------------------------------------------- +TEST_CASE("BDF physical sample conversion") { + std::ifstream stream("test_generator_2.bdf", std::ios::binary); + REQUIRE(stream.is_open()); + + auto header = ReadHeaderExam(stream); + REQUIRE(header.m_signals.size() > 0); + + auto const &sig = header.m_signals[0]; + auto sampleStore = detail::CreateSignalSampleStore(stream, header.m_general, sig); + REQUIRE(sampleStore.size() > 0); + + // Physical processor uses the signal's calibration parameters + ProcessorSampleRecord physProc( + sig.m_detail.m_offset, sig.m_detail.m_scaling); + + // Verify scaling and offset are reasonable + CHECK(sig.m_detail.m_scaling != 0.0); + + // Read the first N samples and verify physical values fall within the + // declared physical range (with a small tolerance for rounding) + double physMin = sig.m_physicalMin; + double physMax = sig.m_physicalMax; + double tolerance = (physMax - physMin) * 0.001; // 0.1% tolerance + double lowerBound = physMin - tolerance; + double upperBound = physMax + tolerance; + + auto limit = std::min(sampleStore.size(), + static_cast(100)); + for (auto it = sampleStore.begin(); + it != sampleStore.begin() + static_cast(limit); ++it) { + auto const &sampleRec = *it; + double physVal = physProc(sampleRec); + CHECK(physVal >= lowerBound); + CHECK(physVal <= upperBound); + } +} + +// --------------------------------------------------------------------------- +// 9. BDF write and read-back round-trip +// --------------------------------------------------------------------------- +TEST_CASE("BDF write and read-back round-trip") { + // Read original BDF file + std::ifstream instream("test_generator_2.bdf", std::ios::binary); + REQUIRE(instream.is_open()); + auto header = ReadHeaderExam(instream); + instream.close(); + + const char *tmpfile = "test_roundtrip.bdf"; + + // Write header and all data records to a temporary file + { + std::ofstream outstream(tmpfile, std::ios::binary); + REQUIRE(outstream.is_open()); + WriteHeaderExam(outstream, header); + + // Re-open the original for data copy + std::ifstream instream2("test_generator_2.bdf", std::ios::binary); + REQUIRE(instream2.is_open()); + + auto store = detail::CreateDataRecordStore(instream2, header.m_general); + + // Write each data record directly to the output stream + for (auto it = store.begin(); it != store.end(); ++it) { + outstream << *it; + } + } + + // Read back and compare + std::ifstream checkstream(tmpfile, std::ios::binary); + REQUIRE(checkstream.is_open()); + auto header2 = ReadHeaderExam(checkstream); + + // General header fields must match + CHECK(header2.m_general.m_version == header.m_general.m_version); + CHECK(IsBdf(header2.m_general.m_version)); + CHECK(header2.m_general.m_totalSignals == header.m_general.m_totalSignals); + CHECK(header2.m_general.m_datarecordsFile == header.m_general.m_datarecordsFile); + CHECK(header2.m_general.m_datarecordDuration == + doctest::Approx(header.m_general.m_datarecordDuration)); + CHECK(header2.m_general.m_headerSize == header.m_general.m_headerSize); + CHECK(header2.m_general.m_detail.m_recordSize == + header.m_general.m_detail.m_recordSize); + + // Signal headers must match + REQUIRE(header2.m_signals.size() == header.m_signals.size()); + for (size_t i = 0; i < header.m_signals.size(); ++i) { + auto const &orig = header.m_signals[i]; + auto const © = header2.m_signals[i]; + CHECK(copy.m_label == orig.m_label); + CHECK(copy.m_samplesInDataRecord == orig.m_samplesInDataRecord); + CHECK(copy.m_digitalMin == orig.m_digitalMin); + CHECK(copy.m_digitalMax == orig.m_digitalMax); + CHECK(copy.m_physicalMin == doctest::Approx(orig.m_physicalMin)); + CHECK(copy.m_physicalMax == doctest::Approx(orig.m_physicalMax)); + } + + // Verify sample data integrity: compare first few digital samples + { + std::ifstream origStream("test_generator_2.bdf", std::ios::binary); + REQUIRE(origStream.is_open()); + auto origHeader = ReadHeaderExam(origStream); + + auto const &sig = origHeader.m_signals[0]; + auto origSamples = detail::CreateSignalSampleStore( + origStream, origHeader.m_general, sig); + + auto const &sig2 = header2.m_signals[0]; + auto copySamples = detail::CreateSignalSampleStore( + checkstream, header2.m_general, sig2); + + CHECK(copySamples.size() == origSamples.size()); + + ProcessorSampleRecord proc(0.0, 1.0); + + auto limit = std::min(origSamples.size(), + static_cast(50)); + auto origIt = origSamples.begin(); + auto copyIt = copySamples.begin(); + for (uint64_t i = 0; i < limit; ++i, ++origIt, ++copyIt) { + int32_t origVal = proc(*origIt); + int32_t copyVal = proc(*copyIt); + CHECK(copyVal == origVal); + } + } + + checkstream.close(); + std::remove(tmpfile); +} diff --git a/tests/test_edffile.cpp b/tests/test_edffile.cpp new file mode 100644 index 0000000..76e2b13 --- /dev/null +++ b/tests/test_edffile.cpp @@ -0,0 +1,410 @@ +#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN +#include +#include +#include +#include +#include + +using namespace edfio; + +// =========================================================================== +// 1. Open test_generator_2.edf -- format, signal count, duration +// =========================================================================== + +TEST_CASE("EdfFile::open reads test_generator_2.edf successfully") { + auto file = EdfFile::open("test_generator_2.edf"); + + SUBCASE("format is EDF+") { + CHECK(file.format() == DataFormat::EdfPlusC); + CHECK(file.isEdf()); + CHECK(file.isPlus()); + CHECK_FALSE(file.isBdf()); + } + + SUBCASE("signal count matches header") { + CHECK(file.signalCount() == 12); + CHECK(file.signals().size() == 12); + } + + SUBCASE("data record count and duration") { + CHECK(file.dataRecordCount() == 600); + // duration = dataRecordCount * datarecordDuration = 600 * 1.0 = 600 + CHECK(file.duration() == doctest::Approx(600.0)); + } + + SUBCASE("general header is accessible") { + CHECK(file.general().m_headerSize > 0); + CHECK(file.general().m_datarecordDuration == doctest::Approx(1.0)); + CHECK(file.general().m_startDate.day == 10); + CHECK(file.general().m_startDate.month == 12); + CHECK(file.general().m_startDate.year == 2009); + } +} + +// =========================================================================== +// 2. Read physical samples -- verify within physical range +// =========================================================================== + +TEST_CASE("readSignal returns physical values within declared range") { + auto file = EdfFile::open("test_generator_2.edf"); + + // Find first non-annotation signal + size_t sigIdx = 0; + for (size_t i = 0; i < file.signals().size(); ++i) { + if (!file.signals()[i].m_detail.m_isAnnotation) { + sigIdx = i; + break; + } + } + auto const &sig = file.signals()[sigIdx]; + REQUIRE_FALSE(sig.m_detail.m_isAnnotation); + + auto samples = file.readSignal(sigIdx); + REQUIRE_FALSE(samples.empty()); + + // Expected sample count = dataRecordCount * samplesInDataRecord + auto expectedCount = static_cast(file.dataRecordCount()) * + static_cast(sig.m_samplesInDataRecord); + CHECK(samples.size() == expectedCount); + + // Verify first 200 samples are within declared physical range + double physMin = sig.m_physicalMin; + double physMax = sig.m_physicalMax; + double tol = (physMax - physMin) * 0.001; + auto limit = std::min(samples.size(), size_t{200}); + for (size_t i = 0; i < limit; ++i) { + CHECK(samples[i] >= physMin - tol); + CHECK(samples[i] <= physMax + tol); + } +} + +// =========================================================================== +// 3. Read digital samples -- verify within digital range +// =========================================================================== + +TEST_CASE("readSignalDigital returns values within digital range") { + auto file = EdfFile::open("test_generator_2.edf"); + + // Find first non-annotation signal + size_t sigIdx = 0; + for (size_t i = 0; i < file.signals().size(); ++i) { + if (!file.signals()[i].m_detail.m_isAnnotation) { + sigIdx = i; + break; + } + } + auto const &sig = file.signals()[sigIdx]; + REQUIRE_FALSE(sig.m_detail.m_isAnnotation); + + auto samples = file.readSignalDigital(sigIdx); + REQUIRE_FALSE(samples.empty()); + + // EDF uses 16-bit signed integers + int32_t digiMin = sig.m_digitalMin; + int32_t digiMax = sig.m_digitalMax; + + auto limit = std::min(samples.size(), size_t{200}); + for (size_t i = 0; i < limit; ++i) { + CHECK(samples[i] >= digiMin); + CHECK(samples[i] <= digiMax); + } +} + +// =========================================================================== +// 4. Read annotations from EDF+ file +// =========================================================================== + +TEST_CASE("readAnnotations extracts annotations from EDF+ file") { + auto file = EdfFile::open("test_generator_2.edf"); + REQUIRE(file.isPlus()); + + auto annots = file.readAnnotations(); + // EDF+ file should have at least some annotations + CHECK(annots.size() > 0); + + for (auto const &a : annots) { + CHECK_FALSE(a.m_annotation.empty()); + CHECK(a.m_duration >= 0.0); + } +} + +// =========================================================================== +// 5. Open test_generator_2.bdf -- verify BDF detection +// =========================================================================== + +TEST_CASE("EdfFile::open reads BDF file correctly") { + auto file = EdfFile::open("test_generator_2.bdf"); + + CHECK(file.isBdf()); + CHECK(file.isPlus()); + CHECK_FALSE(file.isEdf()); + CHECK(file.format() == DataFormat::BdfPlusC); + CHECK(file.signalCount() > 0); + CHECK(file.dataRecordCount() > 0); + CHECK(file.duration() > 0.0); + + SUBCASE("BDF physical samples within range") { + // Find first non-annotation signal + size_t sigIdx = 0; + for (size_t i = 0; i < file.signals().size(); ++i) { + if (!file.signals()[i].m_detail.m_isAnnotation) { + sigIdx = i; + break; + } + } + auto const &sig = file.signals()[sigIdx]; + REQUIRE_FALSE(sig.m_detail.m_isAnnotation); + + auto samples = file.readSignal(sigIdx); + REQUIRE_FALSE(samples.empty()); + + double physMin = sig.m_physicalMin; + double physMax = sig.m_physicalMax; + double tol = (physMax - physMin) * 0.001; + auto limit = std::min(samples.size(), size_t{100}); + for (size_t i = 0; i < limit; ++i) { + CHECK(samples[i] >= physMin - tol); + CHECK(samples[i] <= physMax + tol); + } + } + + SUBCASE("BDF digital samples within 24-bit range") { + size_t sigIdx = 0; + for (size_t i = 0; i < file.signals().size(); ++i) { + if (!file.signals()[i].m_detail.m_isAnnotation) { + sigIdx = i; + break; + } + } + auto const &sig = file.signals()[sigIdx]; + REQUIRE_FALSE(sig.m_detail.m_isAnnotation); + + auto samples = file.readSignalDigital(sigIdx); + REQUIRE_FALSE(samples.empty()); + + constexpr int32_t BDF_MIN = -8388608; + constexpr int32_t BDF_MAX = 8388607; + auto limit = std::min(samples.size(), size_t{100}); + for (size_t i = 0; i < limit; ++i) { + CHECK(samples[i] >= BDF_MIN); + CHECK(samples[i] <= BDF_MAX); + } + } +} + +// =========================================================================== +// 6. Annotation-only EDF+ file (Hypnogram) +// =========================================================================== + +TEST_CASE("EdfFile reads annotations from annotation-only file") { + auto file = EdfFile::open("SC4001EC-Hypnogram.edf"); + + CHECK(file.isEdf()); + CHECK(file.isPlus()); + CHECK(file.signalCount() == 1); + CHECK(file.signals()[0].m_detail.m_isAnnotation); + + auto annots = file.readAnnotations(); + CHECK(annots.size() > 0); + + for (auto const &a : annots) { + CHECK_FALSE(a.m_annotation.empty()); + CHECK(a.m_duration >= 0.0); + } +} + +// =========================================================================== +// 7. Invalid file path throws std::runtime_error +// =========================================================================== + +TEST_CASE("EdfFile::open throws on non-existent file") { + CHECK_THROWS_AS((void)EdfFile::open("no_such_file_xyz.edf"), std::runtime_error); +} + +// =========================================================================== +// 8. Invalid signal index throws std::out_of_range +// =========================================================================== + +TEST_CASE("EdfFile methods throw on invalid signal index") { + auto file = EdfFile::open("test_generator_2.edf"); + auto badIdx = static_cast(file.signalCount()) + 10; + + CHECK_THROWS_AS((void)file.readSignal(badIdx), std::out_of_range); + CHECK_THROWS_AS((void)file.readSignalDigital(badIdx), std::out_of_range); + CHECK_THROWS_AS((void)file.signalRecordStore(badIdx), std::out_of_range); + CHECK_THROWS_AS((void)file.signalSampleStore(badIdx), std::out_of_range); +} + +// =========================================================================== +// 9. EdfWriter round-trip +// =========================================================================== + +TEST_CASE("EdfWriter round-trip preserves header and data") { + const char *tmpfile = "test_edffile_roundtrip.edf"; + + // Read the original file with EdfFile + auto original = EdfFile::open("test_generator_2.edf"); + auto const &hdr = original.header(); + + // Write using EdfWriter + { + auto writer = EdfWriter::create(tmpfile, hdr); + auto store = original.dataRecordStore(); + for (auto it = store.begin(); it != store.end(); ++it) { + writer.writeDataRecord(*it); + } + writer.close(); + } + + // Read back using EdfFile and verify + { + auto copy = EdfFile::open(tmpfile); + + CHECK(copy.format() == original.format()); + CHECK(copy.signalCount() == original.signalCount()); + CHECK(copy.dataRecordCount() == original.dataRecordCount()); + CHECK(copy.duration() == doctest::Approx(original.duration())); + + REQUIRE(copy.signals().size() == original.signals().size()); + for (size_t i = 0; i < copy.signals().size(); ++i) { + CHECK(copy.signals()[i].m_label == original.signals()[i].m_label); + CHECK(copy.signals()[i].m_samplesInDataRecord == + original.signals()[i].m_samplesInDataRecord); + } + + // Compare first non-annotation signal's digital samples + size_t sigIdx = 0; + for (size_t i = 0; i < copy.signals().size(); ++i) { + if (!copy.signals()[i].m_detail.m_isAnnotation) { + sigIdx = i; + break; + } + } + + auto origSamples = original.readSignalDigital(sigIdx); + auto copySamples = copy.readSignalDigital(sigIdx); + REQUIRE(copySamples.size() == origSamples.size()); + + auto limit = std::min(copySamples.size(), size_t{200}); + for (size_t i = 0; i < limit; ++i) { + CHECK(copySamples[i] == origSamples[i]); + } + } + + std::remove(tmpfile); +} + +// =========================================================================== +// 10. EdfWriter auto-patches data record count on close +// =========================================================================== + +TEST_CASE("EdfWriter auto-patches data record count in header") { + const char *tmpfile = "test_autocount.edf"; + + auto original = EdfFile::open("test_generator_2.edf"); + auto hdr = original.header(); + + // Deliberately set count to 0 -- the writer should fix it on close + hdr.m_general.m_datarecordsFile = 0; + + { + auto writer = EdfWriter::create(tmpfile, hdr); + auto store = original.dataRecordStore(); + int64_t written = 0; + for (auto it = store.begin(); it != store.end(); ++it) { + writer.writeDataRecord(*it); + ++written; + } + CHECK(writer.recordsWritten() == written); + CHECK(written == 600); + writer.close(); + } + + // Read back -- the header should now have the correct count + { + auto copy = EdfFile::open(tmpfile); + CHECK(copy.dataRecordCount() == 600); + CHECK(copy.duration() == doctest::Approx(600.0)); + + // Verify data integrity too + size_t sigIdx = 0; + for (size_t i = 0; i < copy.signals().size(); ++i) { + if (!copy.signals()[i].m_detail.m_isAnnotation) { + sigIdx = i; + break; + } + } + auto origSamples = original.readSignalDigital(sigIdx); + auto copySamples = copy.readSignalDigital(sigIdx); + REQUIRE(copySamples.size() == origSamples.size()); + for (size_t i = 0; i < std::min(copySamples.size(), size_t{100}); ++i) { + CHECK(copySamples[i] == origSamples[i]); + } + } + + std::remove(tmpfile); +} + +TEST_CASE("EdfWriter destructor auto-patches count without explicit close") { + const char *tmpfile = "test_autocount_dtor.edf"; + + auto original = EdfFile::open("Calib5.edf"); + auto hdr = original.header(); + hdr.m_general.m_datarecordsFile = -1; // intentionally wrong + + { + auto writer = EdfWriter::create(tmpfile, hdr); + auto store = original.dataRecordStore(); + for (auto it = store.begin(); it != store.end(); ++it) { + writer.writeDataRecord(*it); + } + // No explicit close() -- destructor should handle it + } + + auto copy = EdfFile::open(tmpfile); + CHECK(copy.dataRecordCount() == original.dataRecordCount()); + + std::remove(tmpfile); +} + +// =========================================================================== +// 11. EdfFile is moveable +// =========================================================================== + +TEST_CASE("EdfFile supports move semantics") { + auto file = EdfFile::open("test_generator_2.edf"); + auto moved = std::move(file); + + CHECK(moved.signalCount() == 12); + CHECK(moved.format() == DataFormat::EdfPlusC); +} + +// =========================================================================== +// 11. Low-level store access through EdfFile +// =========================================================================== + +TEST_CASE("EdfFile provides low-level store access") { + auto file = EdfFile::open("test_generator_2.edf"); + + SUBCASE("dataRecordStore") { + auto store = file.dataRecordStore(); + CHECK(store.size() == + static_cast(file.dataRecordCount())); + } + + SUBCASE("signalRecordStore") { + size_t sigIdx = 0; + auto store = file.signalRecordStore(sigIdx); + CHECK(store.size() == + static_cast(file.dataRecordCount())); + } + + SUBCASE("signalSampleStore") { + size_t sigIdx = 0; + auto const &sig = file.signals()[sigIdx]; + auto store = file.signalSampleStore(sigIdx); + auto expected = static_cast(file.dataRecordCount()) * + static_cast(sig.m_samplesInDataRecord); + CHECK(store.size() == expected); + } +} diff --git a/tests/test_edfplus.cpp b/tests/test_edfplus.cpp new file mode 100644 index 0000000..f184b86 --- /dev/null +++ b/tests/test_edfplus.cpp @@ -0,0 +1,412 @@ +#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN +#include +#include +#include + +using namespace edfio; + +// ---- EDF+ format detection ---- + +TEST_CASE("test_generator_2.edf is EDF+ format") { + std::ifstream stream("test_generator_2.edf", std::ios::binary); + REQUIRE(stream.is_open()); + auto header = ReadHeaderExam(stream); + + CHECK(IsEdf(header.m_general.m_version)); + CHECK(IsPlus(header.m_general.m_version)); + CHECK_FALSE(IsBdf(header.m_general.m_version)); + CHECK(header.m_general.m_version == DataFormat::EdfPlusC); +} + +TEST_CASE("EDF+ has annotation channels") { + std::ifstream stream("test_generator_2.edf", std::ios::binary); + REQUIRE(stream.is_open()); + auto header = ReadHeaderExam(stream); + + // Find annotation channels + int annotCount = 0; + int annotIdx = -1; + for (size_t i = 0; i < header.m_signals.size(); ++i) { + if (header.m_signals[i].m_detail.m_isAnnotation) { + if (annotIdx < 0) + annotIdx = static_cast(i); + ++annotCount; + } + } + CHECK(annotCount > 0); + REQUIRE(annotIdx >= 0); + + // Annotation channel label should contain "Annotation" + CHECK(header.m_signals[annotIdx].m_label.find("Annotation") != + std::string::npos); +} + +// ---- EDF+ header fields ---- + +TEST_CASE("EDF+ patient and recording fields are parsed") { + std::ifstream stream("test_generator_2.edf", std::ios::binary); + REQUIRE(stream.is_open()); + auto header = ReadHeaderExam(stream); + + // EDF+ has structured patient/recording fields + CHECK(header.m_general.m_totalSignals == 12); + CHECK(header.m_general.m_datarecordsFile == 600); + CHECK(header.m_general.m_datarecordDuration == doctest::Approx(1.0)); + CHECK(header.m_general.m_headerSize > 0); + + // Date should be 10-DEC-2009 + CHECK(header.m_general.m_startDate.day == 10); + CHECK(header.m_general.m_startDate.month == 12); + CHECK(header.m_general.m_startDate.year == 2009); +} + +// ---- TimeStamp reading ---- + +TEST_CASE("EDF+ TimeStampStore reads timestamps from annotation channel") { + std::ifstream stream("test_generator_2.edf", std::ios::binary); + REQUIRE(stream.is_open()); + auto header = ReadHeaderExam(stream); + + // Find first annotation signal + const HeaderSignal *annotSignal = nullptr; + for (auto const &sig : header.m_signals) { + if (sig.m_detail.m_isAnnotation) { + annotSignal = &sig; + break; + } + } + REQUIRE(annotSignal != nullptr); + + auto tsStore = + detail::CreateTimeStampStore(stream, header.m_general, *annotSignal); + CHECK(tsStore.size() == static_cast(header.m_general.m_datarecordsFile)); + + // Read first timestamp - TimeStampStore uses getline(delim=20) so the + // result is the raw timestamp string (e.g. "+0"), NOT a full TAL record + auto it = tsStore.begin(); + auto &rec = *it; + CHECK(rec.Size() > 0); + + // The first byte should be '+' or '-' + auto const &data = rec(); + CHECK((data[0] == '+' || data[0] == '-')); + + // Parse the timestamp value directly + std::string tsStr(data.begin(), data.end()); + // Trim null bytes + auto nullPos = tsStr.find('\0'); + if (nullPos != std::string::npos) + tsStr.resize(nullPos); + CHECK(!tsStr.empty()); + // First timestamp should start with '+' + CHECK(tsStr[0] == '+'); +} + +TEST_CASE("EDF+ timestamps are monotonically non-decreasing") { + std::ifstream stream("test_generator_2.edf", std::ios::binary); + REQUIRE(stream.is_open()); + auto header = ReadHeaderExam(stream); + + const HeaderSignal *annotSignal = nullptr; + for (auto const &sig : header.m_signals) { + if (sig.m_detail.m_isAnnotation) { + annotSignal = &sig; + break; + } + } + REQUIRE(annotSignal != nullptr); + + auto tsStore = + detail::CreateTimeStampStore(stream, header.m_general, *annotSignal); + + double prevStart = -1.0; + int64_t count = 0; + for (auto it = tsStore.begin(); it != tsStore.end() && count < 10; ++it, ++count) { + auto &rec = *it; + auto const &data = rec(); + // Extract timestamp string, trimming nulls + std::string tsStr(data.begin(), data.end()); + auto nullPos = tsStr.find('\0'); + if (nullPos != std::string::npos) + tsStr.resize(nullPos); + REQUIRE(!tsStr.empty()); + REQUIRE((tsStr[0] == '+' || tsStr[0] == '-')); + + // Parse the numeric value + double val = detail::ParseDouble( + std::string_view(tsStr).substr(tsStr[0] == '+' ? 1 : 0), + "bad timestamp"); + if (tsStr[0] == '-') + val = -val; + CHECK(val >= prevStart); + prevStart = val; + } + CHECK(count == 10); +} + +// ---- TAL (Time-stamped Annotation List) reading ---- + +TEST_CASE("EDF+ TAL reading via SignalRecordStore") { + std::ifstream stream("test_generator_2.edf", std::ios::binary); + REQUIRE(stream.is_open()); + auto header = ReadHeaderExam(stream); + + const HeaderSignal *annotSignal = nullptr; + for (auto const &sig : header.m_signals) { + if (sig.m_detail.m_isAnnotation) { + annotSignal = &sig; + break; + } + } + REQUIRE(annotSignal != nullptr); + + auto sigStore = + detail::CreateSignalRecordStore(stream, header.m_general, *annotSignal); + + // Read first annotation record + auto it = sigStore.begin(); + auto &rec = *it; + CHECK(rec.Size() > 0); + + // The TAL data is the raw bytes of the annotation signal record + // Convert to vector for ProcessTalRecord + std::vector talData(rec().begin(), rec().end()); + + // First TAL should start with '+' or '-' + REQUIRE(!talData.empty()); + CHECK((talData.front() == '+' || talData.front() == '-')); +} + +TEST_CASE("EDF+ TalStore iterates through TALs") { + std::ifstream stream("test_generator_2.edf", std::ios::binary); + REQUIRE(stream.is_open()); + auto header = ReadHeaderExam(stream); + + const HeaderSignal *annotSignal = nullptr; + for (auto const &sig : header.m_signals) { + if (sig.m_detail.m_isAnnotation) { + annotSignal = &sig; + break; + } + } + REQUIRE(annotSignal != nullptr); + + // Read first signal record to use as TalStore input + auto sigStore = + detail::CreateSignalRecordStore(stream, header.m_general, *annotSignal); + auto sigIt = sigStore.begin(); + auto &rec = *sigIt; + + // Create TalStore from the record + TalStore talStore(rec); + int talCount = 0; + for (auto it = talStore.begin(); it != talStore.end(); ++it) { + auto &tal = *it; + CHECK(!tal.empty()); + ++talCount; + } + // Should have at least the timestamp TAL + CHECK(talCount >= 1); +} + +TEST_CASE("ProcessTalRecord extracts annotations from TAL data") { + // Build a synthetic TAL: "+0\x14\x14\x00" (timestamp only, no annotation text) + std::vector tal1 = {'+', '0', 20, 20, 0}; + auto annots1 = ProcessTalRecord(tal1, 0); + // Timestamp-only TAL should produce no annotations (empty annotation text is skipped) + CHECK(annots1.empty()); + + // Build a TAL with an annotation: "+1.5\x14test annotation\x14\x00" + std::vector tal2; + for (char c : std::string("+1.5")) + tal2.push_back(c); + tal2.push_back(20); // ANNOTATION_DIV + for (char c : std::string("test annotation")) + tal2.push_back(c); + tal2.push_back(20); // ANNOTATION_DIV + tal2.push_back(0); // end + + auto annots2 = ProcessTalRecord(tal2, 5); + REQUIRE(annots2.size() == 1); + CHECK(annots2[0].m_start == doctest::Approx(1.5)); + CHECK(annots2[0].m_duration == doctest::Approx(0.0)); + CHECK(annots2[0].m_annotation == "test annotation"); + CHECK(annots2[0].m_datarecord == 5); +} + +TEST_CASE("ProcessTalRecord with duration") { + // "+2.0\x1530.5\x14my event\x14\x00" + std::vector tal; + for (char c : std::string("+2.0")) + tal.push_back(c); + tal.push_back(21); // DURATION_DIV + for (char c : std::string("30.5")) + tal.push_back(c); + tal.push_back(20); // ANNOTATION_DIV + for (char c : std::string("my event")) + tal.push_back(c); + tal.push_back(20); // ANNOTATION_DIV + tal.push_back(0); + + auto annots = ProcessTalRecord(tal, 0); + REQUIRE(annots.size() == 1); + CHECK(annots[0].m_start == doctest::Approx(2.0)); + CHECK(annots[0].m_duration == doctest::Approx(30.5)); + CHECK(annots[0].m_annotation == "my event"); +} + +TEST_CASE("ProcessTalRecord with multiple annotations in one TAL") { + // "+0\x14event1\x14event2\x14\x00" + std::vector tal; + for (char c : std::string("+0")) + tal.push_back(c); + tal.push_back(20); // ANNOTATION_DIV + for (char c : std::string("event1")) + tal.push_back(c); + tal.push_back(20); // ANNOTATION_DIV + for (char c : std::string("event2")) + tal.push_back(c); + tal.push_back(20); // ANNOTATION_DIV + tal.push_back(0); + + auto annots = ProcessTalRecord(tal, 0); + REQUIRE(annots.size() == 2); + CHECK(annots[0].m_annotation == "event1"); + CHECK(annots[1].m_annotation == "event2"); + CHECK(annots[0].m_start == doctest::Approx(0.0)); + CHECK(annots[1].m_start == doctest::Approx(0.0)); +} + +TEST_CASE("ProcessTalRecord with negative onset") { + std::vector tal; + for (char c : std::string("-5.25")) + tal.push_back(c); + tal.push_back(20); + for (char c : std::string("neg event")) + tal.push_back(c); + tal.push_back(20); + tal.push_back(0); + + auto annots = ProcessTalRecord(tal, 0); + REQUIRE(annots.size() == 1); + CHECK(annots[0].m_start == doctest::Approx(-5.25)); + CHECK(annots[0].m_annotation == "neg event"); +} + +TEST_CASE("ProcessTalRecord throws on invalid TAL") { + // TAL not starting with '+' or '-' + std::vector bad = {'0', 20, 20, 0}; + CHECK_THROWS_AS(ProcessTalRecord(bad, 0), std::invalid_argument); +} + +// ---- Annotation-only EDF+ file (Hypnogram) ---- + +TEST_CASE("Hypnogram EDF+ is annotation-only format") { + std::ifstream stream("SC4001EC-Hypnogram.edf", std::ios::binary); + REQUIRE(stream.is_open()); + auto header = ReadHeaderExam(stream); + + CHECK(IsEdf(header.m_general.m_version)); + CHECK(IsPlus(header.m_general.m_version)); + CHECK(header.m_general.m_version == DataFormat::EdfPlusC); + + // Should have exactly 1 signal (the annotation channel) + CHECK(header.m_general.m_totalSignals == 1); + CHECK(header.m_signals.size() == 1); + CHECK(header.m_signals[0].m_detail.m_isAnnotation); + CHECK(header.m_signals[0].m_label.find("Annotation") != std::string::npos); +} + +TEST_CASE("Hypnogram annotations can be read") { + std::ifstream stream("SC4001EC-Hypnogram.edf", std::ios::binary); + REQUIRE(stream.is_open()); + auto header = ReadHeaderExam(stream); + REQUIRE(header.m_signals.size() == 1); + REQUIRE(header.m_signals[0].m_detail.m_isAnnotation); + + auto const &annotSignal = header.m_signals[0]; + auto sigStore = + detail::CreateSignalRecordStore(stream, header.m_general, annotSignal); + + // Read annotation records and parse TALs + int totalAnnotations = 0; + int64_t drIdx = 0; + for (auto it = sigStore.begin(); it != sigStore.end(); ++it, ++drIdx) { + auto &rec = *it; + std::vector talData(rec().begin(), rec().end()); + if (talData.empty() || (talData.front() != '+' && talData.front() != '-')) + continue; + + auto annots = ProcessTalRecord(talData, drIdx); + totalAnnotations += static_cast(annots.size()); + + for (auto const &a : annots) { + // Sleep stage annotations should have non-empty text + CHECK(!a.m_annotation.empty()); + // Duration should be >= 0 + CHECK(a.m_duration >= 0.0); + } + } + // Hypnogram should have many sleep stage annotations + CHECK(totalAnnotations > 0); +} + +// ---- ProcessTimeStamp (write) ---- + +TEST_CASE("ProcessTimeStamp creates correct record for positive time") { + TimeStamp ts; + ts.m_start = 5.0; + ts.m_datarecord = 5; + auto rec = ProcessTimeStamp(ts); + std::string content(rec().begin(), rec().end()); + // Should start with +5 + CHECK(content[0] == '+'); + CHECK(content[1] == '5'); + // Should end with \x14\x14\x00 + auto sz = rec.Size(); + CHECK(rec()[sz - 3] == 20); + CHECK(rec()[sz - 2] == 20); + CHECK(rec()[sz - 1] == 0); +} + +TEST_CASE("ProcessTimeStamp handles negative time") { + TimeStamp ts; + ts.m_start = -3.5; + ts.m_datarecord = 0; + auto rec = ProcessTimeStamp(ts); + CHECK(rec()[0] == '-'); +} + +TEST_CASE("ProcessTimeStamp handles zero time") { + TimeStamp ts; + ts.m_start = 0.0; + ts.m_datarecord = 0; + auto rec = ProcessTimeStamp(ts); + CHECK(rec()[0] == '+'); +} + +// ---- BDF+ format detection ---- + +TEST_CASE("test_generator_2.bdf is BDF+ format") { + std::ifstream stream("test_generator_2.bdf", std::ios::binary); + REQUIRE(stream.is_open()); + auto header = ReadHeaderExam(stream); + + CHECK(IsBdf(header.m_general.m_version)); + CHECK(IsPlus(header.m_general.m_version)); + CHECK_FALSE(IsEdf(header.m_general.m_version)); + CHECK(header.m_general.m_version == DataFormat::BdfPlusC); +} + +TEST_CASE("BDF+ has annotation channels") { + std::ifstream stream("test_generator_2.bdf", std::ios::binary); + REQUIRE(stream.is_open()); + auto header = ReadHeaderExam(stream); + + int annotCount = 0; + for (auto const &sig : header.m_signals) { + if (sig.m_detail.m_isAnnotation) + ++annotCount; + } + CHECK(annotCount > 0); +} diff --git a/tests/test_iterators.cpp b/tests/test_iterators.cpp new file mode 100644 index 0000000..4c72187 --- /dev/null +++ b/tests/test_iterators.cpp @@ -0,0 +1,163 @@ +#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN +#include +#include +#include +#include +#include + +using namespace edfio; + +// Phase 4: Verify ranges compliance at compile time +static_assert(std::random_access_iterator); +static_assert(std::random_access_iterator); +static_assert(std::bidirectional_iterator); +static_assert(std::ranges::random_access_range); +static_assert(std::ranges::random_access_range); +static_assert(std::ranges::bidirectional_range); + +TEST_CASE("RecordStore iterator subtraction and arithmetic (multi-record file)") { + std::ifstream stream("test_generator_2.edf", std::ios::binary); + REQUIRE(stream.is_open()); + auto header = ReadHeaderExam(stream); + auto store = detail::CreateDataRecordStore(stream, header.m_general); + REQUIRE(store.size() == 600); + + auto a = store.begin(); + auto b = store.begin() + 100; + auto c = store.end(); + + CHECK((b - a) == 100); + CHECK((a - b) == -100); + CHECK((c - a) == 600); + CHECK((a - c) == -600); +} + +TEST_CASE("RecordStore iterator n + it and negative offsets") { + std::ifstream stream("test_generator_2.edf", std::ios::binary); + REQUIRE(stream.is_open()); + auto header = ReadHeaderExam(stream); + auto store = detail::CreateDataRecordStore(stream, header.m_general); + REQUIRE(store.size() >= 10); + + // n + it form + auto it = store.begin(); + auto it2 = 5 + it; + CHECK((it2 - store.begin()) == 5); + + // Negative offset via += + auto it3 = store.begin() + 10; + it3 += -3; + CHECK((it3 - store.begin()) == 7); + + // Negative offset via -= + auto it4 = store.begin() + 10; + it4 -= -2; // subtracting negative = adding + CHECK((it4 - store.begin()) == 12); +} + +TEST_CASE("DataRecordStore iteration works") { + std::ifstream stream("test_generator_2.edf", std::ios::binary); + REQUIRE(stream.is_open()); + auto header = ReadHeaderExam(stream); + auto store = detail::CreateDataRecordStore(stream, header.m_general); + + CHECK(store.size() == static_cast(header.m_general.m_datarecordsFile)); + CHECK(store.size() == 600); + + // Iterate through first 10 records + uint32_t count = 0; + for (auto it = store.begin(); it != store.begin() + 10; ++it) { + auto& rec = *it; + CHECK(rec.Size() > 0); + ++count; + } + CHECK(count == 10); +} + +TEST_CASE("RecordStore iterator comparisons via spaceship") { + std::ifstream stream("test_generator_2.edf", std::ios::binary); + REQUIRE(stream.is_open()); + auto header = ReadHeaderExam(stream); + auto store = detail::CreateDataRecordStore(stream, header.m_general); + REQUIRE(store.size() >= 10); + + auto a = store.begin(); + auto b = store.begin() + 5; + auto c = store.end(); + CHECK(a < b); + CHECK(b < c); + CHECK(b > a); + CHECK(c > b); + CHECK(a <= a); + CHECK(a <= b); + CHECK(c >= b); + CHECK(a == a); + CHECK(a != b); +} + +TEST_CASE("RecordStore iterator subscript operator") { + std::ifstream stream("test_generator_2.edf", std::ios::binary); + REQUIRE(stream.is_open()); + auto header = ReadHeaderExam(stream); + auto store = detail::CreateDataRecordStore(stream, header.m_general); + REQUIRE(store.size() >= 3); + + auto it = store.begin(); + auto& rec0 = it[0]; + auto& rec2 = it[2]; + CHECK(rec0.Size() > 0); + CHECK(rec2.Size() > 0); +} + +TEST_CASE("SignalRecordStore iteration works") { + std::ifstream stream("test_generator_2.edf", std::ios::binary); + REQUIRE(stream.is_open()); + auto header = ReadHeaderExam(stream); + REQUIRE(header.m_signals.size() > 0); + + auto store = detail::CreateSignalRecordStore(stream, header.m_general, header.m_signals[0]); + CHECK(store.size() == static_cast(header.m_general.m_datarecordsFile)); + + // Iterate first 5 records + uint32_t count = 0; + for (auto it = store.begin(); it != store.begin() + 5; ++it) { + auto& rec = *it; + CHECK(rec.Size() > 0); + ++count; + } + CHECK(count == 5); +} + +TEST_CASE("DataRecordStore satisfies ranges::random_access_range") { + std::ifstream stream("test_generator_2.edf", std::ios::binary); + REQUIRE(stream.is_open()); + auto header = ReadHeaderExam(stream); + auto store = detail::CreateDataRecordStore(stream, header.m_general); + + // Use std::ranges algorithms + CHECK(std::ranges::distance(store.begin(), store.end()) == 600); + + // Range-based for loop (proves range concept works) + uint32_t count = 0; + for ([[maybe_unused]] auto& rec : store) { + ++count; + if (count >= 3) break; + } + CHECK(count == 3); +} + +TEST_CASE("Const iteration works without const_cast issues") { + std::ifstream stream("test_generator_2.edf", std::ios::binary); + REQUIRE(stream.is_open()); + auto header = ReadHeaderExam(stream); + auto store = detail::CreateDataRecordStore(stream, header.m_general); + + // Call const begin/end + const auto& cstore = store; + auto it = cstore.begin(); + auto end = cstore.end(); + CHECK(it != end); + CHECK((end - it) == 600); + auto& rec = *it; + CHECK(rec.Size() > 0); +} diff --git a/tests/test_processor_sample.cpp b/tests/test_processor_sample.cpp new file mode 100644 index 0000000..7f2430c --- /dev/null +++ b/tests/test_processor_sample.cpp @@ -0,0 +1,76 @@ +#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN +#include +#include + +using namespace edfio; + +TEST_CASE("ProcessorSampleRecord sign-extends negative 2-byte samples") { + // -100 as signed 16-bit = 0xFF9C + Record rec(2); + rec()[0] = static_cast(0xFF); + rec()[1] = static_cast(0x9C); + ProcessorSampleRecord proc(0.0, 1.0); + auto result = proc(rec); + CHECK(result == -100); +} + +TEST_CASE("ProcessorSampleRecord positive 2-byte samples") { + Record rec(2); + rec()[0] = static_cast(0x00); + rec()[1] = static_cast(0x64); + ProcessorSampleRecord proc(0.0, 1.0); + auto result = proc(rec); + CHECK(result == 100); +} + +TEST_CASE("ProcessorSampleRecord 3-byte BDF negative sample") { + // -1000 as signed 24-bit = 0xFFFC18 + Record rec(3); + rec()[0] = static_cast(0xFF); + rec()[1] = static_cast(0xFC); + rec()[2] = static_cast(0x18); + ProcessorSampleRecord proc(0.0, 1.0); + auto result = proc(rec); + CHECK(result == -1000); +} + +TEST_CASE("ProcessorSampleRecord 3-byte BDF positive sample") { + // 1000 as signed 24-bit = 0x0003E8 + Record rec(3); + rec()[0] = static_cast(0x00); + rec()[1] = static_cast(0x03); + rec()[2] = static_cast(0xE8); + ProcessorSampleRecord proc(0.0, 1.0); + auto result = proc(rec); + CHECK(result == 1000); +} + +TEST_CASE("ProcessorSampleRecord 2-byte max positive") { + // 32767 = 0x7FFF + Record rec(2); + rec()[0] = static_cast(0x7F); + rec()[1] = static_cast(0xFF); + ProcessorSampleRecord proc(0.0, 1.0); + auto result = proc(rec); + CHECK(result == 32767); +} + +TEST_CASE("ProcessorSampleRecord 2-byte min negative") { + // -32768 = 0x8000 + Record rec(2); + rec()[0] = static_cast(0x80); + rec()[1] = static_cast(0x00); + ProcessorSampleRecord proc(0.0, 1.0); + auto result = proc(rec); + CHECK(result == -32768); +} + +TEST_CASE("ProcessorSampleRecord 2-byte minus one") { + // -1 = 0xFFFF + Record rec(2); + rec()[0] = static_cast(0xFF); + rec()[1] = static_cast(0xFF); + ProcessorSampleRecord proc(0.0, 1.0); + auto result = proc(rec); + CHECK(result == -1); +} diff --git a/tests/test_processor_utils.cpp b/tests/test_processor_utils.cpp new file mode 100644 index 0000000..9425607 --- /dev/null +++ b/tests/test_processor_utils.cpp @@ -0,0 +1,93 @@ +#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN +#include +#include + +TEST_CASE("ReduceString trims and collapses spaces") { + using edfio::detail::ReduceString; + CHECK(ReduceString(" hello world ") == "hello world"); + CHECK(ReduceString(" ") == ""); + CHECK(ReduceString("no_change") == "no_change"); + CHECK(ReduceString(" a b c ") == "a b c"); + CHECK(ReduceString("") == ""); + CHECK(ReduceString("single") == "single"); + CHECK(ReduceString(" leading") == "leading"); + CHECK(ReduceString("trailing ") == "trailing"); +} + +TEST_CASE("GetStringFromMonth handles boundaries") { + CHECK(edfio::detail::GetStringFromMonth(0) == "JAN"); // was UB, now returns default + CHECK(edfio::detail::GetStringFromMonth(1) == "JAN"); + CHECK(edfio::detail::GetStringFromMonth(6) == "JUN"); + CHECK(edfio::detail::GetStringFromMonth(12) == "DEC"); + CHECK(edfio::detail::GetStringFromMonth(13) == "JAN"); // out of range, returns default +} + +TEST_CASE("GetMonthFromString returns correct values") { + CHECK(edfio::detail::GetMonthFromString("JAN") == 1); + CHECK(edfio::detail::GetMonthFromString("DEC") == 12); + CHECK(edfio::detail::GetMonthFromString("XXX") == 0); +} + +TEST_CASE("GetFormatName returns correct strings") { + CHECK(edfio::detail::GetFormatName(edfio::DataFormat::Edf) == "EDF"); + CHECK(edfio::detail::GetFormatName(edfio::DataFormat::BdfPlusD) == "BDF+D"); + CHECK(edfio::detail::GetFormatName(edfio::DataFormat::Invalid) == ""); +} + +TEST_CASE("DataFormat constexpr functions") { + static_assert(edfio::IsEdf(edfio::DataFormat::Edf)); + static_assert(!edfio::IsBdf(edfio::DataFormat::Edf)); + static_assert(edfio::IsBdf(edfio::DataFormat::Bdf)); + static_assert(edfio::IsPlus(edfio::DataFormat::EdfPlusC)); + static_assert(!edfio::IsPlus(edfio::DataFormat::Edf)); + static_assert(edfio::GetSampleBytes(edfio::DataFormat::Edf) == 2); + static_assert(edfio::GetSampleBytes(edfio::DataFormat::Bdf) == 3); + CHECK(true); +} + +TEST_CASE("GetMonthFromString accepts string_view") { + using namespace std::string_view_literals; + CHECK(edfio::detail::GetMonthFromString("FEB"sv) == 2); + CHECK(edfio::detail::GetMonthFromString("NOV"sv) == 11); +} + +TEST_CASE("GetFormatName returns string_view") { + auto name = edfio::detail::GetFormatName(edfio::DataFormat::EdfPlusC); + static_assert(std::is_same_v); + CHECK(name == "EDF+C"); +} + +TEST_CASE("ParseInt parses integers and trims spaces") { + using edfio::detail::ParseInt; + CHECK(ParseInt("42", "err") == 42); + CHECK(ParseInt(" 42 ", "err") == 42); + CHECK(ParseInt("-7", "err") == -7); + CHECK(ParseInt("0", "err") == 0); + CHECK_THROWS_AS(ParseInt("", "bad"), std::invalid_argument); + CHECK_THROWS_AS(ParseInt("abc", "bad"), std::invalid_argument); + CHECK_THROWS_AS(ParseInt(" ", "bad"), std::invalid_argument); +} + +TEST_CASE("ParseLongLong parses large integers") { + using edfio::detail::ParseLongLong; + CHECK(ParseLongLong("600", "err") == 600LL); + CHECK(ParseLongLong(" 12345678901 ", "err") == 12345678901LL); + CHECK_THROWS_AS(ParseLongLong("xyz", "bad"), std::invalid_argument); +} + +TEST_CASE("ParseDouble parses floating-point numbers") { + using edfio::detail::ParseDouble; + CHECK(ParseDouble("3.14", "err") == doctest::Approx(3.14)); + CHECK(ParseDouble(" 1.0 ", "err") == doctest::Approx(1.0)); + CHECK(ParseDouble("-2.5", "err") == doctest::Approx(-2.5)); + CHECK(ParseDouble("+0.001", "err") == doctest::Approx(0.001)); + CHECK_THROWS_AS(ParseDouble("abc", "bad"), std::invalid_argument); +} + +TEST_CASE("GetError returns non-null for all error codes") { + CHECK(edfio::GetError(edfio::FileErrc::FileDoesNotOpen) != nullptr); + CHECK(edfio::GetError(edfio::FileErrc::FileNotOpened) != nullptr); + CHECK(edfio::GetError(edfio::FileErrc::FileReadError) != nullptr); + CHECK(edfio::GetError(edfio::FileErrc::FileContainsFormatErrors) != nullptr); + CHECK(edfio::GetError(edfio::FileErrc::FileWriteError) != nullptr); +} diff --git a/tests/test_processors.cpp b/tests/test_processors.cpp new file mode 100644 index 0000000..a59c172 --- /dev/null +++ b/tests/test_processors.cpp @@ -0,0 +1,724 @@ +#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN +#include +#include +#include +#include + +using namespace edfio; + +// --------------------------------------------------------------------------- +// Helper: build a minimal HeaderSignal suitable for non-Plus EDF format +// --------------------------------------------------------------------------- +static HeaderSignal MakeEdfSignal(const std::string &label, double physMin, + double physMax, int32_t digMin, + int32_t digMax, int32_t samples) { + HeaderSignal sig; + sig.m_label = label; + sig.m_transducer = "AgAgCl"; + sig.m_physDimension = "uV"; + sig.m_physicalMin = physMin; + sig.m_physicalMax = physMax; + sig.m_digitalMin = digMin; + sig.m_digitalMax = digMax; + sig.m_prefilter = "HP:0.1Hz"; + sig.m_samplesInDataRecord = samples; + sig.m_reserved = ""; + return sig; +} + +// =========================================================================== +// TEST SUITE: ProcessHeaderSignal / ProcessHeaderSignalFields round-trip +// =========================================================================== +TEST_SUITE("ProcessHeaderSignal round-trip") { + + TEST_CASE("EDF signal round-trips through fields and back") { + // 1. Create a known HeaderSignal + HeaderSignal original = MakeEdfSignal("EEG Fp1", -500.0, 500.0, + -32768, 32767, 256); + + // 2. Convert to HeaderSignalFields + std::vector input{original}; + auto fields = ProcessHeaderSignal(std::move(input)); + + REQUIRE(fields.size() == 1); + + // Verify intermediate field values are properly padded + CHECK(fields[0].m_label().size() == 16); + CHECK(fields[0].m_digitalMin().size() == 8); + CHECK(fields[0].m_samplesInDataRecord().size() == 8); + + // 3. Convert back with EDF format (non-Plus, no annotation required) + auto signals = + ProcessHeaderSignalFields(std::move(fields), DataFormat::Edf, 1.0); + + REQUIRE(signals.size() == 1); + const auto &out = signals[0]; + + // Verify all fields round-trip correctly + CHECK(out.m_label == "EEG Fp1"); + CHECK(out.m_transducer == "AgAgCl"); + CHECK(out.m_physDimension == "uV"); + CHECK(out.m_physicalMin == doctest::Approx(-500.0)); + CHECK(out.m_physicalMax == doctest::Approx(500.0)); + CHECK(out.m_digitalMin == -32768); + CHECK(out.m_digitalMax == 32767); + CHECK(out.m_prefilter == "HP:0.1Hz"); + CHECK(out.m_samplesInDataRecord == 256); + + // Verify computed detail fields + double expectedScaling = + (500.0 - (-500.0)) / (32767 - (-32768)); // 1000 / 65535 + CHECK(out.m_detail.m_scaling == doctest::Approx(expectedScaling)); + CHECK(out.m_detail.m_signalOffset == 0); + } + + TEST_CASE("BDF signal round-trips with 24-bit digital range") { + HeaderSignal original = + MakeEdfSignal("EEG Fp2", -3200.0, 3200.0, -8388608, 8388607, 512); + + std::vector input{original}; + auto fields = ProcessHeaderSignal(std::move(input)); + + REQUIRE(fields.size() == 1); + + auto signals = + ProcessHeaderSignalFields(std::move(fields), DataFormat::Bdf, 1.0); + + REQUIRE(signals.size() == 1); + const auto &out = signals[0]; + + CHECK(out.m_digitalMin == -8388608); + CHECK(out.m_digitalMax == 8388607); + CHECK(out.m_physicalMin == doctest::Approx(-3200.0)); + CHECK(out.m_physicalMax == doctest::Approx(3200.0)); + CHECK(out.m_samplesInDataRecord == 512); + + // BDF uses 3 bytes per sample + CHECK(out.m_detail.m_signalOffset == 0); + } + + TEST_CASE("EDF signal with typical 16-bit range") { + HeaderSignal original = + MakeEdfSignal("EMG", -100.0, 100.0, -32768, 32767, 128); + + std::vector input{original}; + auto fields = ProcessHeaderSignal(std::move(input)); + auto signals = + ProcessHeaderSignalFields(std::move(fields), DataFormat::Edf, 1.0); + + REQUIRE(signals.size() == 1); + const auto &out = signals[0]; + + CHECK(out.m_digitalMin == -32768); + CHECK(out.m_digitalMax == 32767); + + double expectedScaling = + (100.0 - (-100.0)) / (32767 - (-32768)); // 200 / 65535 + CHECK(out.m_detail.m_scaling == doctest::Approx(expectedScaling)); + } + + TEST_CASE("Multiple signals: offset accumulates correctly for EDF") { + HeaderSignal sig1 = + MakeEdfSignal("EEG Fp1", -500.0, 500.0, -32768, 32767, 256); + HeaderSignal sig2 = + MakeEdfSignal("EEG Fp2", -500.0, 500.0, -32768, 32767, 128); + + std::vector input{sig1, sig2}; + auto fields = ProcessHeaderSignal(std::move(input)); + auto signals = + ProcessHeaderSignalFields(std::move(fields), DataFormat::Edf, 1.0); + + REQUIRE(signals.size() == 2); + + // First signal offset is 0 + CHECK(signals[0].m_detail.m_signalOffset == 0); + // Second signal offset = first signal's samples * 2 bytes (EDF) + CHECK(signals[1].m_detail.m_signalOffset == 256 * 2); + } + + TEST_CASE("Multiple signals: offset accumulates correctly for BDF") { + HeaderSignal sig1 = + MakeEdfSignal("EEG Fp1", -500.0, 500.0, -8388608, 8388607, 256); + HeaderSignal sig2 = + MakeEdfSignal("EEG Fp2", -500.0, 500.0, -8388608, 8388607, 100); + + std::vector input{sig1, sig2}; + auto fields = ProcessHeaderSignal(std::move(input)); + auto signals = + ProcessHeaderSignalFields(std::move(fields), DataFormat::Bdf, 1.0); + + REQUIRE(signals.size() == 2); + + CHECK(signals[0].m_detail.m_signalOffset == 0); + // Second signal offset = first signal's samples * 3 bytes (BDF) + CHECK(signals[1].m_detail.m_signalOffset == 256 * 3); + } + +} // TEST_SUITE "ProcessHeaderSignal round-trip" + +// =========================================================================== +// TEST SUITE: ProcessHeaderSignalFields validation +// =========================================================================== +TEST_SUITE("ProcessHeaderSignalFields validation") { + + // Helper: create a valid single-signal HeaderSignalFields for non-Plus EDF + static std::vector + MakeValidEdfFields(int32_t digMin = -32768, int32_t digMax = 32767, + int32_t samples = 256) { + HeaderSignalFields f; + f.m_label("EEG Fp1"); + f.m_transducer("AgAgCl"); + f.m_physDimension("uV"); + f.m_physicalMin("-500"); + f.m_physicalMax("500"); + f.m_digitalMin(std::to_string(digMin)); + f.m_digitalMax(std::to_string(digMax)); + f.m_prefilter("HP:0.1Hz"); + f.m_samplesInDataRecord(std::to_string(samples)); + f.m_reserved(""); + return {f}; + } + + TEST_CASE("digitalMax equal to digitalMin throws (div-by-zero)") { + auto fields = MakeValidEdfFields(100, 100, 256); + // digitalMax < digitalMin + 1 means digitalMax == digitalMin fails + CHECK_THROWS_AS( + ProcessHeaderSignalFields(std::move(fields), DataFormat::Edf, 1.0), + std::invalid_argument); + } + + TEST_CASE("digitalMin greater than digitalMax throws") { + auto fields = MakeValidEdfFields(1000, -1000, 256); + CHECK_THROWS_AS( + ProcessHeaderSignalFields(std::move(fields), DataFormat::Edf, 1.0), + std::invalid_argument); + } + + TEST_CASE("samplesInDataRecord less than 1 throws") { + auto fields = MakeValidEdfFields(-32768, 32767, 0); + CHECK_THROWS_AS( + ProcessHeaderSignalFields(std::move(fields), DataFormat::Edf, 1.0), + std::invalid_argument); + } + + TEST_CASE("samplesInDataRecord negative throws") { + auto fields = MakeValidEdfFields(-32768, 32767, -1); + CHECK_THROWS_AS( + ProcessHeaderSignalFields(std::move(fields), DataFormat::Edf, 1.0), + std::invalid_argument); + } + + TEST_CASE("EDF digital min out of range throws") { + // digitalMin = -32769, below EDF 16-bit signed range + auto fields = MakeValidEdfFields(-32769, 32767, 256); + CHECK_THROWS_AS( + ProcessHeaderSignalFields(std::move(fields), DataFormat::Edf, 1.0), + std::invalid_argument); + } + + TEST_CASE("EDF digital max out of range throws") { + // digitalMax = 32768, above EDF 16-bit signed range + auto fields = MakeValidEdfFields(-32768, 32768, 256); + CHECK_THROWS_AS( + ProcessHeaderSignalFields(std::move(fields), DataFormat::Edf, 1.0), + std::invalid_argument); + } + + TEST_CASE("BDF digital min out of range throws") { + // -8388609 is below BDF 24-bit signed range + // Use BDF fields helper + HeaderSignalFields f; + f.m_label("EEG Fp1"); + f.m_transducer("AgAgCl"); + f.m_physDimension("uV"); + f.m_physicalMin("-500"); + f.m_physicalMax("500"); + f.m_digitalMin("-8388609"); + f.m_digitalMax("8388607"); + f.m_prefilter("HP:0.1Hz"); + f.m_samplesInDataRecord("256"); + f.m_reserved(""); + std::vector fields{f}; + CHECK_THROWS_AS( + ProcessHeaderSignalFields(std::move(fields), DataFormat::Bdf, 1.0), + std::invalid_argument); + } + + TEST_CASE("BDF digital max out of range throws") { + HeaderSignalFields f; + f.m_label("EEG Fp1"); + f.m_transducer("AgAgCl"); + f.m_physDimension("uV"); + f.m_physicalMin("-500"); + f.m_physicalMax("500"); + f.m_digitalMin("-8388608"); + f.m_digitalMax("8388608"); + f.m_prefilter("HP:0.1Hz"); + f.m_samplesInDataRecord("256"); + f.m_reserved(""); + std::vector fields{f}; + CHECK_THROWS_AS( + ProcessHeaderSignalFields(std::move(fields), DataFormat::Bdf, 1.0), + std::invalid_argument); + } + + TEST_CASE("Valid EDF boundary values do not throw") { + auto fields = MakeValidEdfFields(-32768, 32767, 1); + CHECK_NOTHROW( + ProcessHeaderSignalFields(std::move(fields), DataFormat::Edf, 1.0)); + } + + TEST_CASE("Valid BDF boundary values do not throw") { + HeaderSignalFields f; + f.m_label("EEG Fp1"); + f.m_transducer("AgAgCl"); + f.m_physDimension("uV"); + f.m_physicalMin("-500"); + f.m_physicalMax("500"); + f.m_digitalMin("-8388608"); + f.m_digitalMax("8388607"); + f.m_prefilter("HP:0.1Hz"); + f.m_samplesInDataRecord("256"); + f.m_reserved(""); + std::vector fields{f}; + CHECK_NOTHROW( + ProcessHeaderSignalFields(std::move(fields), DataFormat::Bdf, 1.0)); + } + +} // TEST_SUITE "ProcessHeaderSignalFields validation" + +// =========================================================================== +// TEST SUITE: ProcessAnnotation +// =========================================================================== +TEST_SUITE("ProcessAnnotation") { + + TEST_CASE("Positive start, no duration") { + Annotation ann; + ann.m_start = 1.5; + ann.m_duration = 0; + ann.m_annotation = "TestEvent"; + + auto record = ProcessAnnotation(ann); + const auto &bytes = record(); + + // Expected layout: "+1.5" \x14 "TestEvent" \x14 \x00 + std::string content(bytes.begin(), bytes.end()); + + // Verify timestamp starts with '+' + CHECK(content[0] == '+'); + // Verify timestamp value is present + CHECK(content.find("+1.5") == 0); + + // Verify ANNOTATION_DIV (0x14 = 20) separates timestamp from annotation + size_t firstDiv = content.find(static_cast(20)); + REQUIRE(firstDiv != std::string::npos); + + // No duration means no DURATION_DIV (21) before the ANNOTATION_DIV + for (size_t i = 0; i < firstDiv; ++i) { + CHECK(content[i] != static_cast(21)); + } + + // Verify annotation text follows the first div + std::string annotText = + content.substr(firstDiv + 1, std::string("TestEvent").size()); + CHECK(annotText == "TestEvent"); + + // Verify record ends with \x14 \x00 + CHECK(bytes[bytes.size() - 2] == static_cast(20)); + CHECK(bytes[bytes.size() - 1] == static_cast(0)); + } + + TEST_CASE("Negative start produces '-' prefix") { + Annotation ann; + ann.m_start = -2.0; + ann.m_duration = 0; + ann.m_annotation = "Onset"; + + auto record = ProcessAnnotation(ann); + const auto &bytes = record(); + std::string content(bytes.begin(), bytes.end()); + + // Negative start should begin with '-', not '+' + CHECK(content[0] == '-'); + CHECK(content.find("-2") == 0); + } + + TEST_CASE("Positive duration includes duration field") { + Annotation ann; + ann.m_start = 10.0; + ann.m_duration = 2.5; + ann.m_annotation = "Stimulus"; + + auto record = ProcessAnnotation(ann); + const auto &bytes = record(); + std::string content(bytes.begin(), bytes.end()); + + // Layout: "+10" \x15 "2.5" \x14 "Stimulus" \x14 \x00 + // DURATION_DIV (21 = 0x15) must be present + size_t durDiv = content.find(static_cast(21)); + REQUIRE(durDiv != std::string::npos); + + // Duration text follows the DURATION_DIV + size_t annotDiv = content.find(static_cast(20)); + std::string durText = content.substr(durDiv + 1, annotDiv - durDiv - 1); + CHECK(durText == "2.5"); + } + + TEST_CASE("Zero duration omits duration field") { + Annotation ann; + ann.m_start = 5.0; + ann.m_duration = 0.0; + ann.m_annotation = "Marker"; + + auto record = ProcessAnnotation(ann); + const auto &bytes = record(); + std::string content(bytes.begin(), bytes.end()); + + // No DURATION_DIV (21) should appear before the first ANNOTATION_DIV (20) + size_t annotDiv = content.find(static_cast(20)); + REQUIRE(annotDiv != std::string::npos); + for (size_t i = 0; i < annotDiv; ++i) { + CHECK(content[i] != static_cast(21)); + } + } + + TEST_CASE("Empty annotation string throws") { + Annotation ann; + ann.m_start = 0.0; + ann.m_duration = 0.0; + ann.m_annotation = ""; + + CHECK_THROWS_AS(ProcessAnnotation(ann), std::invalid_argument); + } + + TEST_CASE("Zero start gets '+' prefix") { + Annotation ann; + ann.m_start = 0.0; + ann.m_duration = 0.0; + ann.m_annotation = "Start"; + + auto record = ProcessAnnotation(ann); + const auto &bytes = record(); + + // 0.0 >= 0, so '+' prefix + CHECK(bytes[0] == '+'); + } + + TEST_CASE("Annotation record has correct total size") { + Annotation ann; + ann.m_start = 3.0; + ann.m_duration = 1.5; + ann.m_annotation = "Event"; + + auto record = ProcessAnnotation(ann); + + // Expected: "+3" (2) + \x15 (1) + "1.5" (3) + \x14 (1) + "Event" (5) + + // \x14 (1) + \x00 (1) = 14 + CHECK(record.Size() == 14); + } + +} // TEST_SUITE "ProcessAnnotation" + +// =========================================================================== +// TEST SUITE: Sample conversion round-trip +// =========================================================================== +TEST_SUITE("Sample conversion round-trip") { + + TEST_CASE("Digital 2-byte round-trip: encode then decode") { + // Use identity conversion (offset=0, scaling=1) + const double offset = 0.0; + const double scaling = 1.0; + const uint32_t sampleSize = 2; // EDF + + ProcessorSample encoder(offset, scaling, + sampleSize); + ProcessorSampleRecord decoder(offset, scaling); + + SUBCASE("Positive value") { + int32_t original = 1234; + auto record = encoder(original); + REQUIRE(record.Size() == 2); + int32_t decoded = decoder(record); + CHECK(decoded == original); + } + + SUBCASE("Negative value") { + int32_t original = -1234; + auto record = encoder(original); + REQUIRE(record.Size() == 2); + int32_t decoded = decoder(record); + CHECK(decoded == original); + } + + SUBCASE("Zero value") { + int32_t original = 0; + auto record = encoder(original); + REQUIRE(record.Size() == 2); + int32_t decoded = decoder(record); + CHECK(decoded == original); + } + } + + TEST_CASE("Digital 3-byte (BDF) round-trip: encode then decode") { + const double offset = 0.0; + const double scaling = 1.0; + const uint32_t sampleSize = 3; // BDF + + ProcessorSample encoder(offset, scaling, + sampleSize); + ProcessorSampleRecord decoder(offset, scaling); + + SUBCASE("Positive value") { + int32_t original = 100000; + auto record = encoder(original); + REQUIRE(record.Size() == 3); + int32_t decoded = decoder(record); + CHECK(decoded == original); + } + + SUBCASE("Negative value") { + int32_t original = -100000; + auto record = encoder(original); + REQUIRE(record.Size() == 3); + int32_t decoded = decoder(record); + CHECK(decoded == original); + } + + SUBCASE("Zero value") { + int32_t original = 0; + auto record = encoder(original); + REQUIRE(record.Size() == 3); + int32_t decoded = decoder(record); + CHECK(decoded == original); + } + } + + TEST_CASE("Physical to digital round-trip through records") { + // Simulate a real EDF signal: physMin=-500, physMax=500, + // digMin=-32768, digMax=32767 + const double physMin = -500.0; + const double physMax = 500.0; + const int32_t digMin = -32768; + const int32_t digMax = 32767; + const double scaling = (physMax - physMin) / (digMax - digMin); + const double offset = physMin - scaling * digMin; + const uint32_t sampleSize = 2; + + // Physical -> Digital -> Record -> Digital -> Physical + double physValue = 123.456; + int32_t digital = ConvertSample(offset, scaling, physValue); + + ProcessorSample encoder(offset, scaling, + sampleSize); + ProcessorSampleRecord decoder(offset, scaling); + + auto record = encoder(digital); + int32_t decodedDigital = decoder(record); + + // Digital value must survive the record round-trip exactly + CHECK(decodedDigital == digital); + + // Convert back to physical + double decodedPhysical = ConvertSample(offset, scaling, decodedDigital); + // Allow small error due to quantization + CHECK(decodedPhysical == doctest::Approx(physValue).epsilon(0.001)); + } + + TEST_CASE("2-byte boundary values round-trip") { + const double offset = 0.0; + const double scaling = 1.0; + const uint32_t sampleSize = 2; + + ProcessorSample encoder(offset, scaling, + sampleSize); + ProcessorSampleRecord decoder(offset, scaling); + + SUBCASE("Max positive: 32767") { + int32_t original = 32767; + auto record = encoder(original); + int32_t decoded = decoder(record); + CHECK(decoded == 32767); + } + + SUBCASE("Min negative: -32768") { + int32_t original = -32768; + auto record = encoder(original); + int32_t decoded = decoder(record); + CHECK(decoded == -32768); + } + + SUBCASE("Minus one: -1") { + int32_t original = -1; + auto record = encoder(original); + int32_t decoded = decoder(record); + CHECK(decoded == -1); + } + + SUBCASE("Plus one: 1") { + int32_t original = 1; + auto record = encoder(original); + int32_t decoded = decoder(record); + CHECK(decoded == 1); + } + } + + TEST_CASE("3-byte boundary values round-trip") { + const double offset = 0.0; + const double scaling = 1.0; + const uint32_t sampleSize = 3; + + ProcessorSample encoder(offset, scaling, + sampleSize); + ProcessorSampleRecord decoder(offset, scaling); + + SUBCASE("Max positive: 8388607") { + int32_t original = 8388607; + auto record = encoder(original); + int32_t decoded = decoder(record); + CHECK(decoded == 8388607); + } + + SUBCASE("Min negative: -8388608") { + int32_t original = -8388608; + auto record = encoder(original); + int32_t decoded = decoder(record); + CHECK(decoded == -8388608); + } + + SUBCASE("Minus one: -1") { + int32_t original = -1; + auto record = encoder(original); + int32_t decoded = decoder(record); + CHECK(decoded == -1); + } + } + + TEST_CASE("ConvertSample digital-to-physical and back") { + const double physMin = -3200.0; + const double physMax = 3200.0; + const int32_t digMin = -8388608; + const int32_t digMax = 8388607; + const double scaling = (physMax - physMin) / (digMax - digMin); + const double offset = physMin - scaling * digMin; + + SUBCASE("Mid-range digital value") { + int32_t digital = 0; + double physical = ConvertSample(offset, scaling, digital); + int32_t backDigital = ConvertSample(offset, scaling, physical); + CHECK(backDigital == digital); + } + + SUBCASE("Max digital value") { + int32_t digital = digMax; + double physical = ConvertSample(offset, scaling, digital); + CHECK(physical == doctest::Approx(physMax).epsilon(0.001)); + } + + SUBCASE("Min digital value") { + int32_t digital = digMin; + double physical = ConvertSample(offset, scaling, digital); + CHECK(physical == doctest::Approx(physMin).epsilon(0.001)); + } + } + + TEST_CASE("Physical round-trip via ProcessorSample") { + // Use Physical sample type which internally converts phys->dig->record + const double physMin = -500.0; + const double physMax = 500.0; + const int32_t digMin = -32768; + const int32_t digMax = 32767; + const double scaling = (physMax - physMin) / (digMax - digMin); + const double offset = physMin - scaling * digMin; + const uint32_t sampleSize = 2; + + ProcessorSample encoder(offset, scaling, + sampleSize); + ProcessorSampleRecord decoder(offset, scaling); + + SUBCASE("Positive physical value") { + double original = 250.0; + auto record = encoder(original); + double decoded = decoder(record); + CHECK(decoded == doctest::Approx(original).epsilon(0.1)); + } + + SUBCASE("Negative physical value") { + double original = -250.0; + auto record = encoder(original); + double decoded = decoder(record); + CHECK(decoded == doctest::Approx(original).epsilon(0.1)); + } + + SUBCASE("Zero physical value") { + double original = 0.0; + auto record = encoder(original); + double decoded = decoder(record); + CHECK(decoded == doctest::Approx(original).epsilon(0.1)); + } + } + +} // TEST_SUITE "Sample conversion round-trip" + +// =========================================================================== +// TEST SUITE: detail::to_string_decimal +// =========================================================================== +TEST_SUITE("to_string_decimal") { + + TEST_CASE("Integer values have no trailing zeros or decimal point") { + // 5.0 should become "5", not "5.000000" + auto result = detail::to_string_decimal(5.0); + CHECK(result == "5"); + + result = detail::to_string_decimal(100.0); + CHECK(result == "100"); + + result = detail::to_string_decimal(0.0); + CHECK(result == "0"); + } + + TEST_CASE("Decimal values have trailing zeros trimmed") { + // 2.5 should become "2.5", not "2.500000" + auto result = detail::to_string_decimal(2.5); + CHECK(result == "2.5"); + + result = detail::to_string_decimal(1.25); + CHECK(result == "1.25"); + + result = detail::to_string_decimal(3.1); + CHECK(result == "3.1"); + } + + TEST_CASE("Negative integer values") { + auto result = detail::to_string_decimal(-10.0); + CHECK(result == "-10"); + + result = detail::to_string_decimal(-1.0); + CHECK(result == "-1"); + } + + TEST_CASE("Negative decimal values") { + auto result = detail::to_string_decimal(-2.5); + CHECK(result == "-2.5"); + + result = detail::to_string_decimal(-0.125); + CHECK(result == "-0.125"); + } + + TEST_CASE("Small fractional values") { + auto result = detail::to_string_decimal(0.5); + CHECK(result == "0.5"); + + result = detail::to_string_decimal(0.1); + // std::to_string(0.1) gives "0.100000", trimmed to "0.1" + CHECK(result == "0.1"); + } + + TEST_CASE("Large integer values") { + auto result = detail::to_string_decimal(32767.0); + CHECK(result == "32767"); + + result = detail::to_string_decimal(-32768.0); + CHECK(result == "-32768"); + } + +} // TEST_SUITE "to_string_decimal" diff --git a/tests/test_reader.cpp b/tests/test_reader.cpp new file mode 100644 index 0000000..b3e2e98 --- /dev/null +++ b/tests/test_reader.cpp @@ -0,0 +1,38 @@ +#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN +#include +#include +#include + +using namespace edfio; + +TEST_CASE("Read Calib5.edf header successfully") { + std::ifstream stream("Calib5.edf", std::ios::binary); + REQUIRE(stream.is_open()); + auto header = ReadHeaderExam(stream); + + CHECK(header.m_general.m_totalSignals > 0); + CHECK(header.m_general.m_datarecordsFile > 0); + CHECK(header.m_general.m_datarecordDuration > 0); + CHECK(header.m_general.m_headerSize > 0); + CHECK(header.m_signals.size() == static_cast(header.m_general.m_totalSignals)); +} + +TEST_CASE("Calib5.edf is plain EDF format") { + std::ifstream stream("Calib5.edf", std::ios::binary); + REQUIRE(stream.is_open()); + auto header = ReadHeaderExam(stream); + + CHECK(IsEdf(header.m_general.m_version)); + CHECK_FALSE(IsBdf(header.m_general.m_version)); +} + +TEST_CASE("Calib5.edf signal headers are valid") { + std::ifstream stream("Calib5.edf", std::ios::binary); + REQUIRE(stream.is_open()); + auto header = ReadHeaderExam(stream); + + for (auto const& sig : header.m_signals) { + CHECK(sig.m_samplesInDataRecord > 0); + CHECK(sig.m_digitalMax > sig.m_digitalMin); + } +} diff --git a/tests/test_record.cpp b/tests/test_record.cpp new file mode 100644 index 0000000..ebf2ca0 --- /dev/null +++ b/tests/test_record.cpp @@ -0,0 +1,45 @@ +#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN +#include +#include + +TEST_CASE("Record is assignable") { + edfio::Record a(10); + a()[0] = 'X'; + edfio::Record b(10); + b = a; // Must compile and work + CHECK(b()[0] == 'X'); + CHECK(b.Size() == 10); +} + +TEST_CASE("Record move-assignment works") { + edfio::Record a(5); + a()[0] = 42; + edfio::Record b(5); + b = std::move(a); + CHECK(b()[0] == 42); +} + +TEST_CASE("Record concatenation") { + edfio::Record a(3); + edfio::Record b(2); + a()[0] = 1; a()[1] = 2; a()[2] = 3; + b()[0] = 4; b()[1] = 5; + auto c = a + b; + CHECK(c.Size() == 5); + CHECK(c()[3] == 4); +} + +TEST_CASE("Record Size derives from vector") { + edfio::Record r(7); + CHECK(r.Size() == 7); + CHECK(r.Size() == r().size()); +} + +TEST_CASE("Record copy construction") { + edfio::Record a(3); + a()[0] = 'A'; a()[1] = 'B'; a()[2] = 'C'; + edfio::Record b(a); + CHECK(b.Size() == 3); + CHECK(b()[0] == 'A'); + CHECK(b()[2] == 'C'); +} diff --git a/tests/test_writer.cpp b/tests/test_writer.cpp new file mode 100644 index 0000000..addd35c --- /dev/null +++ b/tests/test_writer.cpp @@ -0,0 +1,46 @@ +#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN +#include +#include +#include +#include + +using namespace edfio; + +TEST_CASE("Write and read back header round-trip") { + // Read original + std::ifstream instream("Calib5.edf", std::ios::binary); + REQUIRE(instream.is_open()); + auto header = ReadHeaderExam(instream); + instream.close(); + + // Write to temp file + const char* tmpfile = "test_roundtrip.edf"; + { + std::ofstream outstream(tmpfile, std::ios::binary); + REQUIRE(outstream.is_open()); + WriteHeaderExam(outstream, header); + + // Also write data records + std::ifstream instream2("Calib5.edf", std::ios::binary); + auto store = detail::CreateDataRecordStore(instream2, header.m_general); + auto sink = detail::CreateDataRecordSink(outstream, header.m_general); + auto sink_it = sink.begin(); + for (auto it = store.begin(); it != store.end(); ++it) { + *sink_it = *it; + ++sink_it; + } + } + + // Read back + std::ifstream checkstream(tmpfile, std::ios::binary); + REQUIRE(checkstream.is_open()); + auto header2 = ReadHeaderExam(checkstream); + + CHECK(header2.m_general.m_totalSignals == header.m_general.m_totalSignals); + CHECK(header2.m_general.m_datarecordsFile == header.m_general.m_datarecordsFile); + CHECK(header2.m_general.m_datarecordDuration == doctest::Approx(header.m_general.m_datarecordDuration)); + CHECK(header2.m_signals.size() == header.m_signals.size()); + + checkstream.close(); + std::remove(tmpfile); +} diff --git a/third_party/doctest/doctest.h b/third_party/doctest/doctest.h new file mode 100644 index 0000000..5c754cd --- /dev/null +++ b/third_party/doctest/doctest.h @@ -0,0 +1,7106 @@ +// ====================================================================== lgtm [cpp/missing-header-guard] +// == DO NOT MODIFY THIS FILE BY HAND - IT IS AUTO GENERATED BY CMAKE! == +// ====================================================================== +// +// doctest.h - the lightest feature-rich C++ single-header testing framework for unit tests and TDD +// +// Copyright (c) 2016-2023 Viktor Kirilov +// +// Distributed under the MIT Software License +// See accompanying file LICENSE.txt or copy at +// https://opensource.org/licenses/MIT +// +// The documentation can be found at the library's page: +// https://github.com/doctest/doctest/blob/master/doc/markdown/readme.md +// +// ================================================================================================= +// ================================================================================================= +// ================================================================================================= +// +// The library is heavily influenced by Catch - https://github.com/catchorg/Catch2 +// which uses the Boost Software License - Version 1.0 +// see here - https://github.com/catchorg/Catch2/blob/master/LICENSE.txt +// +// The concept of subcases (sections in Catch) and expression decomposition are from there. +// Some parts of the code are taken directly: +// - stringification - the detection of "ostream& operator<<(ostream&, const T&)" and StringMaker<> +// - the Approx() helper class for floating point comparison +// - colors in the console +// - breaking into a debugger +// - signal / SEH handling +// - timer +// - XmlWriter class - thanks to Phil Nash for allowing the direct reuse (AKA copy/paste) +// +// The expression decomposing templates are taken from lest - https://github.com/martinmoene/lest +// which uses the Boost Software License - Version 1.0 +// see here - https://github.com/martinmoene/lest/blob/master/LICENSE.txt +// +// ================================================================================================= +// ================================================================================================= +// ================================================================================================= + +#ifndef DOCTEST_LIBRARY_INCLUDED +#define DOCTEST_LIBRARY_INCLUDED + +// ================================================================================================= +// == VERSION ====================================================================================== +// ================================================================================================= + +#define DOCTEST_VERSION_MAJOR 2 +#define DOCTEST_VERSION_MINOR 4 +#define DOCTEST_VERSION_PATCH 11 + +// util we need here +#define DOCTEST_TOSTR_IMPL(x) #x +#define DOCTEST_TOSTR(x) DOCTEST_TOSTR_IMPL(x) + +#define DOCTEST_VERSION_STR \ + DOCTEST_TOSTR(DOCTEST_VERSION_MAJOR) "." \ + DOCTEST_TOSTR(DOCTEST_VERSION_MINOR) "." \ + DOCTEST_TOSTR(DOCTEST_VERSION_PATCH) + +#define DOCTEST_VERSION \ + (DOCTEST_VERSION_MAJOR * 10000 + DOCTEST_VERSION_MINOR * 100 + DOCTEST_VERSION_PATCH) + +// ================================================================================================= +// == COMPILER VERSION ============================================================================= +// ================================================================================================= + +// ideas for the version stuff are taken from here: https://github.com/cxxstuff/cxx_detect + +#ifdef _MSC_VER +#define DOCTEST_CPLUSPLUS _MSVC_LANG +#else +#define DOCTEST_CPLUSPLUS __cplusplus +#endif + +#define DOCTEST_COMPILER(MAJOR, MINOR, PATCH) ((MAJOR)*10000000 + (MINOR)*100000 + (PATCH)) + +// GCC/Clang and GCC/MSVC are mutually exclusive, but Clang/MSVC are not because of clang-cl... +#if defined(_MSC_VER) && defined(_MSC_FULL_VER) +#if _MSC_VER == _MSC_FULL_VER / 10000 +#define DOCTEST_MSVC DOCTEST_COMPILER(_MSC_VER / 100, _MSC_VER % 100, _MSC_FULL_VER % 10000) +#else // MSVC +#define DOCTEST_MSVC \ + DOCTEST_COMPILER(_MSC_VER / 100, (_MSC_FULL_VER / 100000) % 100, _MSC_FULL_VER % 100000) +#endif // MSVC +#endif // MSVC +#if defined(__clang__) && defined(__clang_minor__) && defined(__clang_patchlevel__) +#define DOCTEST_CLANG DOCTEST_COMPILER(__clang_major__, __clang_minor__, __clang_patchlevel__) +#elif defined(__GNUC__) && defined(__GNUC_MINOR__) && defined(__GNUC_PATCHLEVEL__) && \ + !defined(__INTEL_COMPILER) +#define DOCTEST_GCC DOCTEST_COMPILER(__GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__) +#endif // GCC +#if defined(__INTEL_COMPILER) +#define DOCTEST_ICC DOCTEST_COMPILER(__INTEL_COMPILER / 100, __INTEL_COMPILER % 100, 0) +#endif // ICC + +#ifndef DOCTEST_MSVC +#define DOCTEST_MSVC 0 +#endif // DOCTEST_MSVC +#ifndef DOCTEST_CLANG +#define DOCTEST_CLANG 0 +#endif // DOCTEST_CLANG +#ifndef DOCTEST_GCC +#define DOCTEST_GCC 0 +#endif // DOCTEST_GCC +#ifndef DOCTEST_ICC +#define DOCTEST_ICC 0 +#endif // DOCTEST_ICC + +// ================================================================================================= +// == COMPILER WARNINGS HELPERS ==================================================================== +// ================================================================================================= + +#if DOCTEST_CLANG && !DOCTEST_ICC +#define DOCTEST_PRAGMA_TO_STR(x) _Pragma(#x) +#define DOCTEST_CLANG_SUPPRESS_WARNING_PUSH _Pragma("clang diagnostic push") +#define DOCTEST_CLANG_SUPPRESS_WARNING(w) DOCTEST_PRAGMA_TO_STR(clang diagnostic ignored w) +#define DOCTEST_CLANG_SUPPRESS_WARNING_POP _Pragma("clang diagnostic pop") +#define DOCTEST_CLANG_SUPPRESS_WARNING_WITH_PUSH(w) \ + DOCTEST_CLANG_SUPPRESS_WARNING_PUSH DOCTEST_CLANG_SUPPRESS_WARNING(w) +#else // DOCTEST_CLANG +#define DOCTEST_CLANG_SUPPRESS_WARNING_PUSH +#define DOCTEST_CLANG_SUPPRESS_WARNING(w) +#define DOCTEST_CLANG_SUPPRESS_WARNING_POP +#define DOCTEST_CLANG_SUPPRESS_WARNING_WITH_PUSH(w) +#endif // DOCTEST_CLANG + +#if DOCTEST_GCC +#define DOCTEST_PRAGMA_TO_STR(x) _Pragma(#x) +#define DOCTEST_GCC_SUPPRESS_WARNING_PUSH _Pragma("GCC diagnostic push") +#define DOCTEST_GCC_SUPPRESS_WARNING(w) DOCTEST_PRAGMA_TO_STR(GCC diagnostic ignored w) +#define DOCTEST_GCC_SUPPRESS_WARNING_POP _Pragma("GCC diagnostic pop") +#define DOCTEST_GCC_SUPPRESS_WARNING_WITH_PUSH(w) \ + DOCTEST_GCC_SUPPRESS_WARNING_PUSH DOCTEST_GCC_SUPPRESS_WARNING(w) +#else // DOCTEST_GCC +#define DOCTEST_GCC_SUPPRESS_WARNING_PUSH +#define DOCTEST_GCC_SUPPRESS_WARNING(w) +#define DOCTEST_GCC_SUPPRESS_WARNING_POP +#define DOCTEST_GCC_SUPPRESS_WARNING_WITH_PUSH(w) +#endif // DOCTEST_GCC + +#if DOCTEST_MSVC +#define DOCTEST_MSVC_SUPPRESS_WARNING_PUSH __pragma(warning(push)) +#define DOCTEST_MSVC_SUPPRESS_WARNING(w) __pragma(warning(disable : w)) +#define DOCTEST_MSVC_SUPPRESS_WARNING_POP __pragma(warning(pop)) +#define DOCTEST_MSVC_SUPPRESS_WARNING_WITH_PUSH(w) \ + DOCTEST_MSVC_SUPPRESS_WARNING_PUSH DOCTEST_MSVC_SUPPRESS_WARNING(w) +#else // DOCTEST_MSVC +#define DOCTEST_MSVC_SUPPRESS_WARNING_PUSH +#define DOCTEST_MSVC_SUPPRESS_WARNING(w) +#define DOCTEST_MSVC_SUPPRESS_WARNING_POP +#define DOCTEST_MSVC_SUPPRESS_WARNING_WITH_PUSH(w) +#endif // DOCTEST_MSVC + +// ================================================================================================= +// == COMPILER WARNINGS ============================================================================ +// ================================================================================================= + +// both the header and the implementation suppress all of these, +// so it only makes sense to aggregate them like so +#define DOCTEST_SUPPRESS_COMMON_WARNINGS_PUSH \ + DOCTEST_CLANG_SUPPRESS_WARNING_PUSH \ + DOCTEST_CLANG_SUPPRESS_WARNING("-Wunknown-pragmas") \ + DOCTEST_CLANG_SUPPRESS_WARNING("-Wweak-vtables") \ + DOCTEST_CLANG_SUPPRESS_WARNING("-Wpadded") \ + DOCTEST_CLANG_SUPPRESS_WARNING("-Wmissing-prototypes") \ + DOCTEST_CLANG_SUPPRESS_WARNING("-Wc++98-compat") \ + DOCTEST_CLANG_SUPPRESS_WARNING("-Wc++98-compat-pedantic") \ + \ + DOCTEST_GCC_SUPPRESS_WARNING_PUSH \ + DOCTEST_GCC_SUPPRESS_WARNING("-Wunknown-pragmas") \ + DOCTEST_GCC_SUPPRESS_WARNING("-Wpragmas") \ + DOCTEST_GCC_SUPPRESS_WARNING("-Weffc++") \ + DOCTEST_GCC_SUPPRESS_WARNING("-Wstrict-overflow") \ + DOCTEST_GCC_SUPPRESS_WARNING("-Wstrict-aliasing") \ + DOCTEST_GCC_SUPPRESS_WARNING("-Wmissing-declarations") \ + DOCTEST_GCC_SUPPRESS_WARNING("-Wuseless-cast") \ + DOCTEST_GCC_SUPPRESS_WARNING("-Wnoexcept") \ + \ + DOCTEST_MSVC_SUPPRESS_WARNING_PUSH \ + /* these 4 also disabled globally via cmake: */ \ + DOCTEST_MSVC_SUPPRESS_WARNING(4514) /* unreferenced inline function has been removed */ \ + DOCTEST_MSVC_SUPPRESS_WARNING(4571) /* SEH related */ \ + DOCTEST_MSVC_SUPPRESS_WARNING(4710) /* function not inlined */ \ + DOCTEST_MSVC_SUPPRESS_WARNING(4711) /* function selected for inline expansion*/ \ + /* common ones */ \ + DOCTEST_MSVC_SUPPRESS_WARNING(4616) /* invalid compiler warning */ \ + DOCTEST_MSVC_SUPPRESS_WARNING(4619) /* invalid compiler warning */ \ + DOCTEST_MSVC_SUPPRESS_WARNING(4996) /* The compiler encountered a deprecated declaration */ \ + DOCTEST_MSVC_SUPPRESS_WARNING(4706) /* assignment within conditional expression */ \ + DOCTEST_MSVC_SUPPRESS_WARNING(4512) /* 'class' : assignment operator could not be generated */ \ + DOCTEST_MSVC_SUPPRESS_WARNING(4127) /* conditional expression is constant */ \ + DOCTEST_MSVC_SUPPRESS_WARNING(4820) /* padding */ \ + DOCTEST_MSVC_SUPPRESS_WARNING(4625) /* copy constructor was implicitly deleted */ \ + DOCTEST_MSVC_SUPPRESS_WARNING(4626) /* assignment operator was implicitly deleted */ \ + DOCTEST_MSVC_SUPPRESS_WARNING(5027) /* move assignment operator implicitly deleted */ \ + DOCTEST_MSVC_SUPPRESS_WARNING(5026) /* move constructor was implicitly deleted */ \ + DOCTEST_MSVC_SUPPRESS_WARNING(4640) /* construction of local static object not thread-safe */ \ + DOCTEST_MSVC_SUPPRESS_WARNING(5045) /* Spectre mitigation for memory load */ \ + DOCTEST_MSVC_SUPPRESS_WARNING(5264) /* 'variable-name': 'const' variable is not used */ \ + /* static analysis */ \ + DOCTEST_MSVC_SUPPRESS_WARNING(26439) /* Function may not throw. Declare it 'noexcept' */ \ + DOCTEST_MSVC_SUPPRESS_WARNING(26495) /* Always initialize a member variable */ \ + DOCTEST_MSVC_SUPPRESS_WARNING(26451) /* Arithmetic overflow ... */ \ + DOCTEST_MSVC_SUPPRESS_WARNING(26444) /* Avoid unnamed objects with custom ctor and dtor... */ \ + DOCTEST_MSVC_SUPPRESS_WARNING(26812) /* Prefer 'enum class' over 'enum' */ + +#define DOCTEST_SUPPRESS_COMMON_WARNINGS_POP \ + DOCTEST_CLANG_SUPPRESS_WARNING_POP \ + DOCTEST_GCC_SUPPRESS_WARNING_POP \ + DOCTEST_MSVC_SUPPRESS_WARNING_POP + +DOCTEST_SUPPRESS_COMMON_WARNINGS_PUSH + +DOCTEST_CLANG_SUPPRESS_WARNING_PUSH +DOCTEST_CLANG_SUPPRESS_WARNING("-Wnon-virtual-dtor") +DOCTEST_CLANG_SUPPRESS_WARNING("-Wdeprecated") + +DOCTEST_GCC_SUPPRESS_WARNING_PUSH +DOCTEST_GCC_SUPPRESS_WARNING("-Wctor-dtor-privacy") +DOCTEST_GCC_SUPPRESS_WARNING("-Wnon-virtual-dtor") +DOCTEST_GCC_SUPPRESS_WARNING("-Wsign-promo") + +DOCTEST_MSVC_SUPPRESS_WARNING_PUSH +DOCTEST_MSVC_SUPPRESS_WARNING(4623) // default constructor was implicitly defined as deleted + +#define DOCTEST_MAKE_STD_HEADERS_CLEAN_FROM_WARNINGS_ON_WALL_BEGIN \ + DOCTEST_MSVC_SUPPRESS_WARNING_PUSH \ + DOCTEST_MSVC_SUPPRESS_WARNING(4548) /* before comma no effect; expected side - effect */ \ + DOCTEST_MSVC_SUPPRESS_WARNING(4265) /* virtual functions, but destructor is not virtual */ \ + DOCTEST_MSVC_SUPPRESS_WARNING(4986) /* exception specification does not match previous */ \ + DOCTEST_MSVC_SUPPRESS_WARNING(4350) /* 'member1' called instead of 'member2' */ \ + DOCTEST_MSVC_SUPPRESS_WARNING(4668) /* not defined as a preprocessor macro */ \ + DOCTEST_MSVC_SUPPRESS_WARNING(4365) /* signed/unsigned mismatch */ \ + DOCTEST_MSVC_SUPPRESS_WARNING(4774) /* format string not a string literal */ \ + DOCTEST_MSVC_SUPPRESS_WARNING(4820) /* padding */ \ + DOCTEST_MSVC_SUPPRESS_WARNING(4625) /* copy constructor was implicitly deleted */ \ + DOCTEST_MSVC_SUPPRESS_WARNING(4626) /* assignment operator was implicitly deleted */ \ + DOCTEST_MSVC_SUPPRESS_WARNING(5027) /* move assignment operator implicitly deleted */ \ + DOCTEST_MSVC_SUPPRESS_WARNING(5026) /* move constructor was implicitly deleted */ \ + DOCTEST_MSVC_SUPPRESS_WARNING(4623) /* default constructor was implicitly deleted */ \ + DOCTEST_MSVC_SUPPRESS_WARNING(5039) /* pointer to pot. throwing function passed to extern C */ \ + DOCTEST_MSVC_SUPPRESS_WARNING(5045) /* Spectre mitigation for memory load */ \ + DOCTEST_MSVC_SUPPRESS_WARNING(5105) /* macro producing 'defined' has undefined behavior */ \ + DOCTEST_MSVC_SUPPRESS_WARNING(4738) /* storing float result in memory, loss of performance */ \ + DOCTEST_MSVC_SUPPRESS_WARNING(5262) /* implicit fall-through */ + +#define DOCTEST_MAKE_STD_HEADERS_CLEAN_FROM_WARNINGS_ON_WALL_END DOCTEST_MSVC_SUPPRESS_WARNING_POP + +// ================================================================================================= +// == FEATURE DETECTION ============================================================================ +// ================================================================================================= + +// general compiler feature support table: https://en.cppreference.com/w/cpp/compiler_support +// MSVC C++11 feature support table: https://msdn.microsoft.com/en-us/library/hh567368.aspx +// GCC C++11 feature support table: https://gcc.gnu.org/projects/cxx-status.html +// MSVC version table: +// https://en.wikipedia.org/wiki/Microsoft_Visual_C%2B%2B#Internal_version_numbering +// MSVC++ 14.3 (17) _MSC_VER == 1930 (Visual Studio 2022) +// MSVC++ 14.2 (16) _MSC_VER == 1920 (Visual Studio 2019) +// MSVC++ 14.1 (15) _MSC_VER == 1910 (Visual Studio 2017) +// MSVC++ 14.0 _MSC_VER == 1900 (Visual Studio 2015) +// MSVC++ 12.0 _MSC_VER == 1800 (Visual Studio 2013) +// MSVC++ 11.0 _MSC_VER == 1700 (Visual Studio 2012) +// MSVC++ 10.0 _MSC_VER == 1600 (Visual Studio 2010) +// MSVC++ 9.0 _MSC_VER == 1500 (Visual Studio 2008) +// MSVC++ 8.0 _MSC_VER == 1400 (Visual Studio 2005) + +// Universal Windows Platform support +#if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP) +#define DOCTEST_CONFIG_NO_WINDOWS_SEH +#endif // WINAPI_FAMILY +#if DOCTEST_MSVC && !defined(DOCTEST_CONFIG_WINDOWS_SEH) +#define DOCTEST_CONFIG_WINDOWS_SEH +#endif // MSVC +#if defined(DOCTEST_CONFIG_NO_WINDOWS_SEH) && defined(DOCTEST_CONFIG_WINDOWS_SEH) +#undef DOCTEST_CONFIG_WINDOWS_SEH +#endif // DOCTEST_CONFIG_NO_WINDOWS_SEH + +#if !defined(_WIN32) && !defined(__QNX__) && !defined(DOCTEST_CONFIG_POSIX_SIGNALS) && \ + !defined(__EMSCRIPTEN__) && !defined(__wasi__) +#define DOCTEST_CONFIG_POSIX_SIGNALS +#endif // _WIN32 +#if defined(DOCTEST_CONFIG_NO_POSIX_SIGNALS) && defined(DOCTEST_CONFIG_POSIX_SIGNALS) +#undef DOCTEST_CONFIG_POSIX_SIGNALS +#endif // DOCTEST_CONFIG_NO_POSIX_SIGNALS + +#ifndef DOCTEST_CONFIG_NO_EXCEPTIONS +#if !defined(__cpp_exceptions) && !defined(__EXCEPTIONS) && !defined(_CPPUNWIND) \ + || defined(__wasi__) +#define DOCTEST_CONFIG_NO_EXCEPTIONS +#endif // no exceptions +#endif // DOCTEST_CONFIG_NO_EXCEPTIONS + +#ifdef DOCTEST_CONFIG_NO_EXCEPTIONS_BUT_WITH_ALL_ASSERTS +#ifndef DOCTEST_CONFIG_NO_EXCEPTIONS +#define DOCTEST_CONFIG_NO_EXCEPTIONS +#endif // DOCTEST_CONFIG_NO_EXCEPTIONS +#endif // DOCTEST_CONFIG_NO_EXCEPTIONS_BUT_WITH_ALL_ASSERTS + +#if defined(DOCTEST_CONFIG_NO_EXCEPTIONS) && !defined(DOCTEST_CONFIG_NO_TRY_CATCH_IN_ASSERTS) +#define DOCTEST_CONFIG_NO_TRY_CATCH_IN_ASSERTS +#endif // DOCTEST_CONFIG_NO_EXCEPTIONS && !DOCTEST_CONFIG_NO_TRY_CATCH_IN_ASSERTS + +#ifdef __wasi__ +#define DOCTEST_CONFIG_NO_MULTITHREADING +#endif + +#if defined(DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN) && !defined(DOCTEST_CONFIG_IMPLEMENT) +#define DOCTEST_CONFIG_IMPLEMENT +#endif // DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN + +#if defined(_WIN32) || defined(__CYGWIN__) +#if DOCTEST_MSVC +#define DOCTEST_SYMBOL_EXPORT __declspec(dllexport) +#define DOCTEST_SYMBOL_IMPORT __declspec(dllimport) +#else // MSVC +#define DOCTEST_SYMBOL_EXPORT __attribute__((dllexport)) +#define DOCTEST_SYMBOL_IMPORT __attribute__((dllimport)) +#endif // MSVC +#else // _WIN32 +#define DOCTEST_SYMBOL_EXPORT __attribute__((visibility("default"))) +#define DOCTEST_SYMBOL_IMPORT +#endif // _WIN32 + +#ifdef DOCTEST_CONFIG_IMPLEMENTATION_IN_DLL +#ifdef DOCTEST_CONFIG_IMPLEMENT +#define DOCTEST_INTERFACE DOCTEST_SYMBOL_EXPORT +#else // DOCTEST_CONFIG_IMPLEMENT +#define DOCTEST_INTERFACE DOCTEST_SYMBOL_IMPORT +#endif // DOCTEST_CONFIG_IMPLEMENT +#else // DOCTEST_CONFIG_IMPLEMENTATION_IN_DLL +#define DOCTEST_INTERFACE +#endif // DOCTEST_CONFIG_IMPLEMENTATION_IN_DLL + +// needed for extern template instantiations +// see https://github.com/fmtlib/fmt/issues/2228 +#if DOCTEST_MSVC +#define DOCTEST_INTERFACE_DECL +#define DOCTEST_INTERFACE_DEF DOCTEST_INTERFACE +#else // DOCTEST_MSVC +#define DOCTEST_INTERFACE_DECL DOCTEST_INTERFACE +#define DOCTEST_INTERFACE_DEF +#endif // DOCTEST_MSVC + +#define DOCTEST_EMPTY + +#if DOCTEST_MSVC +#define DOCTEST_NOINLINE __declspec(noinline) +#define DOCTEST_UNUSED +#define DOCTEST_ALIGNMENT(x) +#elif DOCTEST_CLANG && DOCTEST_CLANG < DOCTEST_COMPILER(3, 5, 0) +#define DOCTEST_NOINLINE +#define DOCTEST_UNUSED +#define DOCTEST_ALIGNMENT(x) +#else +#define DOCTEST_NOINLINE __attribute__((noinline)) +#define DOCTEST_UNUSED __attribute__((unused)) +#define DOCTEST_ALIGNMENT(x) __attribute__((aligned(x))) +#endif + +#ifdef DOCTEST_CONFIG_NO_CONTRADICTING_INLINE +#define DOCTEST_INLINE_NOINLINE inline +#else +#define DOCTEST_INLINE_NOINLINE inline DOCTEST_NOINLINE +#endif + +#ifndef DOCTEST_NORETURN +#if DOCTEST_MSVC && (DOCTEST_MSVC < DOCTEST_COMPILER(19, 0, 0)) +#define DOCTEST_NORETURN +#else // DOCTEST_MSVC +#define DOCTEST_NORETURN [[noreturn]] +#endif // DOCTEST_MSVC +#endif // DOCTEST_NORETURN + +#ifndef DOCTEST_NOEXCEPT +#if DOCTEST_MSVC && (DOCTEST_MSVC < DOCTEST_COMPILER(19, 0, 0)) +#define DOCTEST_NOEXCEPT +#else // DOCTEST_MSVC +#define DOCTEST_NOEXCEPT noexcept +#endif // DOCTEST_MSVC +#endif // DOCTEST_NOEXCEPT + +#ifndef DOCTEST_CONSTEXPR +#if DOCTEST_MSVC && (DOCTEST_MSVC < DOCTEST_COMPILER(19, 0, 0)) +#define DOCTEST_CONSTEXPR const +#define DOCTEST_CONSTEXPR_FUNC inline +#else // DOCTEST_MSVC +#define DOCTEST_CONSTEXPR constexpr +#define DOCTEST_CONSTEXPR_FUNC constexpr +#endif // DOCTEST_MSVC +#endif // DOCTEST_CONSTEXPR + +#ifndef DOCTEST_NO_SANITIZE_INTEGER +#if DOCTEST_CLANG >= DOCTEST_COMPILER(3, 7, 0) +#define DOCTEST_NO_SANITIZE_INTEGER __attribute__((no_sanitize("integer"))) +#else +#define DOCTEST_NO_SANITIZE_INTEGER +#endif +#endif // DOCTEST_NO_SANITIZE_INTEGER + +// ================================================================================================= +// == FEATURE DETECTION END ======================================================================== +// ================================================================================================= + +#define DOCTEST_DECLARE_INTERFACE(name) \ + virtual ~name(); \ + name() = default; \ + name(const name&) = delete; \ + name(name&&) = delete; \ + name& operator=(const name&) = delete; \ + name& operator=(name&&) = delete; + +#define DOCTEST_DEFINE_INTERFACE(name) \ + name::~name() = default; + +// internal macros for string concatenation and anonymous variable name generation +#define DOCTEST_CAT_IMPL(s1, s2) s1##s2 +#define DOCTEST_CAT(s1, s2) DOCTEST_CAT_IMPL(s1, s2) +#ifdef __COUNTER__ // not standard and may be missing for some compilers +#define DOCTEST_ANONYMOUS(x) DOCTEST_CAT(x, __COUNTER__) +#else // __COUNTER__ +#define DOCTEST_ANONYMOUS(x) DOCTEST_CAT(x, __LINE__) +#endif // __COUNTER__ + +#ifndef DOCTEST_CONFIG_ASSERTION_PARAMETERS_BY_VALUE +#define DOCTEST_REF_WRAP(x) x& +#else // DOCTEST_CONFIG_ASSERTION_PARAMETERS_BY_VALUE +#define DOCTEST_REF_WRAP(x) x +#endif // DOCTEST_CONFIG_ASSERTION_PARAMETERS_BY_VALUE + +// not using __APPLE__ because... this is how Catch does it +#ifdef __MAC_OS_X_VERSION_MIN_REQUIRED +#define DOCTEST_PLATFORM_MAC +#elif defined(__IPHONE_OS_VERSION_MIN_REQUIRED) +#define DOCTEST_PLATFORM_IPHONE +#elif defined(_WIN32) +#define DOCTEST_PLATFORM_WINDOWS +#elif defined(__wasi__) +#define DOCTEST_PLATFORM_WASI +#else // DOCTEST_PLATFORM +#define DOCTEST_PLATFORM_LINUX +#endif // DOCTEST_PLATFORM + +namespace doctest { namespace detail { + static DOCTEST_CONSTEXPR int consume(const int*, int) noexcept { return 0; } +}} + +#define DOCTEST_GLOBAL_NO_WARNINGS(var, ...) \ + DOCTEST_CLANG_SUPPRESS_WARNING_WITH_PUSH("-Wglobal-constructors") \ + static const int var = doctest::detail::consume(&var, __VA_ARGS__); \ + DOCTEST_CLANG_SUPPRESS_WARNING_POP + +#ifndef DOCTEST_BREAK_INTO_DEBUGGER +// should probably take a look at https://github.com/scottt/debugbreak +#ifdef DOCTEST_PLATFORM_LINUX +#if defined(__GNUC__) && (defined(__i386) || defined(__x86_64)) +// Break at the location of the failing check if possible +#define DOCTEST_BREAK_INTO_DEBUGGER() __asm__("int $3\n" : :) // NOLINT(hicpp-no-assembler) +#else +#include +#define DOCTEST_BREAK_INTO_DEBUGGER() raise(SIGTRAP) +#endif +#elif defined(DOCTEST_PLATFORM_MAC) +#if defined(__x86_64) || defined(__x86_64__) || defined(__amd64__) || defined(__i386) +#define DOCTEST_BREAK_INTO_DEBUGGER() __asm__("int $3\n" : :) // NOLINT(hicpp-no-assembler) +#elif defined(__ppc__) || defined(__ppc64__) +// https://www.cocoawithlove.com/2008/03/break-into-debugger.html +#define DOCTEST_BREAK_INTO_DEBUGGER() __asm__("li r0, 20\nsc\nnop\nli r0, 37\nli r4, 2\nsc\nnop\n": : : "memory","r0","r3","r4") // NOLINT(hicpp-no-assembler) +#else +#define DOCTEST_BREAK_INTO_DEBUGGER() __asm__("brk #0"); // NOLINT(hicpp-no-assembler) +#endif +#elif DOCTEST_MSVC +#define DOCTEST_BREAK_INTO_DEBUGGER() __debugbreak() +#elif defined(__MINGW32__) +DOCTEST_GCC_SUPPRESS_WARNING_WITH_PUSH("-Wredundant-decls") +extern "C" __declspec(dllimport) void __stdcall DebugBreak(); +DOCTEST_GCC_SUPPRESS_WARNING_POP +#define DOCTEST_BREAK_INTO_DEBUGGER() ::DebugBreak() +#else // linux +#define DOCTEST_BREAK_INTO_DEBUGGER() (static_cast(0)) +#endif // linux +#endif // DOCTEST_BREAK_INTO_DEBUGGER + +// this is kept here for backwards compatibility since the config option was changed +#ifdef DOCTEST_CONFIG_USE_IOSFWD +#ifndef DOCTEST_CONFIG_USE_STD_HEADERS +#define DOCTEST_CONFIG_USE_STD_HEADERS +#endif +#endif // DOCTEST_CONFIG_USE_IOSFWD + +// for clang - always include ciso646 (which drags some std stuff) because +// we want to check if we are using libc++ with the _LIBCPP_VERSION macro in +// which case we don't want to forward declare stuff from std - for reference: +// https://github.com/doctest/doctest/issues/126 +// https://github.com/doctest/doctest/issues/356 +#if DOCTEST_CLANG +#include +#endif // clang + +#ifdef _LIBCPP_VERSION +#ifndef DOCTEST_CONFIG_USE_STD_HEADERS +#define DOCTEST_CONFIG_USE_STD_HEADERS +#endif +#endif // _LIBCPP_VERSION + +#ifdef DOCTEST_CONFIG_USE_STD_HEADERS +#ifndef DOCTEST_CONFIG_INCLUDE_TYPE_TRAITS +#define DOCTEST_CONFIG_INCLUDE_TYPE_TRAITS +#endif // DOCTEST_CONFIG_INCLUDE_TYPE_TRAITS +DOCTEST_MAKE_STD_HEADERS_CLEAN_FROM_WARNINGS_ON_WALL_BEGIN +#include +#include +#include +DOCTEST_MAKE_STD_HEADERS_CLEAN_FROM_WARNINGS_ON_WALL_END +#else // DOCTEST_CONFIG_USE_STD_HEADERS + +// Forward declaring 'X' in namespace std is not permitted by the C++ Standard. +DOCTEST_MSVC_SUPPRESS_WARNING_WITH_PUSH(4643) + +namespace std { // NOLINT(cert-dcl58-cpp) +typedef decltype(nullptr) nullptr_t; // NOLINT(modernize-use-using) +typedef decltype(sizeof(void*)) size_t; // NOLINT(modernize-use-using) +template +struct char_traits; +template <> +struct char_traits; +template +class basic_ostream; // NOLINT(fuchsia-virtual-inheritance) +typedef basic_ostream> ostream; // NOLINT(modernize-use-using) +template +// NOLINTNEXTLINE +basic_ostream& operator<<(basic_ostream&, const char*); +template +class basic_istream; +typedef basic_istream> istream; // NOLINT(modernize-use-using) +template +class tuple; +#if DOCTEST_MSVC >= DOCTEST_COMPILER(19, 20, 0) +// see this issue on why this is needed: https://github.com/doctest/doctest/issues/183 +template +class allocator; +template +class basic_string; +using string = basic_string, allocator>; +#endif // VS 2019 +} // namespace std + +DOCTEST_MSVC_SUPPRESS_WARNING_POP + +#endif // DOCTEST_CONFIG_USE_STD_HEADERS + +#ifdef DOCTEST_CONFIG_INCLUDE_TYPE_TRAITS +#include +#endif // DOCTEST_CONFIG_INCLUDE_TYPE_TRAITS + +namespace doctest { + +using std::size_t; + +DOCTEST_INTERFACE extern bool is_running_in_test; + +#ifndef DOCTEST_CONFIG_STRING_SIZE_TYPE +#define DOCTEST_CONFIG_STRING_SIZE_TYPE unsigned +#endif + +// A 24 byte string class (can be as small as 17 for x64 and 13 for x86) that can hold strings with length +// of up to 23 chars on the stack before going on the heap - the last byte of the buffer is used for: +// - "is small" bit - the highest bit - if "0" then it is small - otherwise its "1" (128) +// - if small - capacity left before going on the heap - using the lowest 5 bits +// - if small - 2 bits are left unused - the second and third highest ones +// - if small - acts as a null terminator if strlen() is 23 (24 including the null terminator) +// and the "is small" bit remains "0" ("as well as the capacity left") so its OK +// Idea taken from this lecture about the string implementation of facebook/folly - fbstring +// https://www.youtube.com/watch?v=kPR8h4-qZdk +// TODO: +// - optimizations - like not deleting memory unnecessarily in operator= and etc. +// - resize/reserve/clear +// - replace +// - back/front +// - iterator stuff +// - find & friends +// - push_back/pop_back +// - assign/insert/erase +// - relational operators as free functions - taking const char* as one of the params +class DOCTEST_INTERFACE String +{ +public: + using size_type = DOCTEST_CONFIG_STRING_SIZE_TYPE; + +private: + static DOCTEST_CONSTEXPR size_type len = 24; //!OCLINT avoid private static members + static DOCTEST_CONSTEXPR size_type last = len - 1; //!OCLINT avoid private static members + + struct view // len should be more than sizeof(view) - because of the final byte for flags + { + char* ptr; + size_type size; + size_type capacity; + }; + + union + { + char buf[len]; // NOLINT(*-avoid-c-arrays) + view data; + }; + + char* allocate(size_type sz); + + bool isOnStack() const noexcept { return (buf[last] & 128) == 0; } + void setOnHeap() noexcept; + void setLast(size_type in = last) noexcept; + void setSize(size_type sz) noexcept; + + void copy(const String& other); + +public: + static DOCTEST_CONSTEXPR size_type npos = static_cast(-1); + + String() noexcept; + ~String(); + + // cppcheck-suppress noExplicitConstructor + String(const char* in); + String(const char* in, size_type in_size); + + String(std::istream& in, size_type in_size); + + String(const String& other); + String& operator=(const String& other); + + String& operator+=(const String& other); + + String(String&& other) noexcept; + String& operator=(String&& other) noexcept; + + char operator[](size_type i) const; + char& operator[](size_type i); + + // the only functions I'm willing to leave in the interface - available for inlining + const char* c_str() const { return const_cast(this)->c_str(); } // NOLINT + char* c_str() { + if (isOnStack()) { + return reinterpret_cast(buf); + } + return data.ptr; + } + + size_type size() const; + size_type capacity() const; + + String substr(size_type pos, size_type cnt = npos) &&; + String substr(size_type pos, size_type cnt = npos) const &; + + size_type find(char ch, size_type pos = 0) const; + size_type rfind(char ch, size_type pos = npos) const; + + int compare(const char* other, bool no_case = false) const; + int compare(const String& other, bool no_case = false) const; + +friend DOCTEST_INTERFACE std::ostream& operator<<(std::ostream& s, const String& in); +}; + +DOCTEST_INTERFACE String operator+(const String& lhs, const String& rhs); + +DOCTEST_INTERFACE bool operator==(const String& lhs, const String& rhs); +DOCTEST_INTERFACE bool operator!=(const String& lhs, const String& rhs); +DOCTEST_INTERFACE bool operator<(const String& lhs, const String& rhs); +DOCTEST_INTERFACE bool operator>(const String& lhs, const String& rhs); +DOCTEST_INTERFACE bool operator<=(const String& lhs, const String& rhs); +DOCTEST_INTERFACE bool operator>=(const String& lhs, const String& rhs); + +class DOCTEST_INTERFACE Contains { +public: + explicit Contains(const String& string); + + bool checkWith(const String& other) const; + + String string; +}; + +DOCTEST_INTERFACE String toString(const Contains& in); + +DOCTEST_INTERFACE bool operator==(const String& lhs, const Contains& rhs); +DOCTEST_INTERFACE bool operator==(const Contains& lhs, const String& rhs); +DOCTEST_INTERFACE bool operator!=(const String& lhs, const Contains& rhs); +DOCTEST_INTERFACE bool operator!=(const Contains& lhs, const String& rhs); + +namespace Color { + enum Enum + { + None = 0, + White, + Red, + Green, + Blue, + Cyan, + Yellow, + Grey, + + Bright = 0x10, + + BrightRed = Bright | Red, + BrightGreen = Bright | Green, + LightGrey = Bright | Grey, + BrightWhite = Bright | White + }; + + DOCTEST_INTERFACE std::ostream& operator<<(std::ostream& s, Color::Enum code); +} // namespace Color + +namespace assertType { + enum Enum + { + // macro traits + + is_warn = 1, + is_check = 2 * is_warn, + is_require = 2 * is_check, + + is_normal = 2 * is_require, + is_throws = 2 * is_normal, + is_throws_as = 2 * is_throws, + is_throws_with = 2 * is_throws_as, + is_nothrow = 2 * is_throws_with, + + is_false = 2 * is_nothrow, + is_unary = 2 * is_false, // not checked anywhere - used just to distinguish the types + + is_eq = 2 * is_unary, + is_ne = 2 * is_eq, + + is_lt = 2 * is_ne, + is_gt = 2 * is_lt, + + is_ge = 2 * is_gt, + is_le = 2 * is_ge, + + // macro types + + DT_WARN = is_normal | is_warn, + DT_CHECK = is_normal | is_check, + DT_REQUIRE = is_normal | is_require, + + DT_WARN_FALSE = is_normal | is_false | is_warn, + DT_CHECK_FALSE = is_normal | is_false | is_check, + DT_REQUIRE_FALSE = is_normal | is_false | is_require, + + DT_WARN_THROWS = is_throws | is_warn, + DT_CHECK_THROWS = is_throws | is_check, + DT_REQUIRE_THROWS = is_throws | is_require, + + DT_WARN_THROWS_AS = is_throws_as | is_warn, + DT_CHECK_THROWS_AS = is_throws_as | is_check, + DT_REQUIRE_THROWS_AS = is_throws_as | is_require, + + DT_WARN_THROWS_WITH = is_throws_with | is_warn, + DT_CHECK_THROWS_WITH = is_throws_with | is_check, + DT_REQUIRE_THROWS_WITH = is_throws_with | is_require, + + DT_WARN_THROWS_WITH_AS = is_throws_with | is_throws_as | is_warn, + DT_CHECK_THROWS_WITH_AS = is_throws_with | is_throws_as | is_check, + DT_REQUIRE_THROWS_WITH_AS = is_throws_with | is_throws_as | is_require, + + DT_WARN_NOTHROW = is_nothrow | is_warn, + DT_CHECK_NOTHROW = is_nothrow | is_check, + DT_REQUIRE_NOTHROW = is_nothrow | is_require, + + DT_WARN_EQ = is_normal | is_eq | is_warn, + DT_CHECK_EQ = is_normal | is_eq | is_check, + DT_REQUIRE_EQ = is_normal | is_eq | is_require, + + DT_WARN_NE = is_normal | is_ne | is_warn, + DT_CHECK_NE = is_normal | is_ne | is_check, + DT_REQUIRE_NE = is_normal | is_ne | is_require, + + DT_WARN_GT = is_normal | is_gt | is_warn, + DT_CHECK_GT = is_normal | is_gt | is_check, + DT_REQUIRE_GT = is_normal | is_gt | is_require, + + DT_WARN_LT = is_normal | is_lt | is_warn, + DT_CHECK_LT = is_normal | is_lt | is_check, + DT_REQUIRE_LT = is_normal | is_lt | is_require, + + DT_WARN_GE = is_normal | is_ge | is_warn, + DT_CHECK_GE = is_normal | is_ge | is_check, + DT_REQUIRE_GE = is_normal | is_ge | is_require, + + DT_WARN_LE = is_normal | is_le | is_warn, + DT_CHECK_LE = is_normal | is_le | is_check, + DT_REQUIRE_LE = is_normal | is_le | is_require, + + DT_WARN_UNARY = is_normal | is_unary | is_warn, + DT_CHECK_UNARY = is_normal | is_unary | is_check, + DT_REQUIRE_UNARY = is_normal | is_unary | is_require, + + DT_WARN_UNARY_FALSE = is_normal | is_false | is_unary | is_warn, + DT_CHECK_UNARY_FALSE = is_normal | is_false | is_unary | is_check, + DT_REQUIRE_UNARY_FALSE = is_normal | is_false | is_unary | is_require, + }; +} // namespace assertType + +DOCTEST_INTERFACE const char* assertString(assertType::Enum at); +DOCTEST_INTERFACE const char* failureString(assertType::Enum at); +DOCTEST_INTERFACE const char* skipPathFromFilename(const char* file); + +struct DOCTEST_INTERFACE TestCaseData +{ + String m_file; // the file in which the test was registered (using String - see #350) + unsigned m_line; // the line where the test was registered + const char* m_name; // name of the test case + const char* m_test_suite; // the test suite in which the test was added + const char* m_description; + bool m_skip; + bool m_no_breaks; + bool m_no_output; + bool m_may_fail; + bool m_should_fail; + int m_expected_failures; + double m_timeout; +}; + +struct DOCTEST_INTERFACE AssertData +{ + // common - for all asserts + const TestCaseData* m_test_case; + assertType::Enum m_at; + const char* m_file; + int m_line; + const char* m_expr; + bool m_failed; + + // exception-related - for all asserts + bool m_threw; + String m_exception; + + // for normal asserts + String m_decomp; + + // for specific exception-related asserts + bool m_threw_as; + const char* m_exception_type; + + class DOCTEST_INTERFACE StringContains { + private: + Contains content; + bool isContains; + + public: + StringContains(const String& str) : content(str), isContains(false) { } + StringContains(Contains cntn) : content(static_cast(cntn)), isContains(true) { } + + bool check(const String& str) { return isContains ? (content == str) : (content.string == str); } + + operator const String&() const { return content.string; } + + const char* c_str() const { return content.string.c_str(); } + } m_exception_string; + + AssertData(assertType::Enum at, const char* file, int line, const char* expr, + const char* exception_type, const StringContains& exception_string); +}; + +struct DOCTEST_INTERFACE MessageData +{ + String m_string; + const char* m_file; + int m_line; + assertType::Enum m_severity; +}; + +struct DOCTEST_INTERFACE SubcaseSignature +{ + String m_name; + const char* m_file; + int m_line; + + bool operator==(const SubcaseSignature& other) const; + bool operator<(const SubcaseSignature& other) const; +}; + +struct DOCTEST_INTERFACE IContextScope +{ + DOCTEST_DECLARE_INTERFACE(IContextScope) + virtual void stringify(std::ostream*) const = 0; +}; + +namespace detail { + struct DOCTEST_INTERFACE TestCase; +} // namespace detail + +struct ContextOptions //!OCLINT too many fields +{ + std::ostream* cout = nullptr; // stdout stream + String binary_name; // the test binary name + + const detail::TestCase* currentTest = nullptr; + + // == parameters from the command line + String out; // output filename + String order_by; // how tests should be ordered + unsigned rand_seed; // the seed for rand ordering + + unsigned first; // the first (matching) test to be executed + unsigned last; // the last (matching) test to be executed + + int abort_after; // stop tests after this many failed assertions + int subcase_filter_levels; // apply the subcase filters for the first N levels + + bool success; // include successful assertions in output + bool case_sensitive; // if filtering should be case sensitive + bool exit; // if the program should be exited after the tests are ran/whatever + bool duration; // print the time duration of each test case + bool minimal; // minimal console output (only test failures) + bool quiet; // no console output + bool no_throw; // to skip exceptions-related assertion macros + bool no_exitcode; // if the framework should return 0 as the exitcode + bool no_run; // to not run the tests at all (can be done with an "*" exclude) + bool no_intro; // to not print the intro of the framework + bool no_version; // to not print the version of the framework + bool no_colors; // if output to the console should be colorized + bool force_colors; // forces the use of colors even when a tty cannot be detected + bool no_breaks; // to not break into the debugger + bool no_skip; // don't skip test cases which are marked to be skipped + bool gnu_file_line; // if line numbers should be surrounded with :x: and not (x): + bool no_path_in_filenames; // if the path to files should be removed from the output + bool no_line_numbers; // if source code line numbers should be omitted from the output + bool no_debug_output; // no output in the debug console when a debugger is attached + bool no_skipped_summary; // don't print "skipped" in the summary !!! UNDOCUMENTED !!! + bool no_time_in_output; // omit any time/timestamps from output !!! UNDOCUMENTED !!! + + bool help; // to print the help + bool version; // to print the version + bool count; // if only the count of matching tests is to be retrieved + bool list_test_cases; // to list all tests matching the filters + bool list_test_suites; // to list all suites matching the filters + bool list_reporters; // lists all registered reporters +}; + +namespace detail { + namespace types { +#ifdef DOCTEST_CONFIG_INCLUDE_TYPE_TRAITS + using namespace std; +#else + template + struct enable_if { }; + + template + struct enable_if { using type = T; }; + + struct true_type { static DOCTEST_CONSTEXPR bool value = true; }; + struct false_type { static DOCTEST_CONSTEXPR bool value = false; }; + + template struct remove_reference { using type = T; }; + template struct remove_reference { using type = T; }; + template struct remove_reference { using type = T; }; + + template struct is_rvalue_reference : false_type { }; + template struct is_rvalue_reference : true_type { }; + + template struct remove_const { using type = T; }; + template struct remove_const { using type = T; }; + + // Compiler intrinsics + template struct is_enum { static DOCTEST_CONSTEXPR bool value = __is_enum(T); }; + template struct underlying_type { using type = __underlying_type(T); }; + + template struct is_pointer : false_type { }; + template struct is_pointer : true_type { }; + + template struct is_array : false_type { }; + // NOLINTNEXTLINE(*-avoid-c-arrays) + template struct is_array : true_type { }; +#endif + } + + // + template + T&& declval(); + + template + DOCTEST_CONSTEXPR_FUNC T&& forward(typename types::remove_reference::type& t) DOCTEST_NOEXCEPT { + return static_cast(t); + } + + template + DOCTEST_CONSTEXPR_FUNC T&& forward(typename types::remove_reference::type&& t) DOCTEST_NOEXCEPT { + return static_cast(t); + } + + template + struct deferred_false : types::false_type { }; + +// MSVS 2015 :( +#if !DOCTEST_CLANG && defined(_MSC_VER) && _MSC_VER <= 1900 + template + struct has_global_insertion_operator : types::false_type { }; + + template + struct has_global_insertion_operator(), declval()), void())> : types::true_type { }; + + template + struct has_insertion_operator { static DOCTEST_CONSTEXPR bool value = has_global_insertion_operator::value; }; + + template + struct insert_hack; + + template + struct insert_hack { + static void insert(std::ostream& os, const T& t) { ::operator<<(os, t); } + }; + + template + struct insert_hack { + static void insert(std::ostream& os, const T& t) { operator<<(os, t); } + }; + + template + using insert_hack_t = insert_hack::value>; +#else + template + struct has_insertion_operator : types::false_type { }; +#endif + + template + struct has_insertion_operator(), declval()), void())> : types::true_type { }; + + template + struct should_stringify_as_underlying_type { + static DOCTEST_CONSTEXPR bool value = detail::types::is_enum::value && !doctest::detail::has_insertion_operator::value; + }; + + DOCTEST_INTERFACE std::ostream* tlssPush(); + DOCTEST_INTERFACE String tlssPop(); + + template + struct StringMakerBase { + template + static String convert(const DOCTEST_REF_WRAP(T)) { +#ifdef DOCTEST_CONFIG_REQUIRE_STRINGIFICATION_FOR_ALL_USED_TYPES + static_assert(deferred_false::value, "No stringification detected for type T. See string conversion manual"); +#endif + return "{?}"; + } + }; + + template + struct filldata; + + template + void filloss(std::ostream* stream, const T& in) { + filldata::fill(stream, in); + } + + template + void filloss(std::ostream* stream, const T (&in)[N]) { // NOLINT(*-avoid-c-arrays) + // T[N], T(&)[N], T(&&)[N] have same behaviour. + // Hence remove reference. + filloss::type>(stream, in); + } + + template + String toStream(const T& in) { + std::ostream* stream = tlssPush(); + filloss(stream, in); + return tlssPop(); + } + + template <> + struct StringMakerBase { + template + static String convert(const DOCTEST_REF_WRAP(T) in) { + return toStream(in); + } + }; +} // namespace detail + +template +struct StringMaker : public detail::StringMakerBase< + detail::has_insertion_operator::value || detail::types::is_pointer::value || detail::types::is_array::value> +{}; + +#ifndef DOCTEST_STRINGIFY +#ifdef DOCTEST_CONFIG_DOUBLE_STRINGIFY +#define DOCTEST_STRINGIFY(...) toString(toString(__VA_ARGS__)) +#else +#define DOCTEST_STRINGIFY(...) toString(__VA_ARGS__) +#endif +#endif + +template +String toString() { +#if DOCTEST_CLANG == 0 && DOCTEST_GCC == 0 && DOCTEST_ICC == 0 + String ret = __FUNCSIG__; // class doctest::String __cdecl doctest::toString(void) + String::size_type beginPos = ret.find('<'); + return ret.substr(beginPos + 1, ret.size() - beginPos - static_cast(sizeof(">(void)"))); +#else + String ret = __PRETTY_FUNCTION__; // doctest::String toString() [with T = TYPE] + String::size_type begin = ret.find('=') + 2; + return ret.substr(begin, ret.size() - begin - 1); +#endif +} + +template ::value, bool>::type = true> +String toString(const DOCTEST_REF_WRAP(T) value) { + return StringMaker::convert(value); +} + +#ifdef DOCTEST_CONFIG_TREAT_CHAR_STAR_AS_STRING +DOCTEST_INTERFACE String toString(const char* in); +#endif // DOCTEST_CONFIG_TREAT_CHAR_STAR_AS_STRING + +#if DOCTEST_MSVC >= DOCTEST_COMPILER(19, 20, 0) +// see this issue on why this is needed: https://github.com/doctest/doctest/issues/183 +DOCTEST_INTERFACE String toString(const std::string& in); +#endif // VS 2019 + +DOCTEST_INTERFACE String toString(String in); + +DOCTEST_INTERFACE String toString(std::nullptr_t); + +DOCTEST_INTERFACE String toString(bool in); + +DOCTEST_INTERFACE String toString(float in); +DOCTEST_INTERFACE String toString(double in); +DOCTEST_INTERFACE String toString(double long in); + +DOCTEST_INTERFACE String toString(char in); +DOCTEST_INTERFACE String toString(char signed in); +DOCTEST_INTERFACE String toString(char unsigned in); +DOCTEST_INTERFACE String toString(short in); +DOCTEST_INTERFACE String toString(short unsigned in); +DOCTEST_INTERFACE String toString(signed in); +DOCTEST_INTERFACE String toString(unsigned in); +DOCTEST_INTERFACE String toString(long in); +DOCTEST_INTERFACE String toString(long unsigned in); +DOCTEST_INTERFACE String toString(long long in); +DOCTEST_INTERFACE String toString(long long unsigned in); + +template ::value, bool>::type = true> +String toString(const DOCTEST_REF_WRAP(T) value) { + using UT = typename detail::types::underlying_type::type; + return (DOCTEST_STRINGIFY(static_cast(value))); +} + +namespace detail { + template + struct filldata + { + static void fill(std::ostream* stream, const T& in) { +#if defined(_MSC_VER) && _MSC_VER <= 1900 + insert_hack_t::insert(*stream, in); +#else + operator<<(*stream, in); +#endif + } + }; + +DOCTEST_MSVC_SUPPRESS_WARNING_WITH_PUSH(4866) +// NOLINTBEGIN(*-avoid-c-arrays) + template + struct filldata { + static void fill(std::ostream* stream, const T(&in)[N]) { + *stream << "["; + for (size_t i = 0; i < N; i++) { + if (i != 0) { *stream << ", "; } + *stream << (DOCTEST_STRINGIFY(in[i])); + } + *stream << "]"; + } + }; +// NOLINTEND(*-avoid-c-arrays) +DOCTEST_MSVC_SUPPRESS_WARNING_POP + + // Specialized since we don't want the terminating null byte! +// NOLINTBEGIN(*-avoid-c-arrays) + template + struct filldata { + static void fill(std::ostream* stream, const char (&in)[N]) { + *stream << String(in, in[N - 1] ? N : N - 1); + } // NOLINT(clang-analyzer-cplusplus.NewDeleteLeaks) + }; +// NOLINTEND(*-avoid-c-arrays) + + template <> + struct filldata { + static void fill(std::ostream* stream, const void* in); + }; + + template + struct filldata { +DOCTEST_MSVC_SUPPRESS_WARNING_WITH_PUSH(4180) + static void fill(std::ostream* stream, const T* in) { +DOCTEST_MSVC_SUPPRESS_WARNING_POP +DOCTEST_CLANG_SUPPRESS_WARNING_WITH_PUSH("-Wmicrosoft-cast") + filldata::fill(stream, +#if DOCTEST_GCC == 0 || DOCTEST_GCC >= DOCTEST_COMPILER(4, 9, 0) + reinterpret_cast(in) +#else + *reinterpret_cast(&in) +#endif + ); +DOCTEST_CLANG_SUPPRESS_WARNING_POP + } + }; +} + +struct DOCTEST_INTERFACE Approx +{ + Approx(double value); + + Approx operator()(double value) const; + +#ifdef DOCTEST_CONFIG_INCLUDE_TYPE_TRAITS + template + explicit Approx(const T& value, + typename detail::types::enable_if::value>::type* = + static_cast(nullptr)) { + *this = static_cast(value); + } +#endif // DOCTEST_CONFIG_INCLUDE_TYPE_TRAITS + + Approx& epsilon(double newEpsilon); + +#ifdef DOCTEST_CONFIG_INCLUDE_TYPE_TRAITS + template + typename std::enable_if::value, Approx&>::type epsilon( + const T& newEpsilon) { + m_epsilon = static_cast(newEpsilon); + return *this; + } +#endif // DOCTEST_CONFIG_INCLUDE_TYPE_TRAITS + + Approx& scale(double newScale); + +#ifdef DOCTEST_CONFIG_INCLUDE_TYPE_TRAITS + template + typename std::enable_if::value, Approx&>::type scale( + const T& newScale) { + m_scale = static_cast(newScale); + return *this; + } +#endif // DOCTEST_CONFIG_INCLUDE_TYPE_TRAITS + + // clang-format off + DOCTEST_INTERFACE friend bool operator==(double lhs, const Approx & rhs); + DOCTEST_INTERFACE friend bool operator==(const Approx & lhs, double rhs); + DOCTEST_INTERFACE friend bool operator!=(double lhs, const Approx & rhs); + DOCTEST_INTERFACE friend bool operator!=(const Approx & lhs, double rhs); + DOCTEST_INTERFACE friend bool operator<=(double lhs, const Approx & rhs); + DOCTEST_INTERFACE friend bool operator<=(const Approx & lhs, double rhs); + DOCTEST_INTERFACE friend bool operator>=(double lhs, const Approx & rhs); + DOCTEST_INTERFACE friend bool operator>=(const Approx & lhs, double rhs); + DOCTEST_INTERFACE friend bool operator< (double lhs, const Approx & rhs); + DOCTEST_INTERFACE friend bool operator< (const Approx & lhs, double rhs); + DOCTEST_INTERFACE friend bool operator> (double lhs, const Approx & rhs); + DOCTEST_INTERFACE friend bool operator> (const Approx & lhs, double rhs); + +#ifdef DOCTEST_CONFIG_INCLUDE_TYPE_TRAITS +#define DOCTEST_APPROX_PREFIX \ + template friend typename std::enable_if::value, bool>::type + + DOCTEST_APPROX_PREFIX operator==(const T& lhs, const Approx& rhs) { return operator==(static_cast(lhs), rhs); } + DOCTEST_APPROX_PREFIX operator==(const Approx& lhs, const T& rhs) { return operator==(rhs, lhs); } + DOCTEST_APPROX_PREFIX operator!=(const T& lhs, const Approx& rhs) { return !operator==(lhs, rhs); } + DOCTEST_APPROX_PREFIX operator!=(const Approx& lhs, const T& rhs) { return !operator==(rhs, lhs); } + DOCTEST_APPROX_PREFIX operator<=(const T& lhs, const Approx& rhs) { return static_cast(lhs) < rhs.m_value || lhs == rhs; } + DOCTEST_APPROX_PREFIX operator<=(const Approx& lhs, const T& rhs) { return lhs.m_value < static_cast(rhs) || lhs == rhs; } + DOCTEST_APPROX_PREFIX operator>=(const T& lhs, const Approx& rhs) { return static_cast(lhs) > rhs.m_value || lhs == rhs; } + DOCTEST_APPROX_PREFIX operator>=(const Approx& lhs, const T& rhs) { return lhs.m_value > static_cast(rhs) || lhs == rhs; } + DOCTEST_APPROX_PREFIX operator< (const T& lhs, const Approx& rhs) { return static_cast(lhs) < rhs.m_value && lhs != rhs; } + DOCTEST_APPROX_PREFIX operator< (const Approx& lhs, const T& rhs) { return lhs.m_value < static_cast(rhs) && lhs != rhs; } + DOCTEST_APPROX_PREFIX operator> (const T& lhs, const Approx& rhs) { return static_cast(lhs) > rhs.m_value && lhs != rhs; } + DOCTEST_APPROX_PREFIX operator> (const Approx& lhs, const T& rhs) { return lhs.m_value > static_cast(rhs) && lhs != rhs; } +#undef DOCTEST_APPROX_PREFIX +#endif // DOCTEST_CONFIG_INCLUDE_TYPE_TRAITS + + // clang-format on + + double m_epsilon; + double m_scale; + double m_value; +}; + +DOCTEST_INTERFACE String toString(const Approx& in); + +DOCTEST_INTERFACE const ContextOptions* getContextOptions(); + +template +struct DOCTEST_INTERFACE_DECL IsNaN +{ + F value; bool flipped; + IsNaN(F f, bool flip = false) : value(f), flipped(flip) { } + IsNaN operator!() const { return { value, !flipped }; } + operator bool() const; +}; +#ifndef __MINGW32__ +extern template struct DOCTEST_INTERFACE_DECL IsNaN; +extern template struct DOCTEST_INTERFACE_DECL IsNaN; +extern template struct DOCTEST_INTERFACE_DECL IsNaN; +#endif +DOCTEST_INTERFACE String toString(IsNaN in); +DOCTEST_INTERFACE String toString(IsNaN in); +DOCTEST_INTERFACE String toString(IsNaN in); + +#ifndef DOCTEST_CONFIG_DISABLE + +namespace detail { + // clang-format off +#ifdef DOCTEST_CONFIG_TREAT_CHAR_STAR_AS_STRING + template struct decay_array { using type = T; }; + template struct decay_array { using type = T*; }; + template struct decay_array { using type = T*; }; + + template struct not_char_pointer { static DOCTEST_CONSTEXPR int value = 1; }; + template<> struct not_char_pointer { static DOCTEST_CONSTEXPR int value = 0; }; + template<> struct not_char_pointer { static DOCTEST_CONSTEXPR int value = 0; }; + + template struct can_use_op : public not_char_pointer::type> {}; +#endif // DOCTEST_CONFIG_TREAT_CHAR_STAR_AS_STRING + // clang-format on + + struct DOCTEST_INTERFACE TestFailureException + { + }; + + DOCTEST_INTERFACE bool checkIfShouldThrow(assertType::Enum at); + +#ifndef DOCTEST_CONFIG_NO_EXCEPTIONS + DOCTEST_NORETURN +#endif // DOCTEST_CONFIG_NO_EXCEPTIONS + DOCTEST_INTERFACE void throwException(); + + struct DOCTEST_INTERFACE Subcase + { + SubcaseSignature m_signature; + bool m_entered = false; + + Subcase(const String& name, const char* file, int line); + Subcase(const Subcase&) = delete; + Subcase(Subcase&&) = delete; + Subcase& operator=(const Subcase&) = delete; + Subcase& operator=(Subcase&&) = delete; + ~Subcase(); + + operator bool() const; + + private: + bool checkFilters(); + }; + + template + String stringifyBinaryExpr(const DOCTEST_REF_WRAP(L) lhs, const char* op, + const DOCTEST_REF_WRAP(R) rhs) { + return (DOCTEST_STRINGIFY(lhs)) + op + (DOCTEST_STRINGIFY(rhs)); + } + +#if DOCTEST_CLANG && DOCTEST_CLANG < DOCTEST_COMPILER(3, 6, 0) +DOCTEST_CLANG_SUPPRESS_WARNING_WITH_PUSH("-Wunused-comparison") +#endif + +// This will check if there is any way it could find a operator like member or friend and uses it. +// If not it doesn't find the operator or if the operator at global scope is defined after +// this template, the template won't be instantiated due to SFINAE. Once the template is not +// instantiated it can look for global operator using normal conversions. +#ifdef __NVCC__ +#define SFINAE_OP(ret,op) ret +#else +#define SFINAE_OP(ret,op) decltype((void)(doctest::detail::declval() op doctest::detail::declval()),ret{}) +#endif + +#define DOCTEST_DO_BINARY_EXPRESSION_COMPARISON(op, op_str, op_macro) \ + template \ + DOCTEST_NOINLINE SFINAE_OP(Result,op) operator op(R&& rhs) { \ + bool res = op_macro(doctest::detail::forward(lhs), doctest::detail::forward(rhs)); \ + if(m_at & assertType::is_false) \ + res = !res; \ + if(!res || doctest::getContextOptions()->success) \ + return Result(res, stringifyBinaryExpr(lhs, op_str, rhs)); \ + return Result(res); \ + } + + // more checks could be added - like in Catch: + // https://github.com/catchorg/Catch2/pull/1480/files + // https://github.com/catchorg/Catch2/pull/1481/files +#define DOCTEST_FORBIT_EXPRESSION(rt, op) \ + template \ + rt& operator op(const R&) { \ + static_assert(deferred_false::value, \ + "Expression Too Complex Please Rewrite As Binary Comparison!"); \ + return *this; \ + } + + struct DOCTEST_INTERFACE Result // NOLINT(*-member-init) + { + bool m_passed; + String m_decomp; + + Result() = default; // TODO: Why do we need this? (To remove NOLINT) + Result(bool passed, const String& decomposition = String()); + + // forbidding some expressions based on this table: https://en.cppreference.com/w/cpp/language/operator_precedence + DOCTEST_FORBIT_EXPRESSION(Result, &) + DOCTEST_FORBIT_EXPRESSION(Result, ^) + DOCTEST_FORBIT_EXPRESSION(Result, |) + DOCTEST_FORBIT_EXPRESSION(Result, &&) + DOCTEST_FORBIT_EXPRESSION(Result, ||) + DOCTEST_FORBIT_EXPRESSION(Result, ==) + DOCTEST_FORBIT_EXPRESSION(Result, !=) + DOCTEST_FORBIT_EXPRESSION(Result, <) + DOCTEST_FORBIT_EXPRESSION(Result, >) + DOCTEST_FORBIT_EXPRESSION(Result, <=) + DOCTEST_FORBIT_EXPRESSION(Result, >=) + DOCTEST_FORBIT_EXPRESSION(Result, =) + DOCTEST_FORBIT_EXPRESSION(Result, +=) + DOCTEST_FORBIT_EXPRESSION(Result, -=) + DOCTEST_FORBIT_EXPRESSION(Result, *=) + DOCTEST_FORBIT_EXPRESSION(Result, /=) + DOCTEST_FORBIT_EXPRESSION(Result, %=) + DOCTEST_FORBIT_EXPRESSION(Result, <<=) + DOCTEST_FORBIT_EXPRESSION(Result, >>=) + DOCTEST_FORBIT_EXPRESSION(Result, &=) + DOCTEST_FORBIT_EXPRESSION(Result, ^=) + DOCTEST_FORBIT_EXPRESSION(Result, |=) + }; + +#ifndef DOCTEST_CONFIG_NO_COMPARISON_WARNING_SUPPRESSION + + DOCTEST_CLANG_SUPPRESS_WARNING_PUSH + DOCTEST_CLANG_SUPPRESS_WARNING("-Wsign-conversion") + DOCTEST_CLANG_SUPPRESS_WARNING("-Wsign-compare") + //DOCTEST_CLANG_SUPPRESS_WARNING("-Wdouble-promotion") + //DOCTEST_CLANG_SUPPRESS_WARNING("-Wconversion") + //DOCTEST_CLANG_SUPPRESS_WARNING("-Wfloat-equal") + + DOCTEST_GCC_SUPPRESS_WARNING_PUSH + DOCTEST_GCC_SUPPRESS_WARNING("-Wsign-conversion") + DOCTEST_GCC_SUPPRESS_WARNING("-Wsign-compare") + //DOCTEST_GCC_SUPPRESS_WARNING("-Wdouble-promotion") + //DOCTEST_GCC_SUPPRESS_WARNING("-Wconversion") + //DOCTEST_GCC_SUPPRESS_WARNING("-Wfloat-equal") + + DOCTEST_MSVC_SUPPRESS_WARNING_PUSH + // https://stackoverflow.com/questions/39479163 what's the difference between 4018 and 4389 + DOCTEST_MSVC_SUPPRESS_WARNING(4388) // signed/unsigned mismatch + DOCTEST_MSVC_SUPPRESS_WARNING(4389) // 'operator' : signed/unsigned mismatch + DOCTEST_MSVC_SUPPRESS_WARNING(4018) // 'expression' : signed/unsigned mismatch + //DOCTEST_MSVC_SUPPRESS_WARNING(4805) // 'operation' : unsafe mix of type 'type' and type 'type' in operation + +#endif // DOCTEST_CONFIG_NO_COMPARISON_WARNING_SUPPRESSION + + // clang-format off +#ifndef DOCTEST_CONFIG_TREAT_CHAR_STAR_AS_STRING +#define DOCTEST_COMPARISON_RETURN_TYPE bool +#else // DOCTEST_CONFIG_TREAT_CHAR_STAR_AS_STRING +#define DOCTEST_COMPARISON_RETURN_TYPE typename types::enable_if::value || can_use_op::value, bool>::type + inline bool eq(const char* lhs, const char* rhs) { return String(lhs) == String(rhs); } + inline bool ne(const char* lhs, const char* rhs) { return String(lhs) != String(rhs); } + inline bool lt(const char* lhs, const char* rhs) { return String(lhs) < String(rhs); } + inline bool gt(const char* lhs, const char* rhs) { return String(lhs) > String(rhs); } + inline bool le(const char* lhs, const char* rhs) { return String(lhs) <= String(rhs); } + inline bool ge(const char* lhs, const char* rhs) { return String(lhs) >= String(rhs); } +#endif // DOCTEST_CONFIG_TREAT_CHAR_STAR_AS_STRING + // clang-format on + +#define DOCTEST_RELATIONAL_OP(name, op) \ + template \ + DOCTEST_COMPARISON_RETURN_TYPE name(const DOCTEST_REF_WRAP(L) lhs, \ + const DOCTEST_REF_WRAP(R) rhs) { \ + return lhs op rhs; \ + } + + DOCTEST_RELATIONAL_OP(eq, ==) + DOCTEST_RELATIONAL_OP(ne, !=) + DOCTEST_RELATIONAL_OP(lt, <) + DOCTEST_RELATIONAL_OP(gt, >) + DOCTEST_RELATIONAL_OP(le, <=) + DOCTEST_RELATIONAL_OP(ge, >=) + +#ifndef DOCTEST_CONFIG_TREAT_CHAR_STAR_AS_STRING +#define DOCTEST_CMP_EQ(l, r) l == r +#define DOCTEST_CMP_NE(l, r) l != r +#define DOCTEST_CMP_GT(l, r) l > r +#define DOCTEST_CMP_LT(l, r) l < r +#define DOCTEST_CMP_GE(l, r) l >= r +#define DOCTEST_CMP_LE(l, r) l <= r +#else // DOCTEST_CONFIG_TREAT_CHAR_STAR_AS_STRING +#define DOCTEST_CMP_EQ(l, r) eq(l, r) +#define DOCTEST_CMP_NE(l, r) ne(l, r) +#define DOCTEST_CMP_GT(l, r) gt(l, r) +#define DOCTEST_CMP_LT(l, r) lt(l, r) +#define DOCTEST_CMP_GE(l, r) ge(l, r) +#define DOCTEST_CMP_LE(l, r) le(l, r) +#endif // DOCTEST_CONFIG_TREAT_CHAR_STAR_AS_STRING + + template + // cppcheck-suppress copyCtorAndEqOperator + struct Expression_lhs + { + L lhs; + assertType::Enum m_at; + + explicit Expression_lhs(L&& in, assertType::Enum at) + : lhs(static_cast(in)) + , m_at(at) {} + + DOCTEST_NOINLINE operator Result() { +// this is needed only for MSVC 2015 +DOCTEST_MSVC_SUPPRESS_WARNING_WITH_PUSH(4800) // 'int': forcing value to bool + bool res = static_cast(lhs); +DOCTEST_MSVC_SUPPRESS_WARNING_POP + if(m_at & assertType::is_false) { //!OCLINT bitwise operator in conditional + res = !res; + } + + if(!res || getContextOptions()->success) { + return { res, (DOCTEST_STRINGIFY(lhs)) }; + } + return { res }; + } + + /* This is required for user-defined conversions from Expression_lhs to L */ + operator L() const { return lhs; } + + // clang-format off + DOCTEST_DO_BINARY_EXPRESSION_COMPARISON(==, " == ", DOCTEST_CMP_EQ) //!OCLINT bitwise operator in conditional + DOCTEST_DO_BINARY_EXPRESSION_COMPARISON(!=, " != ", DOCTEST_CMP_NE) //!OCLINT bitwise operator in conditional + DOCTEST_DO_BINARY_EXPRESSION_COMPARISON(>, " > ", DOCTEST_CMP_GT) //!OCLINT bitwise operator in conditional + DOCTEST_DO_BINARY_EXPRESSION_COMPARISON(<, " < ", DOCTEST_CMP_LT) //!OCLINT bitwise operator in conditional + DOCTEST_DO_BINARY_EXPRESSION_COMPARISON(>=, " >= ", DOCTEST_CMP_GE) //!OCLINT bitwise operator in conditional + DOCTEST_DO_BINARY_EXPRESSION_COMPARISON(<=, " <= ", DOCTEST_CMP_LE) //!OCLINT bitwise operator in conditional + // clang-format on + + // forbidding some expressions based on this table: https://en.cppreference.com/w/cpp/language/operator_precedence + DOCTEST_FORBIT_EXPRESSION(Expression_lhs, &) + DOCTEST_FORBIT_EXPRESSION(Expression_lhs, ^) + DOCTEST_FORBIT_EXPRESSION(Expression_lhs, |) + DOCTEST_FORBIT_EXPRESSION(Expression_lhs, &&) + DOCTEST_FORBIT_EXPRESSION(Expression_lhs, ||) + DOCTEST_FORBIT_EXPRESSION(Expression_lhs, =) + DOCTEST_FORBIT_EXPRESSION(Expression_lhs, +=) + DOCTEST_FORBIT_EXPRESSION(Expression_lhs, -=) + DOCTEST_FORBIT_EXPRESSION(Expression_lhs, *=) + DOCTEST_FORBIT_EXPRESSION(Expression_lhs, /=) + DOCTEST_FORBIT_EXPRESSION(Expression_lhs, %=) + DOCTEST_FORBIT_EXPRESSION(Expression_lhs, <<=) + DOCTEST_FORBIT_EXPRESSION(Expression_lhs, >>=) + DOCTEST_FORBIT_EXPRESSION(Expression_lhs, &=) + DOCTEST_FORBIT_EXPRESSION(Expression_lhs, ^=) + DOCTEST_FORBIT_EXPRESSION(Expression_lhs, |=) + // these 2 are unfortunate because they should be allowed - they have higher precedence over the comparisons, but the + // ExpressionDecomposer class uses the left shift operator to capture the left operand of the binary expression... + DOCTEST_FORBIT_EXPRESSION(Expression_lhs, <<) + DOCTEST_FORBIT_EXPRESSION(Expression_lhs, >>) + }; + +#ifndef DOCTEST_CONFIG_NO_COMPARISON_WARNING_SUPPRESSION + + DOCTEST_CLANG_SUPPRESS_WARNING_POP + DOCTEST_MSVC_SUPPRESS_WARNING_POP + DOCTEST_GCC_SUPPRESS_WARNING_POP + +#endif // DOCTEST_CONFIG_NO_COMPARISON_WARNING_SUPPRESSION + +#if DOCTEST_CLANG && DOCTEST_CLANG < DOCTEST_COMPILER(3, 6, 0) +DOCTEST_CLANG_SUPPRESS_WARNING_POP +#endif + + struct DOCTEST_INTERFACE ExpressionDecomposer + { + assertType::Enum m_at; + + ExpressionDecomposer(assertType::Enum at); + + // The right operator for capturing expressions is "<=" instead of "<<" (based on the operator precedence table) + // but then there will be warnings from GCC about "-Wparentheses" and since "_Pragma()" is problematic this will stay for now... + // https://github.com/catchorg/Catch2/issues/870 + // https://github.com/catchorg/Catch2/issues/565 + template + Expression_lhs operator<<(L&& operand) { + return Expression_lhs(static_cast(operand), m_at); + } + + template ::value,void >::type* = nullptr> + Expression_lhs operator<<(const L &operand) { + return Expression_lhs(operand, m_at); + } + }; + + struct DOCTEST_INTERFACE TestSuite + { + const char* m_test_suite = nullptr; + const char* m_description = nullptr; + bool m_skip = false; + bool m_no_breaks = false; + bool m_no_output = false; + bool m_may_fail = false; + bool m_should_fail = false; + int m_expected_failures = 0; + double m_timeout = 0; + + TestSuite& operator*(const char* in); + + template + TestSuite& operator*(const T& in) { + in.fill(*this); + return *this; + } + }; + + using funcType = void (*)(); + + struct DOCTEST_INTERFACE TestCase : public TestCaseData + { + funcType m_test; // a function pointer to the test case + + String m_type; // for templated test cases - gets appended to the real name + int m_template_id; // an ID used to distinguish between the different versions of a templated test case + String m_full_name; // contains the name (only for templated test cases!) + the template type + + TestCase(funcType test, const char* file, unsigned line, const TestSuite& test_suite, + const String& type = String(), int template_id = -1); + + TestCase(const TestCase& other); + TestCase(TestCase&&) = delete; + + DOCTEST_MSVC_SUPPRESS_WARNING_WITH_PUSH(26434) // hides a non-virtual function + TestCase& operator=(const TestCase& other); + DOCTEST_MSVC_SUPPRESS_WARNING_POP + + TestCase& operator=(TestCase&&) = delete; + + TestCase& operator*(const char* in); + + template + TestCase& operator*(const T& in) { + in.fill(*this); + return *this; + } + + bool operator<(const TestCase& other) const; + + ~TestCase() = default; + }; + + // forward declarations of functions used by the macros + DOCTEST_INTERFACE int regTest(const TestCase& tc); + DOCTEST_INTERFACE int setTestSuite(const TestSuite& ts); + DOCTEST_INTERFACE bool isDebuggerActive(); + + template + int instantiationHelper(const T&) { return 0; } + + namespace binaryAssertComparison { + enum Enum + { + eq = 0, + ne, + gt, + lt, + ge, + le + }; + } // namespace binaryAssertComparison + + // clang-format off + template struct RelationalComparator { bool operator()(const DOCTEST_REF_WRAP(L), const DOCTEST_REF_WRAP(R) ) const { return false; } }; + +#define DOCTEST_BINARY_RELATIONAL_OP(n, op) \ + template struct RelationalComparator { bool operator()(const DOCTEST_REF_WRAP(L) lhs, const DOCTEST_REF_WRAP(R) rhs) const { return op(lhs, rhs); } }; + // clang-format on + + DOCTEST_BINARY_RELATIONAL_OP(0, doctest::detail::eq) + DOCTEST_BINARY_RELATIONAL_OP(1, doctest::detail::ne) + DOCTEST_BINARY_RELATIONAL_OP(2, doctest::detail::gt) + DOCTEST_BINARY_RELATIONAL_OP(3, doctest::detail::lt) + DOCTEST_BINARY_RELATIONAL_OP(4, doctest::detail::ge) + DOCTEST_BINARY_RELATIONAL_OP(5, doctest::detail::le) + + struct DOCTEST_INTERFACE ResultBuilder : public AssertData + { + ResultBuilder(assertType::Enum at, const char* file, int line, const char* expr, + const char* exception_type = "", const String& exception_string = ""); + + ResultBuilder(assertType::Enum at, const char* file, int line, const char* expr, + const char* exception_type, const Contains& exception_string); + + void setResult(const Result& res); + + template + DOCTEST_NOINLINE bool binary_assert(const DOCTEST_REF_WRAP(L) lhs, + const DOCTEST_REF_WRAP(R) rhs) { + m_failed = !RelationalComparator()(lhs, rhs); + if (m_failed || getContextOptions()->success) { + m_decomp = stringifyBinaryExpr(lhs, ", ", rhs); + } + return !m_failed; + } + + template + DOCTEST_NOINLINE bool unary_assert(const DOCTEST_REF_WRAP(L) val) { + m_failed = !val; + + if (m_at & assertType::is_false) { //!OCLINT bitwise operator in conditional + m_failed = !m_failed; + } + + if (m_failed || getContextOptions()->success) { + m_decomp = (DOCTEST_STRINGIFY(val)); + } + + return !m_failed; + } + + void translateException(); + + bool log(); + void react() const; + }; + + namespace assertAction { + enum Enum + { + nothing = 0, + dbgbreak = 1, + shouldthrow = 2 + }; + } // namespace assertAction + + DOCTEST_INTERFACE void failed_out_of_a_testing_context(const AssertData& ad); + + DOCTEST_INTERFACE bool decomp_assert(assertType::Enum at, const char* file, int line, + const char* expr, const Result& result); + +#define DOCTEST_ASSERT_OUT_OF_TESTS(decomp) \ + do { \ + if(!is_running_in_test) { \ + if(failed) { \ + ResultBuilder rb(at, file, line, expr); \ + rb.m_failed = failed; \ + rb.m_decomp = decomp; \ + failed_out_of_a_testing_context(rb); \ + if(isDebuggerActive() && !getContextOptions()->no_breaks) \ + DOCTEST_BREAK_INTO_DEBUGGER(); \ + if(checkIfShouldThrow(at)) \ + throwException(); \ + } \ + return !failed; \ + } \ + } while(false) + +#define DOCTEST_ASSERT_IN_TESTS(decomp) \ + ResultBuilder rb(at, file, line, expr); \ + rb.m_failed = failed; \ + if(rb.m_failed || getContextOptions()->success) \ + rb.m_decomp = decomp; \ + if(rb.log()) \ + DOCTEST_BREAK_INTO_DEBUGGER(); \ + if(rb.m_failed && checkIfShouldThrow(at)) \ + throwException() + + template + DOCTEST_NOINLINE bool binary_assert(assertType::Enum at, const char* file, int line, + const char* expr, const DOCTEST_REF_WRAP(L) lhs, + const DOCTEST_REF_WRAP(R) rhs) { + bool failed = !RelationalComparator()(lhs, rhs); + + // ################################################################################### + // IF THE DEBUGGER BREAKS HERE - GO 1 LEVEL UP IN THE CALLSTACK FOR THE FAILING ASSERT + // THIS IS THE EFFECT OF HAVING 'DOCTEST_CONFIG_SUPER_FAST_ASSERTS' DEFINED + // ################################################################################### + DOCTEST_ASSERT_OUT_OF_TESTS(stringifyBinaryExpr(lhs, ", ", rhs)); + DOCTEST_ASSERT_IN_TESTS(stringifyBinaryExpr(lhs, ", ", rhs)); + return !failed; + } + + template + DOCTEST_NOINLINE bool unary_assert(assertType::Enum at, const char* file, int line, + const char* expr, const DOCTEST_REF_WRAP(L) val) { + bool failed = !val; + + if(at & assertType::is_false) //!OCLINT bitwise operator in conditional + failed = !failed; + + // ################################################################################### + // IF THE DEBUGGER BREAKS HERE - GO 1 LEVEL UP IN THE CALLSTACK FOR THE FAILING ASSERT + // THIS IS THE EFFECT OF HAVING 'DOCTEST_CONFIG_SUPER_FAST_ASSERTS' DEFINED + // ################################################################################### + DOCTEST_ASSERT_OUT_OF_TESTS((DOCTEST_STRINGIFY(val))); + DOCTEST_ASSERT_IN_TESTS((DOCTEST_STRINGIFY(val))); + return !failed; + } + + struct DOCTEST_INTERFACE IExceptionTranslator + { + DOCTEST_DECLARE_INTERFACE(IExceptionTranslator) + virtual bool translate(String&) const = 0; + }; + + template + class ExceptionTranslator : public IExceptionTranslator //!OCLINT destructor of virtual class + { + public: + explicit ExceptionTranslator(String (*translateFunction)(T)) + : m_translateFunction(translateFunction) {} + + bool translate(String& res) const override { +#ifndef DOCTEST_CONFIG_NO_EXCEPTIONS + try { + throw; // lgtm [cpp/rethrow-no-exception] + // cppcheck-suppress catchExceptionByValue + } catch(const T& ex) { + res = m_translateFunction(ex); //!OCLINT parameter reassignment + return true; + } catch(...) {} //!OCLINT - empty catch statement +#endif // DOCTEST_CONFIG_NO_EXCEPTIONS + static_cast(res); // to silence -Wunused-parameter + return false; + } + + private: + String (*m_translateFunction)(T); + }; + + DOCTEST_INTERFACE void registerExceptionTranslatorImpl(const IExceptionTranslator* et); + + // ContextScope base class used to allow implementing methods of ContextScope + // that don't depend on the template parameter in doctest.cpp. + struct DOCTEST_INTERFACE ContextScopeBase : public IContextScope { + ContextScopeBase(const ContextScopeBase&) = delete; + + ContextScopeBase& operator=(const ContextScopeBase&) = delete; + ContextScopeBase& operator=(ContextScopeBase&&) = delete; + + ~ContextScopeBase() override = default; + + protected: + ContextScopeBase(); + ContextScopeBase(ContextScopeBase&& other) noexcept; + + void destroy(); + bool need_to_destroy{true}; + }; + + template class ContextScope : public ContextScopeBase + { + L lambda_; + + public: + explicit ContextScope(const L &lambda) : lambda_(lambda) {} + explicit ContextScope(L&& lambda) : lambda_(static_cast(lambda)) { } + + ContextScope(const ContextScope&) = delete; + ContextScope(ContextScope&&) noexcept = default; + + ContextScope& operator=(const ContextScope&) = delete; + ContextScope& operator=(ContextScope&&) = delete; + + void stringify(std::ostream* s) const override { lambda_(s); } + + ~ContextScope() override { + if (need_to_destroy) { + destroy(); + } + } + }; + + struct DOCTEST_INTERFACE MessageBuilder : public MessageData + { + std::ostream* m_stream; + bool logged = false; + + MessageBuilder(const char* file, int line, assertType::Enum severity); + + MessageBuilder(const MessageBuilder&) = delete; + MessageBuilder(MessageBuilder&&) = delete; + + MessageBuilder& operator=(const MessageBuilder&) = delete; + MessageBuilder& operator=(MessageBuilder&&) = delete; + + ~MessageBuilder(); + + // the preferred way of chaining parameters for stringification +DOCTEST_MSVC_SUPPRESS_WARNING_WITH_PUSH(4866) + template + MessageBuilder& operator,(const T& in) { + *m_stream << (DOCTEST_STRINGIFY(in)); + return *this; + } +DOCTEST_MSVC_SUPPRESS_WARNING_POP + + // kept here just for backwards-compatibility - the comma operator should be preferred now + template + MessageBuilder& operator<<(const T& in) { return this->operator,(in); } + + // the `,` operator has the lowest operator precedence - if `<<` is used by the user then + // the `,` operator will be called last which is not what we want and thus the `*` operator + // is used first (has higher operator precedence compared to `<<`) so that we guarantee that + // an operator of the MessageBuilder class is called first before the rest of the parameters + template + MessageBuilder& operator*(const T& in) { return this->operator,(in); } + + bool log(); + void react(); + }; + + template + ContextScope MakeContextScope(const L &lambda) { + return ContextScope(lambda); + } +} // namespace detail + +#define DOCTEST_DEFINE_DECORATOR(name, type, def) \ + struct name \ + { \ + type data; \ + name(type in = def) \ + : data(in) {} \ + void fill(detail::TestCase& state) const { state.DOCTEST_CAT(m_, name) = data; } \ + void fill(detail::TestSuite& state) const { state.DOCTEST_CAT(m_, name) = data; } \ + } + +DOCTEST_DEFINE_DECORATOR(test_suite, const char*, ""); +DOCTEST_DEFINE_DECORATOR(description, const char*, ""); +DOCTEST_DEFINE_DECORATOR(skip, bool, true); +DOCTEST_DEFINE_DECORATOR(no_breaks, bool, true); +DOCTEST_DEFINE_DECORATOR(no_output, bool, true); +DOCTEST_DEFINE_DECORATOR(timeout, double, 0); +DOCTEST_DEFINE_DECORATOR(may_fail, bool, true); +DOCTEST_DEFINE_DECORATOR(should_fail, bool, true); +DOCTEST_DEFINE_DECORATOR(expected_failures, int, 0); + +template +int registerExceptionTranslator(String (*translateFunction)(T)) { + DOCTEST_CLANG_SUPPRESS_WARNING_WITH_PUSH("-Wexit-time-destructors") + static detail::ExceptionTranslator exceptionTranslator(translateFunction); + DOCTEST_CLANG_SUPPRESS_WARNING_POP + detail::registerExceptionTranslatorImpl(&exceptionTranslator); + return 0; +} + +} // namespace doctest + +// in a separate namespace outside of doctest because the DOCTEST_TEST_SUITE macro +// introduces an anonymous namespace in which getCurrentTestSuite gets overridden +namespace doctest_detail_test_suite_ns { +DOCTEST_INTERFACE doctest::detail::TestSuite& getCurrentTestSuite(); +} // namespace doctest_detail_test_suite_ns + +namespace doctest { +#else // DOCTEST_CONFIG_DISABLE +template +int registerExceptionTranslator(String (*)(T)) { + return 0; +} +#endif // DOCTEST_CONFIG_DISABLE + +namespace detail { + using assert_handler = void (*)(const AssertData&); + struct ContextState; +} // namespace detail + +class DOCTEST_INTERFACE Context +{ + detail::ContextState* p; + + void parseArgs(int argc, const char* const* argv, bool withDefaults = false); + +public: + explicit Context(int argc = 0, const char* const* argv = nullptr); + + Context(const Context&) = delete; + Context(Context&&) = delete; + + Context& operator=(const Context&) = delete; + Context& operator=(Context&&) = delete; + + ~Context(); // NOLINT(performance-trivially-destructible) + + void applyCommandLine(int argc, const char* const* argv); + + void addFilter(const char* filter, const char* value); + void clearFilters(); + void setOption(const char* option, bool value); + void setOption(const char* option, int value); + void setOption(const char* option, const char* value); + + bool shouldExit(); + + void setAsDefaultForAssertsOutOfTestCases(); + + void setAssertHandler(detail::assert_handler ah); + + void setCout(std::ostream* out); + + int run(); +}; + +namespace TestCaseFailureReason { + enum Enum + { + None = 0, + AssertFailure = 1, // an assertion has failed in the test case + Exception = 2, // test case threw an exception + Crash = 4, // a crash... + TooManyFailedAsserts = 8, // the abort-after option + Timeout = 16, // see the timeout decorator + ShouldHaveFailedButDidnt = 32, // see the should_fail decorator + ShouldHaveFailedAndDid = 64, // see the should_fail decorator + DidntFailExactlyNumTimes = 128, // see the expected_failures decorator + FailedExactlyNumTimes = 256, // see the expected_failures decorator + CouldHaveFailedAndDid = 512 // see the may_fail decorator + }; +} // namespace TestCaseFailureReason + +struct DOCTEST_INTERFACE CurrentTestCaseStats +{ + int numAssertsCurrentTest; + int numAssertsFailedCurrentTest; + double seconds; + int failure_flags; // use TestCaseFailureReason::Enum + bool testCaseSuccess; +}; + +struct DOCTEST_INTERFACE TestCaseException +{ + String error_string; + bool is_crash; +}; + +struct DOCTEST_INTERFACE TestRunStats +{ + unsigned numTestCases; + unsigned numTestCasesPassingFilters; + unsigned numTestSuitesPassingFilters; + unsigned numTestCasesFailed; + int numAsserts; + int numAssertsFailed; +}; + +struct QueryData +{ + const TestRunStats* run_stats = nullptr; + const TestCaseData** data = nullptr; + unsigned num_data = 0; +}; + +struct DOCTEST_INTERFACE IReporter +{ + // The constructor has to accept "const ContextOptions&" as a single argument + // which has most of the options for the run + a pointer to the stdout stream + // Reporter(const ContextOptions& in) + + // called when a query should be reported (listing test cases, printing the version, etc.) + virtual void report_query(const QueryData&) = 0; + + // called when the whole test run starts + virtual void test_run_start() = 0; + // called when the whole test run ends (caching a pointer to the input doesn't make sense here) + virtual void test_run_end(const TestRunStats&) = 0; + + // called when a test case is started (safe to cache a pointer to the input) + virtual void test_case_start(const TestCaseData&) = 0; + // called when a test case is reentered because of unfinished subcases (safe to cache a pointer to the input) + virtual void test_case_reenter(const TestCaseData&) = 0; + // called when a test case has ended + virtual void test_case_end(const CurrentTestCaseStats&) = 0; + + // called when an exception is thrown from the test case (or it crashes) + virtual void test_case_exception(const TestCaseException&) = 0; + + // called whenever a subcase is entered (don't cache pointers to the input) + virtual void subcase_start(const SubcaseSignature&) = 0; + // called whenever a subcase is exited (don't cache pointers to the input) + virtual void subcase_end() = 0; + + // called for each assert (don't cache pointers to the input) + virtual void log_assert(const AssertData&) = 0; + // called for each message (don't cache pointers to the input) + virtual void log_message(const MessageData&) = 0; + + // called when a test case is skipped either because it doesn't pass the filters, has a skip decorator + // or isn't in the execution range (between first and last) (safe to cache a pointer to the input) + virtual void test_case_skipped(const TestCaseData&) = 0; + + DOCTEST_DECLARE_INTERFACE(IReporter) + + // can obtain all currently active contexts and stringify them if one wishes to do so + static int get_num_active_contexts(); + static const IContextScope* const* get_active_contexts(); + + // can iterate through contexts which have been stringified automatically in their destructors when an exception has been thrown + static int get_num_stringified_contexts(); + static const String* get_stringified_contexts(); +}; + +namespace detail { + using reporterCreatorFunc = IReporter* (*)(const ContextOptions&); + + DOCTEST_INTERFACE void registerReporterImpl(const char* name, int prio, reporterCreatorFunc c, bool isReporter); + + template + IReporter* reporterCreator(const ContextOptions& o) { + return new Reporter(o); + } +} // namespace detail + +template +int registerReporter(const char* name, int priority, bool isReporter) { + detail::registerReporterImpl(name, priority, detail::reporterCreator, isReporter); + return 0; +} +} // namespace doctest + +#ifdef DOCTEST_CONFIG_ASSERTS_RETURN_VALUES +#define DOCTEST_FUNC_EMPTY [] { return false; }() +#else +#define DOCTEST_FUNC_EMPTY (void)0 +#endif + +// if registering is not disabled +#ifndef DOCTEST_CONFIG_DISABLE + +#ifdef DOCTEST_CONFIG_ASSERTS_RETURN_VALUES +#define DOCTEST_FUNC_SCOPE_BEGIN [&] +#define DOCTEST_FUNC_SCOPE_END () +#define DOCTEST_FUNC_SCOPE_RET(v) return v +#else +#define DOCTEST_FUNC_SCOPE_BEGIN do +#define DOCTEST_FUNC_SCOPE_END while(false) +#define DOCTEST_FUNC_SCOPE_RET(v) (void)0 +#endif + +// common code in asserts - for convenience +#define DOCTEST_ASSERT_LOG_REACT_RETURN(b) \ + if(b.log()) DOCTEST_BREAK_INTO_DEBUGGER(); \ + b.react(); \ + DOCTEST_FUNC_SCOPE_RET(!b.m_failed) + +#ifdef DOCTEST_CONFIG_NO_TRY_CATCH_IN_ASSERTS +#define DOCTEST_WRAP_IN_TRY(x) x; +#else // DOCTEST_CONFIG_NO_TRY_CATCH_IN_ASSERTS +#define DOCTEST_WRAP_IN_TRY(x) \ + try { \ + x; \ + } catch(...) { DOCTEST_RB.translateException(); } +#endif // DOCTEST_CONFIG_NO_TRY_CATCH_IN_ASSERTS + +#ifdef DOCTEST_CONFIG_VOID_CAST_EXPRESSIONS +#define DOCTEST_CAST_TO_VOID(...) \ + DOCTEST_GCC_SUPPRESS_WARNING_WITH_PUSH("-Wuseless-cast") \ + static_cast(__VA_ARGS__); \ + DOCTEST_GCC_SUPPRESS_WARNING_POP +#else // DOCTEST_CONFIG_VOID_CAST_EXPRESSIONS +#define DOCTEST_CAST_TO_VOID(...) __VA_ARGS__; +#endif // DOCTEST_CONFIG_VOID_CAST_EXPRESSIONS + +// registers the test by initializing a dummy var with a function +#define DOCTEST_REGISTER_FUNCTION(global_prefix, f, decorators) \ + global_prefix DOCTEST_GLOBAL_NO_WARNINGS(DOCTEST_ANONYMOUS(DOCTEST_ANON_VAR_), /* NOLINT */ \ + doctest::detail::regTest( \ + doctest::detail::TestCase( \ + f, __FILE__, __LINE__, \ + doctest_detail_test_suite_ns::getCurrentTestSuite()) * \ + decorators)) + +#define DOCTEST_IMPLEMENT_FIXTURE(der, base, func, decorators) \ + namespace { /* NOLINT */ \ + struct der : public base \ + { \ + void f(); \ + }; \ + static DOCTEST_INLINE_NOINLINE void func() { \ + der v; \ + v.f(); \ + } \ + DOCTEST_REGISTER_FUNCTION(DOCTEST_EMPTY, func, decorators) \ + } \ + DOCTEST_INLINE_NOINLINE void der::f() // NOLINT(misc-definitions-in-headers) + +#define DOCTEST_CREATE_AND_REGISTER_FUNCTION(f, decorators) \ + static void f(); \ + DOCTEST_REGISTER_FUNCTION(DOCTEST_EMPTY, f, decorators) \ + static void f() + +#define DOCTEST_CREATE_AND_REGISTER_FUNCTION_IN_CLASS(f, proxy, decorators) \ + static doctest::detail::funcType proxy() { return f; } \ + DOCTEST_REGISTER_FUNCTION(inline, proxy(), decorators) \ + static void f() + +// for registering tests +#define DOCTEST_TEST_CASE(decorators) \ + DOCTEST_CREATE_AND_REGISTER_FUNCTION(DOCTEST_ANONYMOUS(DOCTEST_ANON_FUNC_), decorators) + +// for registering tests in classes - requires C++17 for inline variables! +#if DOCTEST_CPLUSPLUS >= 201703L +#define DOCTEST_TEST_CASE_CLASS(decorators) \ + DOCTEST_CREATE_AND_REGISTER_FUNCTION_IN_CLASS(DOCTEST_ANONYMOUS(DOCTEST_ANON_FUNC_), \ + DOCTEST_ANONYMOUS(DOCTEST_ANON_PROXY_), \ + decorators) +#else // DOCTEST_TEST_CASE_CLASS +#define DOCTEST_TEST_CASE_CLASS(...) \ + TEST_CASES_CAN_BE_REGISTERED_IN_CLASSES_ONLY_IN_CPP17_MODE_OR_WITH_VS_2017_OR_NEWER +#endif // DOCTEST_TEST_CASE_CLASS + +// for registering tests with a fixture +#define DOCTEST_TEST_CASE_FIXTURE(c, decorators) \ + DOCTEST_IMPLEMENT_FIXTURE(DOCTEST_ANONYMOUS(DOCTEST_ANON_CLASS_), c, \ + DOCTEST_ANONYMOUS(DOCTEST_ANON_FUNC_), decorators) + +// for converting types to strings without the header and demangling +#define DOCTEST_TYPE_TO_STRING_AS(str, ...) \ + namespace doctest { \ + template <> \ + inline String toString<__VA_ARGS__>() { \ + return str; \ + } \ + } \ + static_assert(true, "") + +#define DOCTEST_TYPE_TO_STRING(...) DOCTEST_TYPE_TO_STRING_AS(#__VA_ARGS__, __VA_ARGS__) + +#define DOCTEST_TEST_CASE_TEMPLATE_DEFINE_IMPL(dec, T, iter, func) \ + template \ + static void func(); \ + namespace { /* NOLINT */ \ + template \ + struct iter; \ + template \ + struct iter> \ + { \ + iter(const char* file, unsigned line, int index) { \ + doctest::detail::regTest(doctest::detail::TestCase(func, file, line, \ + doctest_detail_test_suite_ns::getCurrentTestSuite(), \ + doctest::toString(), \ + int(line) * 1000 + index) \ + * dec); \ + iter>(file, line, index + 1); \ + } \ + }; \ + template <> \ + struct iter> \ + { \ + iter(const char*, unsigned, int) {} \ + }; \ + } \ + template \ + static void func() + +#define DOCTEST_TEST_CASE_TEMPLATE_DEFINE(dec, T, id) \ + DOCTEST_TEST_CASE_TEMPLATE_DEFINE_IMPL(dec, T, DOCTEST_CAT(id, ITERATOR), \ + DOCTEST_ANONYMOUS(DOCTEST_ANON_TMP_)) + +#define DOCTEST_TEST_CASE_TEMPLATE_INSTANTIATE_IMPL(id, anon, ...) \ + DOCTEST_GLOBAL_NO_WARNINGS(DOCTEST_CAT(anon, DUMMY), /* NOLINT(cert-err58-cpp, fuchsia-statically-constructed-objects) */ \ + doctest::detail::instantiationHelper( \ + DOCTEST_CAT(id, ITERATOR)<__VA_ARGS__>(__FILE__, __LINE__, 0))) + +#define DOCTEST_TEST_CASE_TEMPLATE_INVOKE(id, ...) \ + DOCTEST_TEST_CASE_TEMPLATE_INSTANTIATE_IMPL(id, DOCTEST_ANONYMOUS(DOCTEST_ANON_TMP_), std::tuple<__VA_ARGS__>) \ + static_assert(true, "") + +#define DOCTEST_TEST_CASE_TEMPLATE_APPLY(id, ...) \ + DOCTEST_TEST_CASE_TEMPLATE_INSTANTIATE_IMPL(id, DOCTEST_ANONYMOUS(DOCTEST_ANON_TMP_), __VA_ARGS__) \ + static_assert(true, "") + +#define DOCTEST_TEST_CASE_TEMPLATE_IMPL(dec, T, anon, ...) \ + DOCTEST_TEST_CASE_TEMPLATE_DEFINE_IMPL(dec, T, DOCTEST_CAT(anon, ITERATOR), anon); \ + DOCTEST_TEST_CASE_TEMPLATE_INSTANTIATE_IMPL(anon, anon, std::tuple<__VA_ARGS__>) \ + template \ + static void anon() + +#define DOCTEST_TEST_CASE_TEMPLATE(dec, T, ...) \ + DOCTEST_TEST_CASE_TEMPLATE_IMPL(dec, T, DOCTEST_ANONYMOUS(DOCTEST_ANON_TMP_), __VA_ARGS__) + +// for subcases +#define DOCTEST_SUBCASE(name) \ + if(const doctest::detail::Subcase & DOCTEST_ANONYMOUS(DOCTEST_ANON_SUBCASE_) DOCTEST_UNUSED = \ + doctest::detail::Subcase(name, __FILE__, __LINE__)) + +// for grouping tests in test suites by using code blocks +#define DOCTEST_TEST_SUITE_IMPL(decorators, ns_name) \ + namespace ns_name { namespace doctest_detail_test_suite_ns { \ + static DOCTEST_NOINLINE doctest::detail::TestSuite& getCurrentTestSuite() noexcept { \ + DOCTEST_MSVC_SUPPRESS_WARNING_WITH_PUSH(4640) \ + DOCTEST_CLANG_SUPPRESS_WARNING_WITH_PUSH("-Wexit-time-destructors") \ + DOCTEST_GCC_SUPPRESS_WARNING_WITH_PUSH("-Wmissing-field-initializers") \ + static doctest::detail::TestSuite data{}; \ + static bool inited = false; \ + DOCTEST_MSVC_SUPPRESS_WARNING_POP \ + DOCTEST_CLANG_SUPPRESS_WARNING_POP \ + DOCTEST_GCC_SUPPRESS_WARNING_POP \ + if(!inited) { \ + data* decorators; \ + inited = true; \ + } \ + return data; \ + } \ + } \ + } \ + namespace ns_name + +#define DOCTEST_TEST_SUITE(decorators) \ + DOCTEST_TEST_SUITE_IMPL(decorators, DOCTEST_ANONYMOUS(DOCTEST_ANON_SUITE_)) + +// for starting a testsuite block +#define DOCTEST_TEST_SUITE_BEGIN(decorators) \ + DOCTEST_GLOBAL_NO_WARNINGS(DOCTEST_ANONYMOUS(DOCTEST_ANON_VAR_), /* NOLINT(cert-err58-cpp) */ \ + doctest::detail::setTestSuite(doctest::detail::TestSuite() * decorators)) \ + static_assert(true, "") + +// for ending a testsuite block +#define DOCTEST_TEST_SUITE_END \ + DOCTEST_GLOBAL_NO_WARNINGS(DOCTEST_ANONYMOUS(DOCTEST_ANON_VAR_), /* NOLINT(cert-err58-cpp) */ \ + doctest::detail::setTestSuite(doctest::detail::TestSuite() * "")) \ + using DOCTEST_ANONYMOUS(DOCTEST_ANON_FOR_SEMICOLON_) = int + +// for registering exception translators +#define DOCTEST_REGISTER_EXCEPTION_TRANSLATOR_IMPL(translatorName, signature) \ + inline doctest::String translatorName(signature); \ + DOCTEST_GLOBAL_NO_WARNINGS(DOCTEST_ANONYMOUS(DOCTEST_ANON_TRANSLATOR_), /* NOLINT(cert-err58-cpp) */ \ + doctest::registerExceptionTranslator(translatorName)) \ + doctest::String translatorName(signature) + +#define DOCTEST_REGISTER_EXCEPTION_TRANSLATOR(signature) \ + DOCTEST_REGISTER_EXCEPTION_TRANSLATOR_IMPL(DOCTEST_ANONYMOUS(DOCTEST_ANON_TRANSLATOR_), \ + signature) + +// for registering reporters +#define DOCTEST_REGISTER_REPORTER(name, priority, reporter) \ + DOCTEST_GLOBAL_NO_WARNINGS(DOCTEST_ANONYMOUS(DOCTEST_ANON_REPORTER_), /* NOLINT(cert-err58-cpp) */ \ + doctest::registerReporter(name, priority, true)) \ + static_assert(true, "") + +// for registering listeners +#define DOCTEST_REGISTER_LISTENER(name, priority, reporter) \ + DOCTEST_GLOBAL_NO_WARNINGS(DOCTEST_ANONYMOUS(DOCTEST_ANON_REPORTER_), /* NOLINT(cert-err58-cpp) */ \ + doctest::registerReporter(name, priority, false)) \ + static_assert(true, "") + +// clang-format off +// for logging - disabling formatting because it's important to have these on 2 separate lines - see PR #557 +#define DOCTEST_INFO(...) \ + DOCTEST_INFO_IMPL(DOCTEST_ANONYMOUS(DOCTEST_CAPTURE_), \ + DOCTEST_ANONYMOUS(DOCTEST_CAPTURE_OTHER_), \ + __VA_ARGS__) +// clang-format on + +#define DOCTEST_INFO_IMPL(mb_name, s_name, ...) \ + auto DOCTEST_ANONYMOUS(DOCTEST_CAPTURE_) = doctest::detail::MakeContextScope( \ + [&](std::ostream* s_name) { \ + doctest::detail::MessageBuilder mb_name(__FILE__, __LINE__, doctest::assertType::is_warn); \ + mb_name.m_stream = s_name; \ + mb_name * __VA_ARGS__; \ + }) + +#define DOCTEST_CAPTURE(x) DOCTEST_INFO(#x " := ", x) + +#define DOCTEST_ADD_AT_IMPL(type, file, line, mb, ...) \ + DOCTEST_FUNC_SCOPE_BEGIN { \ + doctest::detail::MessageBuilder mb(file, line, doctest::assertType::type); \ + mb * __VA_ARGS__; \ + if(mb.log()) \ + DOCTEST_BREAK_INTO_DEBUGGER(); \ + mb.react(); \ + } DOCTEST_FUNC_SCOPE_END + +// clang-format off +#define DOCTEST_ADD_MESSAGE_AT(file, line, ...) DOCTEST_ADD_AT_IMPL(is_warn, file, line, DOCTEST_ANONYMOUS(DOCTEST_MESSAGE_), __VA_ARGS__) +#define DOCTEST_ADD_FAIL_CHECK_AT(file, line, ...) DOCTEST_ADD_AT_IMPL(is_check, file, line, DOCTEST_ANONYMOUS(DOCTEST_MESSAGE_), __VA_ARGS__) +#define DOCTEST_ADD_FAIL_AT(file, line, ...) DOCTEST_ADD_AT_IMPL(is_require, file, line, DOCTEST_ANONYMOUS(DOCTEST_MESSAGE_), __VA_ARGS__) +// clang-format on + +#define DOCTEST_MESSAGE(...) DOCTEST_ADD_MESSAGE_AT(__FILE__, __LINE__, __VA_ARGS__) +#define DOCTEST_FAIL_CHECK(...) DOCTEST_ADD_FAIL_CHECK_AT(__FILE__, __LINE__, __VA_ARGS__) +#define DOCTEST_FAIL(...) DOCTEST_ADD_FAIL_AT(__FILE__, __LINE__, __VA_ARGS__) + +#define DOCTEST_TO_LVALUE(...) __VA_ARGS__ // Not removed to keep backwards compatibility. + +#ifndef DOCTEST_CONFIG_SUPER_FAST_ASSERTS + +#define DOCTEST_ASSERT_IMPLEMENT_2(assert_type, ...) \ + DOCTEST_CLANG_SUPPRESS_WARNING_WITH_PUSH("-Woverloaded-shift-op-parentheses") \ + /* NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks) */ \ + doctest::detail::ResultBuilder DOCTEST_RB(doctest::assertType::assert_type, __FILE__, \ + __LINE__, #__VA_ARGS__); \ + DOCTEST_WRAP_IN_TRY(DOCTEST_RB.setResult( \ + doctest::detail::ExpressionDecomposer(doctest::assertType::assert_type) \ + << __VA_ARGS__)) /* NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks) */ \ + DOCTEST_ASSERT_LOG_REACT_RETURN(DOCTEST_RB) \ + DOCTEST_CLANG_SUPPRESS_WARNING_POP + +#define DOCTEST_ASSERT_IMPLEMENT_1(assert_type, ...) \ + DOCTEST_FUNC_SCOPE_BEGIN { \ + DOCTEST_ASSERT_IMPLEMENT_2(assert_type, __VA_ARGS__); \ + } DOCTEST_FUNC_SCOPE_END // NOLINT(clang-analyzer-cplusplus.NewDeleteLeaks) + +#define DOCTEST_BINARY_ASSERT(assert_type, comp, ...) \ + DOCTEST_FUNC_SCOPE_BEGIN { \ + doctest::detail::ResultBuilder DOCTEST_RB(doctest::assertType::assert_type, __FILE__, \ + __LINE__, #__VA_ARGS__); \ + DOCTEST_WRAP_IN_TRY( \ + DOCTEST_RB.binary_assert( \ + __VA_ARGS__)) \ + DOCTEST_ASSERT_LOG_REACT_RETURN(DOCTEST_RB); \ + } DOCTEST_FUNC_SCOPE_END + +#define DOCTEST_UNARY_ASSERT(assert_type, ...) \ + DOCTEST_FUNC_SCOPE_BEGIN { \ + doctest::detail::ResultBuilder DOCTEST_RB(doctest::assertType::assert_type, __FILE__, \ + __LINE__, #__VA_ARGS__); \ + DOCTEST_WRAP_IN_TRY(DOCTEST_RB.unary_assert(__VA_ARGS__)) \ + DOCTEST_ASSERT_LOG_REACT_RETURN(DOCTEST_RB); \ + } DOCTEST_FUNC_SCOPE_END + +#else // DOCTEST_CONFIG_SUPER_FAST_ASSERTS + +// necessary for _MESSAGE +#define DOCTEST_ASSERT_IMPLEMENT_2 DOCTEST_ASSERT_IMPLEMENT_1 + +#define DOCTEST_ASSERT_IMPLEMENT_1(assert_type, ...) \ + DOCTEST_CLANG_SUPPRESS_WARNING_WITH_PUSH("-Woverloaded-shift-op-parentheses") \ + doctest::detail::decomp_assert( \ + doctest::assertType::assert_type, __FILE__, __LINE__, #__VA_ARGS__, \ + doctest::detail::ExpressionDecomposer(doctest::assertType::assert_type) \ + << __VA_ARGS__) DOCTEST_CLANG_SUPPRESS_WARNING_POP + +#define DOCTEST_BINARY_ASSERT(assert_type, comparison, ...) \ + doctest::detail::binary_assert( \ + doctest::assertType::assert_type, __FILE__, __LINE__, #__VA_ARGS__, __VA_ARGS__) + +#define DOCTEST_UNARY_ASSERT(assert_type, ...) \ + doctest::detail::unary_assert(doctest::assertType::assert_type, __FILE__, __LINE__, \ + #__VA_ARGS__, __VA_ARGS__) + +#endif // DOCTEST_CONFIG_SUPER_FAST_ASSERTS + +#define DOCTEST_WARN(...) DOCTEST_ASSERT_IMPLEMENT_1(DT_WARN, __VA_ARGS__) +#define DOCTEST_CHECK(...) DOCTEST_ASSERT_IMPLEMENT_1(DT_CHECK, __VA_ARGS__) +#define DOCTEST_REQUIRE(...) DOCTEST_ASSERT_IMPLEMENT_1(DT_REQUIRE, __VA_ARGS__) +#define DOCTEST_WARN_FALSE(...) DOCTEST_ASSERT_IMPLEMENT_1(DT_WARN_FALSE, __VA_ARGS__) +#define DOCTEST_CHECK_FALSE(...) DOCTEST_ASSERT_IMPLEMENT_1(DT_CHECK_FALSE, __VA_ARGS__) +#define DOCTEST_REQUIRE_FALSE(...) DOCTEST_ASSERT_IMPLEMENT_1(DT_REQUIRE_FALSE, __VA_ARGS__) + +// clang-format off +#define DOCTEST_WARN_MESSAGE(cond, ...) DOCTEST_FUNC_SCOPE_BEGIN { DOCTEST_INFO(__VA_ARGS__); DOCTEST_ASSERT_IMPLEMENT_2(DT_WARN, cond); } DOCTEST_FUNC_SCOPE_END +#define DOCTEST_CHECK_MESSAGE(cond, ...) DOCTEST_FUNC_SCOPE_BEGIN { DOCTEST_INFO(__VA_ARGS__); DOCTEST_ASSERT_IMPLEMENT_2(DT_CHECK, cond); } DOCTEST_FUNC_SCOPE_END +#define DOCTEST_REQUIRE_MESSAGE(cond, ...) DOCTEST_FUNC_SCOPE_BEGIN { DOCTEST_INFO(__VA_ARGS__); DOCTEST_ASSERT_IMPLEMENT_2(DT_REQUIRE, cond); } DOCTEST_FUNC_SCOPE_END +#define DOCTEST_WARN_FALSE_MESSAGE(cond, ...) DOCTEST_FUNC_SCOPE_BEGIN { DOCTEST_INFO(__VA_ARGS__); DOCTEST_ASSERT_IMPLEMENT_2(DT_WARN_FALSE, cond); } DOCTEST_FUNC_SCOPE_END +#define DOCTEST_CHECK_FALSE_MESSAGE(cond, ...) DOCTEST_FUNC_SCOPE_BEGIN { DOCTEST_INFO(__VA_ARGS__); DOCTEST_ASSERT_IMPLEMENT_2(DT_CHECK_FALSE, cond); } DOCTEST_FUNC_SCOPE_END +#define DOCTEST_REQUIRE_FALSE_MESSAGE(cond, ...) DOCTEST_FUNC_SCOPE_BEGIN { DOCTEST_INFO(__VA_ARGS__); DOCTEST_ASSERT_IMPLEMENT_2(DT_REQUIRE_FALSE, cond); } DOCTEST_FUNC_SCOPE_END +// clang-format on + +#define DOCTEST_WARN_EQ(...) DOCTEST_BINARY_ASSERT(DT_WARN_EQ, eq, __VA_ARGS__) +#define DOCTEST_CHECK_EQ(...) DOCTEST_BINARY_ASSERT(DT_CHECK_EQ, eq, __VA_ARGS__) +#define DOCTEST_REQUIRE_EQ(...) DOCTEST_BINARY_ASSERT(DT_REQUIRE_EQ, eq, __VA_ARGS__) +#define DOCTEST_WARN_NE(...) DOCTEST_BINARY_ASSERT(DT_WARN_NE, ne, __VA_ARGS__) +#define DOCTEST_CHECK_NE(...) DOCTEST_BINARY_ASSERT(DT_CHECK_NE, ne, __VA_ARGS__) +#define DOCTEST_REQUIRE_NE(...) DOCTEST_BINARY_ASSERT(DT_REQUIRE_NE, ne, __VA_ARGS__) +#define DOCTEST_WARN_GT(...) DOCTEST_BINARY_ASSERT(DT_WARN_GT, gt, __VA_ARGS__) +#define DOCTEST_CHECK_GT(...) DOCTEST_BINARY_ASSERT(DT_CHECK_GT, gt, __VA_ARGS__) +#define DOCTEST_REQUIRE_GT(...) DOCTEST_BINARY_ASSERT(DT_REQUIRE_GT, gt, __VA_ARGS__) +#define DOCTEST_WARN_LT(...) DOCTEST_BINARY_ASSERT(DT_WARN_LT, lt, __VA_ARGS__) +#define DOCTEST_CHECK_LT(...) DOCTEST_BINARY_ASSERT(DT_CHECK_LT, lt, __VA_ARGS__) +#define DOCTEST_REQUIRE_LT(...) DOCTEST_BINARY_ASSERT(DT_REQUIRE_LT, lt, __VA_ARGS__) +#define DOCTEST_WARN_GE(...) DOCTEST_BINARY_ASSERT(DT_WARN_GE, ge, __VA_ARGS__) +#define DOCTEST_CHECK_GE(...) DOCTEST_BINARY_ASSERT(DT_CHECK_GE, ge, __VA_ARGS__) +#define DOCTEST_REQUIRE_GE(...) DOCTEST_BINARY_ASSERT(DT_REQUIRE_GE, ge, __VA_ARGS__) +#define DOCTEST_WARN_LE(...) DOCTEST_BINARY_ASSERT(DT_WARN_LE, le, __VA_ARGS__) +#define DOCTEST_CHECK_LE(...) DOCTEST_BINARY_ASSERT(DT_CHECK_LE, le, __VA_ARGS__) +#define DOCTEST_REQUIRE_LE(...) DOCTEST_BINARY_ASSERT(DT_REQUIRE_LE, le, __VA_ARGS__) + +#define DOCTEST_WARN_UNARY(...) DOCTEST_UNARY_ASSERT(DT_WARN_UNARY, __VA_ARGS__) +#define DOCTEST_CHECK_UNARY(...) DOCTEST_UNARY_ASSERT(DT_CHECK_UNARY, __VA_ARGS__) +#define DOCTEST_REQUIRE_UNARY(...) DOCTEST_UNARY_ASSERT(DT_REQUIRE_UNARY, __VA_ARGS__) +#define DOCTEST_WARN_UNARY_FALSE(...) DOCTEST_UNARY_ASSERT(DT_WARN_UNARY_FALSE, __VA_ARGS__) +#define DOCTEST_CHECK_UNARY_FALSE(...) DOCTEST_UNARY_ASSERT(DT_CHECK_UNARY_FALSE, __VA_ARGS__) +#define DOCTEST_REQUIRE_UNARY_FALSE(...) DOCTEST_UNARY_ASSERT(DT_REQUIRE_UNARY_FALSE, __VA_ARGS__) + +#ifndef DOCTEST_CONFIG_NO_EXCEPTIONS + +#define DOCTEST_ASSERT_THROWS_AS(expr, assert_type, message, ...) \ + DOCTEST_FUNC_SCOPE_BEGIN { \ + if(!doctest::getContextOptions()->no_throw) { \ + doctest::detail::ResultBuilder DOCTEST_RB(doctest::assertType::assert_type, __FILE__, \ + __LINE__, #expr, #__VA_ARGS__, message); \ + try { \ + DOCTEST_CAST_TO_VOID(expr) \ + } catch(const typename doctest::detail::types::remove_const< \ + typename doctest::detail::types::remove_reference<__VA_ARGS__>::type>::type&) {\ + DOCTEST_RB.translateException(); \ + DOCTEST_RB.m_threw_as = true; \ + } catch(...) { DOCTEST_RB.translateException(); } \ + DOCTEST_ASSERT_LOG_REACT_RETURN(DOCTEST_RB); \ + } else { /* NOLINT(*-else-after-return) */ \ + DOCTEST_FUNC_SCOPE_RET(false); \ + } \ + } DOCTEST_FUNC_SCOPE_END + +#define DOCTEST_ASSERT_THROWS_WITH(expr, expr_str, assert_type, ...) \ + DOCTEST_FUNC_SCOPE_BEGIN { \ + if(!doctest::getContextOptions()->no_throw) { \ + doctest::detail::ResultBuilder DOCTEST_RB(doctest::assertType::assert_type, __FILE__, \ + __LINE__, expr_str, "", __VA_ARGS__); \ + try { \ + DOCTEST_CAST_TO_VOID(expr) \ + } catch(...) { DOCTEST_RB.translateException(); } \ + DOCTEST_ASSERT_LOG_REACT_RETURN(DOCTEST_RB); \ + } else { /* NOLINT(*-else-after-return) */ \ + DOCTEST_FUNC_SCOPE_RET(false); \ + } \ + } DOCTEST_FUNC_SCOPE_END + +#define DOCTEST_ASSERT_NOTHROW(assert_type, ...) \ + DOCTEST_FUNC_SCOPE_BEGIN { \ + doctest::detail::ResultBuilder DOCTEST_RB(doctest::assertType::assert_type, __FILE__, \ + __LINE__, #__VA_ARGS__); \ + try { \ + DOCTEST_CAST_TO_VOID(__VA_ARGS__) \ + } catch(...) { DOCTEST_RB.translateException(); } \ + DOCTEST_ASSERT_LOG_REACT_RETURN(DOCTEST_RB); \ + } DOCTEST_FUNC_SCOPE_END + +// clang-format off +#define DOCTEST_WARN_THROWS(...) DOCTEST_ASSERT_THROWS_WITH((__VA_ARGS__), #__VA_ARGS__, DT_WARN_THROWS, "") +#define DOCTEST_CHECK_THROWS(...) DOCTEST_ASSERT_THROWS_WITH((__VA_ARGS__), #__VA_ARGS__, DT_CHECK_THROWS, "") +#define DOCTEST_REQUIRE_THROWS(...) DOCTEST_ASSERT_THROWS_WITH((__VA_ARGS__), #__VA_ARGS__, DT_REQUIRE_THROWS, "") + +#define DOCTEST_WARN_THROWS_AS(expr, ...) DOCTEST_ASSERT_THROWS_AS(expr, DT_WARN_THROWS_AS, "", __VA_ARGS__) +#define DOCTEST_CHECK_THROWS_AS(expr, ...) DOCTEST_ASSERT_THROWS_AS(expr, DT_CHECK_THROWS_AS, "", __VA_ARGS__) +#define DOCTEST_REQUIRE_THROWS_AS(expr, ...) DOCTEST_ASSERT_THROWS_AS(expr, DT_REQUIRE_THROWS_AS, "", __VA_ARGS__) + +#define DOCTEST_WARN_THROWS_WITH(expr, ...) DOCTEST_ASSERT_THROWS_WITH(expr, #expr, DT_WARN_THROWS_WITH, __VA_ARGS__) +#define DOCTEST_CHECK_THROWS_WITH(expr, ...) DOCTEST_ASSERT_THROWS_WITH(expr, #expr, DT_CHECK_THROWS_WITH, __VA_ARGS__) +#define DOCTEST_REQUIRE_THROWS_WITH(expr, ...) DOCTEST_ASSERT_THROWS_WITH(expr, #expr, DT_REQUIRE_THROWS_WITH, __VA_ARGS__) + +#define DOCTEST_WARN_THROWS_WITH_AS(expr, message, ...) DOCTEST_ASSERT_THROWS_AS(expr, DT_WARN_THROWS_WITH_AS, message, __VA_ARGS__) +#define DOCTEST_CHECK_THROWS_WITH_AS(expr, message, ...) DOCTEST_ASSERT_THROWS_AS(expr, DT_CHECK_THROWS_WITH_AS, message, __VA_ARGS__) +#define DOCTEST_REQUIRE_THROWS_WITH_AS(expr, message, ...) DOCTEST_ASSERT_THROWS_AS(expr, DT_REQUIRE_THROWS_WITH_AS, message, __VA_ARGS__) + +#define DOCTEST_WARN_NOTHROW(...) DOCTEST_ASSERT_NOTHROW(DT_WARN_NOTHROW, __VA_ARGS__) +#define DOCTEST_CHECK_NOTHROW(...) DOCTEST_ASSERT_NOTHROW(DT_CHECK_NOTHROW, __VA_ARGS__) +#define DOCTEST_REQUIRE_NOTHROW(...) DOCTEST_ASSERT_NOTHROW(DT_REQUIRE_NOTHROW, __VA_ARGS__) + +#define DOCTEST_WARN_THROWS_MESSAGE(expr, ...) DOCTEST_FUNC_SCOPE_BEGIN { DOCTEST_INFO(__VA_ARGS__); DOCTEST_WARN_THROWS(expr); } DOCTEST_FUNC_SCOPE_END +#define DOCTEST_CHECK_THROWS_MESSAGE(expr, ...) DOCTEST_FUNC_SCOPE_BEGIN { DOCTEST_INFO(__VA_ARGS__); DOCTEST_CHECK_THROWS(expr); } DOCTEST_FUNC_SCOPE_END +#define DOCTEST_REQUIRE_THROWS_MESSAGE(expr, ...) DOCTEST_FUNC_SCOPE_BEGIN { DOCTEST_INFO(__VA_ARGS__); DOCTEST_REQUIRE_THROWS(expr); } DOCTEST_FUNC_SCOPE_END +#define DOCTEST_WARN_THROWS_AS_MESSAGE(expr, ex, ...) DOCTEST_FUNC_SCOPE_BEGIN { DOCTEST_INFO(__VA_ARGS__); DOCTEST_WARN_THROWS_AS(expr, ex); } DOCTEST_FUNC_SCOPE_END +#define DOCTEST_CHECK_THROWS_AS_MESSAGE(expr, ex, ...) DOCTEST_FUNC_SCOPE_BEGIN { DOCTEST_INFO(__VA_ARGS__); DOCTEST_CHECK_THROWS_AS(expr, ex); } DOCTEST_FUNC_SCOPE_END +#define DOCTEST_REQUIRE_THROWS_AS_MESSAGE(expr, ex, ...) DOCTEST_FUNC_SCOPE_BEGIN { DOCTEST_INFO(__VA_ARGS__); DOCTEST_REQUIRE_THROWS_AS(expr, ex); } DOCTEST_FUNC_SCOPE_END +#define DOCTEST_WARN_THROWS_WITH_MESSAGE(expr, with, ...) DOCTEST_FUNC_SCOPE_BEGIN { DOCTEST_INFO(__VA_ARGS__); DOCTEST_WARN_THROWS_WITH(expr, with); } DOCTEST_FUNC_SCOPE_END +#define DOCTEST_CHECK_THROWS_WITH_MESSAGE(expr, with, ...) DOCTEST_FUNC_SCOPE_BEGIN { DOCTEST_INFO(__VA_ARGS__); DOCTEST_CHECK_THROWS_WITH(expr, with); } DOCTEST_FUNC_SCOPE_END +#define DOCTEST_REQUIRE_THROWS_WITH_MESSAGE(expr, with, ...) DOCTEST_FUNC_SCOPE_BEGIN { DOCTEST_INFO(__VA_ARGS__); DOCTEST_REQUIRE_THROWS_WITH(expr, with); } DOCTEST_FUNC_SCOPE_END +#define DOCTEST_WARN_THROWS_WITH_AS_MESSAGE(expr, with, ex, ...) DOCTEST_FUNC_SCOPE_BEGIN { DOCTEST_INFO(__VA_ARGS__); DOCTEST_WARN_THROWS_WITH_AS(expr, with, ex); } DOCTEST_FUNC_SCOPE_END +#define DOCTEST_CHECK_THROWS_WITH_AS_MESSAGE(expr, with, ex, ...) DOCTEST_FUNC_SCOPE_BEGIN { DOCTEST_INFO(__VA_ARGS__); DOCTEST_CHECK_THROWS_WITH_AS(expr, with, ex); } DOCTEST_FUNC_SCOPE_END +#define DOCTEST_REQUIRE_THROWS_WITH_AS_MESSAGE(expr, with, ex, ...) DOCTEST_FUNC_SCOPE_BEGIN { DOCTEST_INFO(__VA_ARGS__); DOCTEST_REQUIRE_THROWS_WITH_AS(expr, with, ex); } DOCTEST_FUNC_SCOPE_END +#define DOCTEST_WARN_NOTHROW_MESSAGE(expr, ...) DOCTEST_FUNC_SCOPE_BEGIN { DOCTEST_INFO(__VA_ARGS__); DOCTEST_WARN_NOTHROW(expr); } DOCTEST_FUNC_SCOPE_END +#define DOCTEST_CHECK_NOTHROW_MESSAGE(expr, ...) DOCTEST_FUNC_SCOPE_BEGIN { DOCTEST_INFO(__VA_ARGS__); DOCTEST_CHECK_NOTHROW(expr); } DOCTEST_FUNC_SCOPE_END +#define DOCTEST_REQUIRE_NOTHROW_MESSAGE(expr, ...) DOCTEST_FUNC_SCOPE_BEGIN { DOCTEST_INFO(__VA_ARGS__); DOCTEST_REQUIRE_NOTHROW(expr); } DOCTEST_FUNC_SCOPE_END +// clang-format on + +#endif // DOCTEST_CONFIG_NO_EXCEPTIONS + +// ================================================================================================= +// == WHAT FOLLOWS IS VERSIONS OF THE MACROS THAT DO NOT DO ANY REGISTERING! == +// == THIS CAN BE ENABLED BY DEFINING DOCTEST_CONFIG_DISABLE GLOBALLY! == +// ================================================================================================= +#else // DOCTEST_CONFIG_DISABLE + +#define DOCTEST_IMPLEMENT_FIXTURE(der, base, func, name) \ + namespace /* NOLINT */ { \ + template \ + struct der : public base \ + { void f(); }; \ + } \ + template \ + inline void der::f() + +#define DOCTEST_CREATE_AND_REGISTER_FUNCTION(f, name) \ + template \ + static inline void f() + +// for registering tests +#define DOCTEST_TEST_CASE(name) \ + DOCTEST_CREATE_AND_REGISTER_FUNCTION(DOCTEST_ANONYMOUS(DOCTEST_ANON_FUNC_), name) + +// for registering tests in classes +#define DOCTEST_TEST_CASE_CLASS(name) \ + DOCTEST_CREATE_AND_REGISTER_FUNCTION(DOCTEST_ANONYMOUS(DOCTEST_ANON_FUNC_), name) + +// for registering tests with a fixture +#define DOCTEST_TEST_CASE_FIXTURE(x, name) \ + DOCTEST_IMPLEMENT_FIXTURE(DOCTEST_ANONYMOUS(DOCTEST_ANON_CLASS_), x, \ + DOCTEST_ANONYMOUS(DOCTEST_ANON_FUNC_), name) + +// for converting types to strings without the header and demangling +#define DOCTEST_TYPE_TO_STRING_AS(str, ...) static_assert(true, "") +#define DOCTEST_TYPE_TO_STRING(...) static_assert(true, "") + +// for typed tests +#define DOCTEST_TEST_CASE_TEMPLATE(name, type, ...) \ + template \ + inline void DOCTEST_ANONYMOUS(DOCTEST_ANON_TMP_)() + +#define DOCTEST_TEST_CASE_TEMPLATE_DEFINE(name, type, id) \ + template \ + inline void DOCTEST_ANONYMOUS(DOCTEST_ANON_TMP_)() + +#define DOCTEST_TEST_CASE_TEMPLATE_INVOKE(id, ...) static_assert(true, "") +#define DOCTEST_TEST_CASE_TEMPLATE_APPLY(id, ...) static_assert(true, "") + +// for subcases +#define DOCTEST_SUBCASE(name) + +// for a testsuite block +#define DOCTEST_TEST_SUITE(name) namespace // NOLINT + +// for starting a testsuite block +#define DOCTEST_TEST_SUITE_BEGIN(name) static_assert(true, "") + +// for ending a testsuite block +#define DOCTEST_TEST_SUITE_END using DOCTEST_ANONYMOUS(DOCTEST_ANON_FOR_SEMICOLON_) = int + +#define DOCTEST_REGISTER_EXCEPTION_TRANSLATOR(signature) \ + template \ + static inline doctest::String DOCTEST_ANONYMOUS(DOCTEST_ANON_TRANSLATOR_)(signature) + +#define DOCTEST_REGISTER_REPORTER(name, priority, reporter) +#define DOCTEST_REGISTER_LISTENER(name, priority, reporter) + +#define DOCTEST_INFO(...) (static_cast(0)) +#define DOCTEST_CAPTURE(x) (static_cast(0)) +#define DOCTEST_ADD_MESSAGE_AT(file, line, ...) (static_cast(0)) +#define DOCTEST_ADD_FAIL_CHECK_AT(file, line, ...) (static_cast(0)) +#define DOCTEST_ADD_FAIL_AT(file, line, ...) (static_cast(0)) +#define DOCTEST_MESSAGE(...) (static_cast(0)) +#define DOCTEST_FAIL_CHECK(...) (static_cast(0)) +#define DOCTEST_FAIL(...) (static_cast(0)) + +#if defined(DOCTEST_CONFIG_EVALUATE_ASSERTS_EVEN_WHEN_DISABLED) \ + && defined(DOCTEST_CONFIG_ASSERTS_RETURN_VALUES) + +#define DOCTEST_WARN(...) [&] { return __VA_ARGS__; }() +#define DOCTEST_CHECK(...) [&] { return __VA_ARGS__; }() +#define DOCTEST_REQUIRE(...) [&] { return __VA_ARGS__; }() +#define DOCTEST_WARN_FALSE(...) [&] { return !(__VA_ARGS__); }() +#define DOCTEST_CHECK_FALSE(...) [&] { return !(__VA_ARGS__); }() +#define DOCTEST_REQUIRE_FALSE(...) [&] { return !(__VA_ARGS__); }() + +#define DOCTEST_WARN_MESSAGE(cond, ...) [&] { return cond; }() +#define DOCTEST_CHECK_MESSAGE(cond, ...) [&] { return cond; }() +#define DOCTEST_REQUIRE_MESSAGE(cond, ...) [&] { return cond; }() +#define DOCTEST_WARN_FALSE_MESSAGE(cond, ...) [&] { return !(cond); }() +#define DOCTEST_CHECK_FALSE_MESSAGE(cond, ...) [&] { return !(cond); }() +#define DOCTEST_REQUIRE_FALSE_MESSAGE(cond, ...) [&] { return !(cond); }() + +namespace doctest { +namespace detail { +#define DOCTEST_RELATIONAL_OP(name, op) \ + template \ + bool name(const DOCTEST_REF_WRAP(L) lhs, const DOCTEST_REF_WRAP(R) rhs) { return lhs op rhs; } + + DOCTEST_RELATIONAL_OP(eq, ==) + DOCTEST_RELATIONAL_OP(ne, !=) + DOCTEST_RELATIONAL_OP(lt, <) + DOCTEST_RELATIONAL_OP(gt, >) + DOCTEST_RELATIONAL_OP(le, <=) + DOCTEST_RELATIONAL_OP(ge, >=) +} // namespace detail +} // namespace doctest + +#define DOCTEST_WARN_EQ(...) [&] { return doctest::detail::eq(__VA_ARGS__); }() +#define DOCTEST_CHECK_EQ(...) [&] { return doctest::detail::eq(__VA_ARGS__); }() +#define DOCTEST_REQUIRE_EQ(...) [&] { return doctest::detail::eq(__VA_ARGS__); }() +#define DOCTEST_WARN_NE(...) [&] { return doctest::detail::ne(__VA_ARGS__); }() +#define DOCTEST_CHECK_NE(...) [&] { return doctest::detail::ne(__VA_ARGS__); }() +#define DOCTEST_REQUIRE_NE(...) [&] { return doctest::detail::ne(__VA_ARGS__); }() +#define DOCTEST_WARN_LT(...) [&] { return doctest::detail::lt(__VA_ARGS__); }() +#define DOCTEST_CHECK_LT(...) [&] { return doctest::detail::lt(__VA_ARGS__); }() +#define DOCTEST_REQUIRE_LT(...) [&] { return doctest::detail::lt(__VA_ARGS__); }() +#define DOCTEST_WARN_GT(...) [&] { return doctest::detail::gt(__VA_ARGS__); }() +#define DOCTEST_CHECK_GT(...) [&] { return doctest::detail::gt(__VA_ARGS__); }() +#define DOCTEST_REQUIRE_GT(...) [&] { return doctest::detail::gt(__VA_ARGS__); }() +#define DOCTEST_WARN_LE(...) [&] { return doctest::detail::le(__VA_ARGS__); }() +#define DOCTEST_CHECK_LE(...) [&] { return doctest::detail::le(__VA_ARGS__); }() +#define DOCTEST_REQUIRE_LE(...) [&] { return doctest::detail::le(__VA_ARGS__); }() +#define DOCTEST_WARN_GE(...) [&] { return doctest::detail::ge(__VA_ARGS__); }() +#define DOCTEST_CHECK_GE(...) [&] { return doctest::detail::ge(__VA_ARGS__); }() +#define DOCTEST_REQUIRE_GE(...) [&] { return doctest::detail::ge(__VA_ARGS__); }() +#define DOCTEST_WARN_UNARY(...) [&] { return __VA_ARGS__; }() +#define DOCTEST_CHECK_UNARY(...) [&] { return __VA_ARGS__; }() +#define DOCTEST_REQUIRE_UNARY(...) [&] { return __VA_ARGS__; }() +#define DOCTEST_WARN_UNARY_FALSE(...) [&] { return !(__VA_ARGS__); }() +#define DOCTEST_CHECK_UNARY_FALSE(...) [&] { return !(__VA_ARGS__); }() +#define DOCTEST_REQUIRE_UNARY_FALSE(...) [&] { return !(__VA_ARGS__); }() + +#ifndef DOCTEST_CONFIG_NO_EXCEPTIONS + +#define DOCTEST_WARN_THROWS_WITH(expr, with, ...) [] { static_assert(false, "Exception translation is not available when doctest is disabled."); return false; }() +#define DOCTEST_CHECK_THROWS_WITH(expr, with, ...) DOCTEST_WARN_THROWS_WITH(,,) +#define DOCTEST_REQUIRE_THROWS_WITH(expr, with, ...) DOCTEST_WARN_THROWS_WITH(,,) +#define DOCTEST_WARN_THROWS_WITH_AS(expr, with, ex, ...) DOCTEST_WARN_THROWS_WITH(,,) +#define DOCTEST_CHECK_THROWS_WITH_AS(expr, with, ex, ...) DOCTEST_WARN_THROWS_WITH(,,) +#define DOCTEST_REQUIRE_THROWS_WITH_AS(expr, with, ex, ...) DOCTEST_WARN_THROWS_WITH(,,) + +#define DOCTEST_WARN_THROWS_WITH_MESSAGE(expr, with, ...) DOCTEST_WARN_THROWS_WITH(,,) +#define DOCTEST_CHECK_THROWS_WITH_MESSAGE(expr, with, ...) DOCTEST_WARN_THROWS_WITH(,,) +#define DOCTEST_REQUIRE_THROWS_WITH_MESSAGE(expr, with, ...) DOCTEST_WARN_THROWS_WITH(,,) +#define DOCTEST_WARN_THROWS_WITH_AS_MESSAGE(expr, with, ex, ...) DOCTEST_WARN_THROWS_WITH(,,) +#define DOCTEST_CHECK_THROWS_WITH_AS_MESSAGE(expr, with, ex, ...) DOCTEST_WARN_THROWS_WITH(,,) +#define DOCTEST_REQUIRE_THROWS_WITH_AS_MESSAGE(expr, with, ex, ...) DOCTEST_WARN_THROWS_WITH(,,) + +#define DOCTEST_WARN_THROWS(...) [&] { try { __VA_ARGS__; return false; } catch (...) { return true; } }() +#define DOCTEST_CHECK_THROWS(...) [&] { try { __VA_ARGS__; return false; } catch (...) { return true; } }() +#define DOCTEST_REQUIRE_THROWS(...) [&] { try { __VA_ARGS__; return false; } catch (...) { return true; } }() +#define DOCTEST_WARN_THROWS_AS(expr, ...) [&] { try { expr; } catch (__VA_ARGS__) { return true; } catch (...) { } return false; }() +#define DOCTEST_CHECK_THROWS_AS(expr, ...) [&] { try { expr; } catch (__VA_ARGS__) { return true; } catch (...) { } return false; }() +#define DOCTEST_REQUIRE_THROWS_AS(expr, ...) [&] { try { expr; } catch (__VA_ARGS__) { return true; } catch (...) { } return false; }() +#define DOCTEST_WARN_NOTHROW(...) [&] { try { __VA_ARGS__; return true; } catch (...) { return false; } }() +#define DOCTEST_CHECK_NOTHROW(...) [&] { try { __VA_ARGS__; return true; } catch (...) { return false; } }() +#define DOCTEST_REQUIRE_NOTHROW(...) [&] { try { __VA_ARGS__; return true; } catch (...) { return false; } }() + +#define DOCTEST_WARN_THROWS_MESSAGE(expr, ...) [&] { try { __VA_ARGS__; return false; } catch (...) { return true; } }() +#define DOCTEST_CHECK_THROWS_MESSAGE(expr, ...) [&] { try { __VA_ARGS__; return false; } catch (...) { return true; } }() +#define DOCTEST_REQUIRE_THROWS_MESSAGE(expr, ...) [&] { try { __VA_ARGS__; return false; } catch (...) { return true; } }() +#define DOCTEST_WARN_THROWS_AS_MESSAGE(expr, ex, ...) [&] { try { expr; } catch (__VA_ARGS__) { return true; } catch (...) { } return false; }() +#define DOCTEST_CHECK_THROWS_AS_MESSAGE(expr, ex, ...) [&] { try { expr; } catch (__VA_ARGS__) { return true; } catch (...) { } return false; }() +#define DOCTEST_REQUIRE_THROWS_AS_MESSAGE(expr, ex, ...) [&] { try { expr; } catch (__VA_ARGS__) { return true; } catch (...) { } return false; }() +#define DOCTEST_WARN_NOTHROW_MESSAGE(expr, ...) [&] { try { __VA_ARGS__; return true; } catch (...) { return false; } }() +#define DOCTEST_CHECK_NOTHROW_MESSAGE(expr, ...) [&] { try { __VA_ARGS__; return true; } catch (...) { return false; } }() +#define DOCTEST_REQUIRE_NOTHROW_MESSAGE(expr, ...) [&] { try { __VA_ARGS__; return true; } catch (...) { return false; } }() + +#endif // DOCTEST_CONFIG_NO_EXCEPTIONS + +#else // DOCTEST_CONFIG_EVALUATE_ASSERTS_EVEN_WHEN_DISABLED + +#define DOCTEST_WARN(...) DOCTEST_FUNC_EMPTY +#define DOCTEST_CHECK(...) DOCTEST_FUNC_EMPTY +#define DOCTEST_REQUIRE(...) DOCTEST_FUNC_EMPTY +#define DOCTEST_WARN_FALSE(...) DOCTEST_FUNC_EMPTY +#define DOCTEST_CHECK_FALSE(...) DOCTEST_FUNC_EMPTY +#define DOCTEST_REQUIRE_FALSE(...) DOCTEST_FUNC_EMPTY + +#define DOCTEST_WARN_MESSAGE(cond, ...) DOCTEST_FUNC_EMPTY +#define DOCTEST_CHECK_MESSAGE(cond, ...) DOCTEST_FUNC_EMPTY +#define DOCTEST_REQUIRE_MESSAGE(cond, ...) DOCTEST_FUNC_EMPTY +#define DOCTEST_WARN_FALSE_MESSAGE(cond, ...) DOCTEST_FUNC_EMPTY +#define DOCTEST_CHECK_FALSE_MESSAGE(cond, ...) DOCTEST_FUNC_EMPTY +#define DOCTEST_REQUIRE_FALSE_MESSAGE(cond, ...) DOCTEST_FUNC_EMPTY + +#define DOCTEST_WARN_EQ(...) DOCTEST_FUNC_EMPTY +#define DOCTEST_CHECK_EQ(...) DOCTEST_FUNC_EMPTY +#define DOCTEST_REQUIRE_EQ(...) DOCTEST_FUNC_EMPTY +#define DOCTEST_WARN_NE(...) DOCTEST_FUNC_EMPTY +#define DOCTEST_CHECK_NE(...) DOCTEST_FUNC_EMPTY +#define DOCTEST_REQUIRE_NE(...) DOCTEST_FUNC_EMPTY +#define DOCTEST_WARN_GT(...) DOCTEST_FUNC_EMPTY +#define DOCTEST_CHECK_GT(...) DOCTEST_FUNC_EMPTY +#define DOCTEST_REQUIRE_GT(...) DOCTEST_FUNC_EMPTY +#define DOCTEST_WARN_LT(...) DOCTEST_FUNC_EMPTY +#define DOCTEST_CHECK_LT(...) DOCTEST_FUNC_EMPTY +#define DOCTEST_REQUIRE_LT(...) DOCTEST_FUNC_EMPTY +#define DOCTEST_WARN_GE(...) DOCTEST_FUNC_EMPTY +#define DOCTEST_CHECK_GE(...) DOCTEST_FUNC_EMPTY +#define DOCTEST_REQUIRE_GE(...) DOCTEST_FUNC_EMPTY +#define DOCTEST_WARN_LE(...) DOCTEST_FUNC_EMPTY +#define DOCTEST_CHECK_LE(...) DOCTEST_FUNC_EMPTY +#define DOCTEST_REQUIRE_LE(...) DOCTEST_FUNC_EMPTY + +#define DOCTEST_WARN_UNARY(...) DOCTEST_FUNC_EMPTY +#define DOCTEST_CHECK_UNARY(...) DOCTEST_FUNC_EMPTY +#define DOCTEST_REQUIRE_UNARY(...) DOCTEST_FUNC_EMPTY +#define DOCTEST_WARN_UNARY_FALSE(...) DOCTEST_FUNC_EMPTY +#define DOCTEST_CHECK_UNARY_FALSE(...) DOCTEST_FUNC_EMPTY +#define DOCTEST_REQUIRE_UNARY_FALSE(...) DOCTEST_FUNC_EMPTY + +#ifndef DOCTEST_CONFIG_NO_EXCEPTIONS + +#define DOCTEST_WARN_THROWS(...) DOCTEST_FUNC_EMPTY +#define DOCTEST_CHECK_THROWS(...) DOCTEST_FUNC_EMPTY +#define DOCTEST_REQUIRE_THROWS(...) DOCTEST_FUNC_EMPTY +#define DOCTEST_WARN_THROWS_AS(expr, ...) DOCTEST_FUNC_EMPTY +#define DOCTEST_CHECK_THROWS_AS(expr, ...) DOCTEST_FUNC_EMPTY +#define DOCTEST_REQUIRE_THROWS_AS(expr, ...) DOCTEST_FUNC_EMPTY +#define DOCTEST_WARN_THROWS_WITH(expr, ...) DOCTEST_FUNC_EMPTY +#define DOCTEST_CHECK_THROWS_WITH(expr, ...) DOCTEST_FUNC_EMPTY +#define DOCTEST_REQUIRE_THROWS_WITH(expr, ...) DOCTEST_FUNC_EMPTY +#define DOCTEST_WARN_THROWS_WITH_AS(expr, with, ...) DOCTEST_FUNC_EMPTY +#define DOCTEST_CHECK_THROWS_WITH_AS(expr, with, ...) DOCTEST_FUNC_EMPTY +#define DOCTEST_REQUIRE_THROWS_WITH_AS(expr, with, ...) DOCTEST_FUNC_EMPTY +#define DOCTEST_WARN_NOTHROW(...) DOCTEST_FUNC_EMPTY +#define DOCTEST_CHECK_NOTHROW(...) DOCTEST_FUNC_EMPTY +#define DOCTEST_REQUIRE_NOTHROW(...) DOCTEST_FUNC_EMPTY + +#define DOCTEST_WARN_THROWS_MESSAGE(expr, ...) DOCTEST_FUNC_EMPTY +#define DOCTEST_CHECK_THROWS_MESSAGE(expr, ...) DOCTEST_FUNC_EMPTY +#define DOCTEST_REQUIRE_THROWS_MESSAGE(expr, ...) DOCTEST_FUNC_EMPTY +#define DOCTEST_WARN_THROWS_AS_MESSAGE(expr, ex, ...) DOCTEST_FUNC_EMPTY +#define DOCTEST_CHECK_THROWS_AS_MESSAGE(expr, ex, ...) DOCTEST_FUNC_EMPTY +#define DOCTEST_REQUIRE_THROWS_AS_MESSAGE(expr, ex, ...) DOCTEST_FUNC_EMPTY +#define DOCTEST_WARN_THROWS_WITH_MESSAGE(expr, with, ...) DOCTEST_FUNC_EMPTY +#define DOCTEST_CHECK_THROWS_WITH_MESSAGE(expr, with, ...) DOCTEST_FUNC_EMPTY +#define DOCTEST_REQUIRE_THROWS_WITH_MESSAGE(expr, with, ...) DOCTEST_FUNC_EMPTY +#define DOCTEST_WARN_THROWS_WITH_AS_MESSAGE(expr, with, ex, ...) DOCTEST_FUNC_EMPTY +#define DOCTEST_CHECK_THROWS_WITH_AS_MESSAGE(expr, with, ex, ...) DOCTEST_FUNC_EMPTY +#define DOCTEST_REQUIRE_THROWS_WITH_AS_MESSAGE(expr, with, ex, ...) DOCTEST_FUNC_EMPTY +#define DOCTEST_WARN_NOTHROW_MESSAGE(expr, ...) DOCTEST_FUNC_EMPTY +#define DOCTEST_CHECK_NOTHROW_MESSAGE(expr, ...) DOCTEST_FUNC_EMPTY +#define DOCTEST_REQUIRE_NOTHROW_MESSAGE(expr, ...) DOCTEST_FUNC_EMPTY + +#endif // DOCTEST_CONFIG_NO_EXCEPTIONS + +#endif // DOCTEST_CONFIG_EVALUATE_ASSERTS_EVEN_WHEN_DISABLED + +#endif // DOCTEST_CONFIG_DISABLE + +#ifdef DOCTEST_CONFIG_NO_EXCEPTIONS + +#ifdef DOCTEST_CONFIG_NO_EXCEPTIONS_BUT_WITH_ALL_ASSERTS +#define DOCTEST_EXCEPTION_EMPTY_FUNC DOCTEST_FUNC_EMPTY +#else // DOCTEST_CONFIG_NO_EXCEPTIONS_BUT_WITH_ALL_ASSERTS +#define DOCTEST_EXCEPTION_EMPTY_FUNC [] { static_assert(false, "Exceptions are disabled! " \ + "Use DOCTEST_CONFIG_NO_EXCEPTIONS_BUT_WITH_ALL_ASSERTS if you want to compile with exceptions disabled."); return false; }() + +#undef DOCTEST_REQUIRE +#undef DOCTEST_REQUIRE_FALSE +#undef DOCTEST_REQUIRE_MESSAGE +#undef DOCTEST_REQUIRE_FALSE_MESSAGE +#undef DOCTEST_REQUIRE_EQ +#undef DOCTEST_REQUIRE_NE +#undef DOCTEST_REQUIRE_GT +#undef DOCTEST_REQUIRE_LT +#undef DOCTEST_REQUIRE_GE +#undef DOCTEST_REQUIRE_LE +#undef DOCTEST_REQUIRE_UNARY +#undef DOCTEST_REQUIRE_UNARY_FALSE + +#define DOCTEST_REQUIRE DOCTEST_EXCEPTION_EMPTY_FUNC +#define DOCTEST_REQUIRE_FALSE DOCTEST_EXCEPTION_EMPTY_FUNC +#define DOCTEST_REQUIRE_MESSAGE DOCTEST_EXCEPTION_EMPTY_FUNC +#define DOCTEST_REQUIRE_FALSE_MESSAGE DOCTEST_EXCEPTION_EMPTY_FUNC +#define DOCTEST_REQUIRE_EQ DOCTEST_EXCEPTION_EMPTY_FUNC +#define DOCTEST_REQUIRE_NE DOCTEST_EXCEPTION_EMPTY_FUNC +#define DOCTEST_REQUIRE_GT DOCTEST_EXCEPTION_EMPTY_FUNC +#define DOCTEST_REQUIRE_LT DOCTEST_EXCEPTION_EMPTY_FUNC +#define DOCTEST_REQUIRE_GE DOCTEST_EXCEPTION_EMPTY_FUNC +#define DOCTEST_REQUIRE_LE DOCTEST_EXCEPTION_EMPTY_FUNC +#define DOCTEST_REQUIRE_UNARY DOCTEST_EXCEPTION_EMPTY_FUNC +#define DOCTEST_REQUIRE_UNARY_FALSE DOCTEST_EXCEPTION_EMPTY_FUNC + +#endif // DOCTEST_CONFIG_NO_EXCEPTIONS_BUT_WITH_ALL_ASSERTS + +#define DOCTEST_WARN_THROWS(...) DOCTEST_EXCEPTION_EMPTY_FUNC +#define DOCTEST_CHECK_THROWS(...) DOCTEST_EXCEPTION_EMPTY_FUNC +#define DOCTEST_REQUIRE_THROWS(...) DOCTEST_EXCEPTION_EMPTY_FUNC +#define DOCTEST_WARN_THROWS_AS(expr, ...) DOCTEST_EXCEPTION_EMPTY_FUNC +#define DOCTEST_CHECK_THROWS_AS(expr, ...) DOCTEST_EXCEPTION_EMPTY_FUNC +#define DOCTEST_REQUIRE_THROWS_AS(expr, ...) DOCTEST_EXCEPTION_EMPTY_FUNC +#define DOCTEST_WARN_THROWS_WITH(expr, ...) DOCTEST_EXCEPTION_EMPTY_FUNC +#define DOCTEST_CHECK_THROWS_WITH(expr, ...) DOCTEST_EXCEPTION_EMPTY_FUNC +#define DOCTEST_REQUIRE_THROWS_WITH(expr, ...) DOCTEST_EXCEPTION_EMPTY_FUNC +#define DOCTEST_WARN_THROWS_WITH_AS(expr, with, ...) DOCTEST_EXCEPTION_EMPTY_FUNC +#define DOCTEST_CHECK_THROWS_WITH_AS(expr, with, ...) DOCTEST_EXCEPTION_EMPTY_FUNC +#define DOCTEST_REQUIRE_THROWS_WITH_AS(expr, with, ...) DOCTEST_EXCEPTION_EMPTY_FUNC +#define DOCTEST_WARN_NOTHROW(...) DOCTEST_EXCEPTION_EMPTY_FUNC +#define DOCTEST_CHECK_NOTHROW(...) DOCTEST_EXCEPTION_EMPTY_FUNC +#define DOCTEST_REQUIRE_NOTHROW(...) DOCTEST_EXCEPTION_EMPTY_FUNC + +#define DOCTEST_WARN_THROWS_MESSAGE(expr, ...) DOCTEST_EXCEPTION_EMPTY_FUNC +#define DOCTEST_CHECK_THROWS_MESSAGE(expr, ...) DOCTEST_EXCEPTION_EMPTY_FUNC +#define DOCTEST_REQUIRE_THROWS_MESSAGE(expr, ...) DOCTEST_EXCEPTION_EMPTY_FUNC +#define DOCTEST_WARN_THROWS_AS_MESSAGE(expr, ex, ...) DOCTEST_EXCEPTION_EMPTY_FUNC +#define DOCTEST_CHECK_THROWS_AS_MESSAGE(expr, ex, ...) DOCTEST_EXCEPTION_EMPTY_FUNC +#define DOCTEST_REQUIRE_THROWS_AS_MESSAGE(expr, ex, ...) DOCTEST_EXCEPTION_EMPTY_FUNC +#define DOCTEST_WARN_THROWS_WITH_MESSAGE(expr, with, ...) DOCTEST_EXCEPTION_EMPTY_FUNC +#define DOCTEST_CHECK_THROWS_WITH_MESSAGE(expr, with, ...) DOCTEST_EXCEPTION_EMPTY_FUNC +#define DOCTEST_REQUIRE_THROWS_WITH_MESSAGE(expr, with, ...) DOCTEST_EXCEPTION_EMPTY_FUNC +#define DOCTEST_WARN_THROWS_WITH_AS_MESSAGE(expr, with, ex, ...) DOCTEST_EXCEPTION_EMPTY_FUNC +#define DOCTEST_CHECK_THROWS_WITH_AS_MESSAGE(expr, with, ex, ...) DOCTEST_EXCEPTION_EMPTY_FUNC +#define DOCTEST_REQUIRE_THROWS_WITH_AS_MESSAGE(expr, with, ex, ...) DOCTEST_EXCEPTION_EMPTY_FUNC +#define DOCTEST_WARN_NOTHROW_MESSAGE(expr, ...) DOCTEST_EXCEPTION_EMPTY_FUNC +#define DOCTEST_CHECK_NOTHROW_MESSAGE(expr, ...) DOCTEST_EXCEPTION_EMPTY_FUNC +#define DOCTEST_REQUIRE_NOTHROW_MESSAGE(expr, ...) DOCTEST_EXCEPTION_EMPTY_FUNC + +#endif // DOCTEST_CONFIG_NO_EXCEPTIONS + +// clang-format off +// KEPT FOR BACKWARDS COMPATIBILITY - FORWARDING TO THE RIGHT MACROS +#define DOCTEST_FAST_WARN_EQ DOCTEST_WARN_EQ +#define DOCTEST_FAST_CHECK_EQ DOCTEST_CHECK_EQ +#define DOCTEST_FAST_REQUIRE_EQ DOCTEST_REQUIRE_EQ +#define DOCTEST_FAST_WARN_NE DOCTEST_WARN_NE +#define DOCTEST_FAST_CHECK_NE DOCTEST_CHECK_NE +#define DOCTEST_FAST_REQUIRE_NE DOCTEST_REQUIRE_NE +#define DOCTEST_FAST_WARN_GT DOCTEST_WARN_GT +#define DOCTEST_FAST_CHECK_GT DOCTEST_CHECK_GT +#define DOCTEST_FAST_REQUIRE_GT DOCTEST_REQUIRE_GT +#define DOCTEST_FAST_WARN_LT DOCTEST_WARN_LT +#define DOCTEST_FAST_CHECK_LT DOCTEST_CHECK_LT +#define DOCTEST_FAST_REQUIRE_LT DOCTEST_REQUIRE_LT +#define DOCTEST_FAST_WARN_GE DOCTEST_WARN_GE +#define DOCTEST_FAST_CHECK_GE DOCTEST_CHECK_GE +#define DOCTEST_FAST_REQUIRE_GE DOCTEST_REQUIRE_GE +#define DOCTEST_FAST_WARN_LE DOCTEST_WARN_LE +#define DOCTEST_FAST_CHECK_LE DOCTEST_CHECK_LE +#define DOCTEST_FAST_REQUIRE_LE DOCTEST_REQUIRE_LE + +#define DOCTEST_FAST_WARN_UNARY DOCTEST_WARN_UNARY +#define DOCTEST_FAST_CHECK_UNARY DOCTEST_CHECK_UNARY +#define DOCTEST_FAST_REQUIRE_UNARY DOCTEST_REQUIRE_UNARY +#define DOCTEST_FAST_WARN_UNARY_FALSE DOCTEST_WARN_UNARY_FALSE +#define DOCTEST_FAST_CHECK_UNARY_FALSE DOCTEST_CHECK_UNARY_FALSE +#define DOCTEST_FAST_REQUIRE_UNARY_FALSE DOCTEST_REQUIRE_UNARY_FALSE + +#define DOCTEST_TEST_CASE_TEMPLATE_INSTANTIATE(id, ...) DOCTEST_TEST_CASE_TEMPLATE_INVOKE(id,__VA_ARGS__) +// clang-format on + +// BDD style macros +// clang-format off +#define DOCTEST_SCENARIO(name) DOCTEST_TEST_CASE(" Scenario: " name) +#define DOCTEST_SCENARIO_CLASS(name) DOCTEST_TEST_CASE_CLASS(" Scenario: " name) +#define DOCTEST_SCENARIO_TEMPLATE(name, T, ...) DOCTEST_TEST_CASE_TEMPLATE(" Scenario: " name, T, __VA_ARGS__) +#define DOCTEST_SCENARIO_TEMPLATE_DEFINE(name, T, id) DOCTEST_TEST_CASE_TEMPLATE_DEFINE(" Scenario: " name, T, id) + +#define DOCTEST_GIVEN(name) DOCTEST_SUBCASE(" Given: " name) +#define DOCTEST_WHEN(name) DOCTEST_SUBCASE(" When: " name) +#define DOCTEST_AND_WHEN(name) DOCTEST_SUBCASE("And when: " name) +#define DOCTEST_THEN(name) DOCTEST_SUBCASE(" Then: " name) +#define DOCTEST_AND_THEN(name) DOCTEST_SUBCASE(" And: " name) +// clang-format on + +// == SHORT VERSIONS OF THE MACROS +#ifndef DOCTEST_CONFIG_NO_SHORT_MACRO_NAMES + +#define TEST_CASE(name) DOCTEST_TEST_CASE(name) +#define TEST_CASE_CLASS(name) DOCTEST_TEST_CASE_CLASS(name) +#define TEST_CASE_FIXTURE(x, name) DOCTEST_TEST_CASE_FIXTURE(x, name) +#define TYPE_TO_STRING_AS(str, ...) DOCTEST_TYPE_TO_STRING_AS(str, __VA_ARGS__) +#define TYPE_TO_STRING(...) DOCTEST_TYPE_TO_STRING(__VA_ARGS__) +#define TEST_CASE_TEMPLATE(name, T, ...) DOCTEST_TEST_CASE_TEMPLATE(name, T, __VA_ARGS__) +#define TEST_CASE_TEMPLATE_DEFINE(name, T, id) DOCTEST_TEST_CASE_TEMPLATE_DEFINE(name, T, id) +#define TEST_CASE_TEMPLATE_INVOKE(id, ...) DOCTEST_TEST_CASE_TEMPLATE_INVOKE(id, __VA_ARGS__) +#define TEST_CASE_TEMPLATE_APPLY(id, ...) DOCTEST_TEST_CASE_TEMPLATE_APPLY(id, __VA_ARGS__) +#define SUBCASE(name) DOCTEST_SUBCASE(name) +#define TEST_SUITE(decorators) DOCTEST_TEST_SUITE(decorators) +#define TEST_SUITE_BEGIN(name) DOCTEST_TEST_SUITE_BEGIN(name) +#define TEST_SUITE_END DOCTEST_TEST_SUITE_END +#define REGISTER_EXCEPTION_TRANSLATOR(signature) DOCTEST_REGISTER_EXCEPTION_TRANSLATOR(signature) +#define REGISTER_REPORTER(name, priority, reporter) DOCTEST_REGISTER_REPORTER(name, priority, reporter) +#define REGISTER_LISTENER(name, priority, reporter) DOCTEST_REGISTER_LISTENER(name, priority, reporter) +#define INFO(...) DOCTEST_INFO(__VA_ARGS__) +#define CAPTURE(x) DOCTEST_CAPTURE(x) +#define ADD_MESSAGE_AT(file, line, ...) DOCTEST_ADD_MESSAGE_AT(file, line, __VA_ARGS__) +#define ADD_FAIL_CHECK_AT(file, line, ...) DOCTEST_ADD_FAIL_CHECK_AT(file, line, __VA_ARGS__) +#define ADD_FAIL_AT(file, line, ...) DOCTEST_ADD_FAIL_AT(file, line, __VA_ARGS__) +#define MESSAGE(...) DOCTEST_MESSAGE(__VA_ARGS__) +#define FAIL_CHECK(...) DOCTEST_FAIL_CHECK(__VA_ARGS__) +#define FAIL(...) DOCTEST_FAIL(__VA_ARGS__) +#define TO_LVALUE(...) DOCTEST_TO_LVALUE(__VA_ARGS__) + +#define WARN(...) DOCTEST_WARN(__VA_ARGS__) +#define WARN_FALSE(...) DOCTEST_WARN_FALSE(__VA_ARGS__) +#define WARN_THROWS(...) DOCTEST_WARN_THROWS(__VA_ARGS__) +#define WARN_THROWS_AS(expr, ...) DOCTEST_WARN_THROWS_AS(expr, __VA_ARGS__) +#define WARN_THROWS_WITH(expr, ...) DOCTEST_WARN_THROWS_WITH(expr, __VA_ARGS__) +#define WARN_THROWS_WITH_AS(expr, with, ...) DOCTEST_WARN_THROWS_WITH_AS(expr, with, __VA_ARGS__) +#define WARN_NOTHROW(...) DOCTEST_WARN_NOTHROW(__VA_ARGS__) +#define CHECK(...) DOCTEST_CHECK(__VA_ARGS__) +#define CHECK_FALSE(...) DOCTEST_CHECK_FALSE(__VA_ARGS__) +#define CHECK_THROWS(...) DOCTEST_CHECK_THROWS(__VA_ARGS__) +#define CHECK_THROWS_AS(expr, ...) DOCTEST_CHECK_THROWS_AS(expr, __VA_ARGS__) +#define CHECK_THROWS_WITH(expr, ...) DOCTEST_CHECK_THROWS_WITH(expr, __VA_ARGS__) +#define CHECK_THROWS_WITH_AS(expr, with, ...) DOCTEST_CHECK_THROWS_WITH_AS(expr, with, __VA_ARGS__) +#define CHECK_NOTHROW(...) DOCTEST_CHECK_NOTHROW(__VA_ARGS__) +#define REQUIRE(...) DOCTEST_REQUIRE(__VA_ARGS__) +#define REQUIRE_FALSE(...) DOCTEST_REQUIRE_FALSE(__VA_ARGS__) +#define REQUIRE_THROWS(...) DOCTEST_REQUIRE_THROWS(__VA_ARGS__) +#define REQUIRE_THROWS_AS(expr, ...) DOCTEST_REQUIRE_THROWS_AS(expr, __VA_ARGS__) +#define REQUIRE_THROWS_WITH(expr, ...) DOCTEST_REQUIRE_THROWS_WITH(expr, __VA_ARGS__) +#define REQUIRE_THROWS_WITH_AS(expr, with, ...) DOCTEST_REQUIRE_THROWS_WITH_AS(expr, with, __VA_ARGS__) +#define REQUIRE_NOTHROW(...) DOCTEST_REQUIRE_NOTHROW(__VA_ARGS__) + +#define WARN_MESSAGE(cond, ...) DOCTEST_WARN_MESSAGE(cond, __VA_ARGS__) +#define WARN_FALSE_MESSAGE(cond, ...) DOCTEST_WARN_FALSE_MESSAGE(cond, __VA_ARGS__) +#define WARN_THROWS_MESSAGE(expr, ...) DOCTEST_WARN_THROWS_MESSAGE(expr, __VA_ARGS__) +#define WARN_THROWS_AS_MESSAGE(expr, ex, ...) DOCTEST_WARN_THROWS_AS_MESSAGE(expr, ex, __VA_ARGS__) +#define WARN_THROWS_WITH_MESSAGE(expr, with, ...) DOCTEST_WARN_THROWS_WITH_MESSAGE(expr, with, __VA_ARGS__) +#define WARN_THROWS_WITH_AS_MESSAGE(expr, with, ex, ...) DOCTEST_WARN_THROWS_WITH_AS_MESSAGE(expr, with, ex, __VA_ARGS__) +#define WARN_NOTHROW_MESSAGE(expr, ...) DOCTEST_WARN_NOTHROW_MESSAGE(expr, __VA_ARGS__) +#define CHECK_MESSAGE(cond, ...) DOCTEST_CHECK_MESSAGE(cond, __VA_ARGS__) +#define CHECK_FALSE_MESSAGE(cond, ...) DOCTEST_CHECK_FALSE_MESSAGE(cond, __VA_ARGS__) +#define CHECK_THROWS_MESSAGE(expr, ...) DOCTEST_CHECK_THROWS_MESSAGE(expr, __VA_ARGS__) +#define CHECK_THROWS_AS_MESSAGE(expr, ex, ...) DOCTEST_CHECK_THROWS_AS_MESSAGE(expr, ex, __VA_ARGS__) +#define CHECK_THROWS_WITH_MESSAGE(expr, with, ...) DOCTEST_CHECK_THROWS_WITH_MESSAGE(expr, with, __VA_ARGS__) +#define CHECK_THROWS_WITH_AS_MESSAGE(expr, with, ex, ...) DOCTEST_CHECK_THROWS_WITH_AS_MESSAGE(expr, with, ex, __VA_ARGS__) +#define CHECK_NOTHROW_MESSAGE(expr, ...) DOCTEST_CHECK_NOTHROW_MESSAGE(expr, __VA_ARGS__) +#define REQUIRE_MESSAGE(cond, ...) DOCTEST_REQUIRE_MESSAGE(cond, __VA_ARGS__) +#define REQUIRE_FALSE_MESSAGE(cond, ...) DOCTEST_REQUIRE_FALSE_MESSAGE(cond, __VA_ARGS__) +#define REQUIRE_THROWS_MESSAGE(expr, ...) DOCTEST_REQUIRE_THROWS_MESSAGE(expr, __VA_ARGS__) +#define REQUIRE_THROWS_AS_MESSAGE(expr, ex, ...) DOCTEST_REQUIRE_THROWS_AS_MESSAGE(expr, ex, __VA_ARGS__) +#define REQUIRE_THROWS_WITH_MESSAGE(expr, with, ...) DOCTEST_REQUIRE_THROWS_WITH_MESSAGE(expr, with, __VA_ARGS__) +#define REQUIRE_THROWS_WITH_AS_MESSAGE(expr, with, ex, ...) DOCTEST_REQUIRE_THROWS_WITH_AS_MESSAGE(expr, with, ex, __VA_ARGS__) +#define REQUIRE_NOTHROW_MESSAGE(expr, ...) DOCTEST_REQUIRE_NOTHROW_MESSAGE(expr, __VA_ARGS__) + +#define SCENARIO(name) DOCTEST_SCENARIO(name) +#define SCENARIO_CLASS(name) DOCTEST_SCENARIO_CLASS(name) +#define SCENARIO_TEMPLATE(name, T, ...) DOCTEST_SCENARIO_TEMPLATE(name, T, __VA_ARGS__) +#define SCENARIO_TEMPLATE_DEFINE(name, T, id) DOCTEST_SCENARIO_TEMPLATE_DEFINE(name, T, id) +#define GIVEN(name) DOCTEST_GIVEN(name) +#define WHEN(name) DOCTEST_WHEN(name) +#define AND_WHEN(name) DOCTEST_AND_WHEN(name) +#define THEN(name) DOCTEST_THEN(name) +#define AND_THEN(name) DOCTEST_AND_THEN(name) + +#define WARN_EQ(...) DOCTEST_WARN_EQ(__VA_ARGS__) +#define CHECK_EQ(...) DOCTEST_CHECK_EQ(__VA_ARGS__) +#define REQUIRE_EQ(...) DOCTEST_REQUIRE_EQ(__VA_ARGS__) +#define WARN_NE(...) DOCTEST_WARN_NE(__VA_ARGS__) +#define CHECK_NE(...) DOCTEST_CHECK_NE(__VA_ARGS__) +#define REQUIRE_NE(...) DOCTEST_REQUIRE_NE(__VA_ARGS__) +#define WARN_GT(...) DOCTEST_WARN_GT(__VA_ARGS__) +#define CHECK_GT(...) DOCTEST_CHECK_GT(__VA_ARGS__) +#define REQUIRE_GT(...) DOCTEST_REQUIRE_GT(__VA_ARGS__) +#define WARN_LT(...) DOCTEST_WARN_LT(__VA_ARGS__) +#define CHECK_LT(...) DOCTEST_CHECK_LT(__VA_ARGS__) +#define REQUIRE_LT(...) DOCTEST_REQUIRE_LT(__VA_ARGS__) +#define WARN_GE(...) DOCTEST_WARN_GE(__VA_ARGS__) +#define CHECK_GE(...) DOCTEST_CHECK_GE(__VA_ARGS__) +#define REQUIRE_GE(...) DOCTEST_REQUIRE_GE(__VA_ARGS__) +#define WARN_LE(...) DOCTEST_WARN_LE(__VA_ARGS__) +#define CHECK_LE(...) DOCTEST_CHECK_LE(__VA_ARGS__) +#define REQUIRE_LE(...) DOCTEST_REQUIRE_LE(__VA_ARGS__) +#define WARN_UNARY(...) DOCTEST_WARN_UNARY(__VA_ARGS__) +#define CHECK_UNARY(...) DOCTEST_CHECK_UNARY(__VA_ARGS__) +#define REQUIRE_UNARY(...) DOCTEST_REQUIRE_UNARY(__VA_ARGS__) +#define WARN_UNARY_FALSE(...) DOCTEST_WARN_UNARY_FALSE(__VA_ARGS__) +#define CHECK_UNARY_FALSE(...) DOCTEST_CHECK_UNARY_FALSE(__VA_ARGS__) +#define REQUIRE_UNARY_FALSE(...) DOCTEST_REQUIRE_UNARY_FALSE(__VA_ARGS__) + +// KEPT FOR BACKWARDS COMPATIBILITY +#define FAST_WARN_EQ(...) DOCTEST_FAST_WARN_EQ(__VA_ARGS__) +#define FAST_CHECK_EQ(...) DOCTEST_FAST_CHECK_EQ(__VA_ARGS__) +#define FAST_REQUIRE_EQ(...) DOCTEST_FAST_REQUIRE_EQ(__VA_ARGS__) +#define FAST_WARN_NE(...) DOCTEST_FAST_WARN_NE(__VA_ARGS__) +#define FAST_CHECK_NE(...) DOCTEST_FAST_CHECK_NE(__VA_ARGS__) +#define FAST_REQUIRE_NE(...) DOCTEST_FAST_REQUIRE_NE(__VA_ARGS__) +#define FAST_WARN_GT(...) DOCTEST_FAST_WARN_GT(__VA_ARGS__) +#define FAST_CHECK_GT(...) DOCTEST_FAST_CHECK_GT(__VA_ARGS__) +#define FAST_REQUIRE_GT(...) DOCTEST_FAST_REQUIRE_GT(__VA_ARGS__) +#define FAST_WARN_LT(...) DOCTEST_FAST_WARN_LT(__VA_ARGS__) +#define FAST_CHECK_LT(...) DOCTEST_FAST_CHECK_LT(__VA_ARGS__) +#define FAST_REQUIRE_LT(...) DOCTEST_FAST_REQUIRE_LT(__VA_ARGS__) +#define FAST_WARN_GE(...) DOCTEST_FAST_WARN_GE(__VA_ARGS__) +#define FAST_CHECK_GE(...) DOCTEST_FAST_CHECK_GE(__VA_ARGS__) +#define FAST_REQUIRE_GE(...) DOCTEST_FAST_REQUIRE_GE(__VA_ARGS__) +#define FAST_WARN_LE(...) DOCTEST_FAST_WARN_LE(__VA_ARGS__) +#define FAST_CHECK_LE(...) DOCTEST_FAST_CHECK_LE(__VA_ARGS__) +#define FAST_REQUIRE_LE(...) DOCTEST_FAST_REQUIRE_LE(__VA_ARGS__) + +#define FAST_WARN_UNARY(...) DOCTEST_FAST_WARN_UNARY(__VA_ARGS__) +#define FAST_CHECK_UNARY(...) DOCTEST_FAST_CHECK_UNARY(__VA_ARGS__) +#define FAST_REQUIRE_UNARY(...) DOCTEST_FAST_REQUIRE_UNARY(__VA_ARGS__) +#define FAST_WARN_UNARY_FALSE(...) DOCTEST_FAST_WARN_UNARY_FALSE(__VA_ARGS__) +#define FAST_CHECK_UNARY_FALSE(...) DOCTEST_FAST_CHECK_UNARY_FALSE(__VA_ARGS__) +#define FAST_REQUIRE_UNARY_FALSE(...) DOCTEST_FAST_REQUIRE_UNARY_FALSE(__VA_ARGS__) + +#define TEST_CASE_TEMPLATE_INSTANTIATE(id, ...) DOCTEST_TEST_CASE_TEMPLATE_INSTANTIATE(id, __VA_ARGS__) + +#endif // DOCTEST_CONFIG_NO_SHORT_MACRO_NAMES + +#ifndef DOCTEST_CONFIG_DISABLE + +// this is here to clear the 'current test suite' for the current translation unit - at the top +DOCTEST_TEST_SUITE_END(); + +#endif // DOCTEST_CONFIG_DISABLE + +DOCTEST_CLANG_SUPPRESS_WARNING_POP +DOCTEST_MSVC_SUPPRESS_WARNING_POP +DOCTEST_GCC_SUPPRESS_WARNING_POP + +DOCTEST_SUPPRESS_COMMON_WARNINGS_POP + +#endif // DOCTEST_LIBRARY_INCLUDED + +#ifndef DOCTEST_SINGLE_HEADER +#define DOCTEST_SINGLE_HEADER +#endif // DOCTEST_SINGLE_HEADER + +#if defined(DOCTEST_CONFIG_IMPLEMENT) || !defined(DOCTEST_SINGLE_HEADER) + +#ifndef DOCTEST_SINGLE_HEADER +#include "doctest_fwd.h" +#endif // DOCTEST_SINGLE_HEADER + +DOCTEST_CLANG_SUPPRESS_WARNING_WITH_PUSH("-Wunused-macros") + +#ifndef DOCTEST_LIBRARY_IMPLEMENTATION +#define DOCTEST_LIBRARY_IMPLEMENTATION + +DOCTEST_CLANG_SUPPRESS_WARNING_POP + +DOCTEST_SUPPRESS_COMMON_WARNINGS_PUSH + +DOCTEST_CLANG_SUPPRESS_WARNING_PUSH +DOCTEST_CLANG_SUPPRESS_WARNING("-Wglobal-constructors") +DOCTEST_CLANG_SUPPRESS_WARNING("-Wexit-time-destructors") +DOCTEST_CLANG_SUPPRESS_WARNING("-Wsign-conversion") +DOCTEST_CLANG_SUPPRESS_WARNING("-Wshorten-64-to-32") +DOCTEST_CLANG_SUPPRESS_WARNING("-Wmissing-variable-declarations") +DOCTEST_CLANG_SUPPRESS_WARNING("-Wswitch") +DOCTEST_CLANG_SUPPRESS_WARNING("-Wswitch-enum") +DOCTEST_CLANG_SUPPRESS_WARNING("-Wcovered-switch-default") +DOCTEST_CLANG_SUPPRESS_WARNING("-Wmissing-noreturn") +DOCTEST_CLANG_SUPPRESS_WARNING("-Wdisabled-macro-expansion") +DOCTEST_CLANG_SUPPRESS_WARNING("-Wmissing-braces") +DOCTEST_CLANG_SUPPRESS_WARNING("-Wmissing-field-initializers") +DOCTEST_CLANG_SUPPRESS_WARNING("-Wunused-member-function") +DOCTEST_CLANG_SUPPRESS_WARNING("-Wnonportable-system-include-path") + +DOCTEST_GCC_SUPPRESS_WARNING_PUSH +DOCTEST_GCC_SUPPRESS_WARNING("-Wconversion") +DOCTEST_GCC_SUPPRESS_WARNING("-Wsign-conversion") +DOCTEST_GCC_SUPPRESS_WARNING("-Wmissing-field-initializers") +DOCTEST_GCC_SUPPRESS_WARNING("-Wmissing-braces") +DOCTEST_GCC_SUPPRESS_WARNING("-Wswitch") +DOCTEST_GCC_SUPPRESS_WARNING("-Wswitch-enum") +DOCTEST_GCC_SUPPRESS_WARNING("-Wswitch-default") +DOCTEST_GCC_SUPPRESS_WARNING("-Wunsafe-loop-optimizations") +DOCTEST_GCC_SUPPRESS_WARNING("-Wold-style-cast") +DOCTEST_GCC_SUPPRESS_WARNING("-Wunused-function") +DOCTEST_GCC_SUPPRESS_WARNING("-Wmultiple-inheritance") +DOCTEST_GCC_SUPPRESS_WARNING("-Wsuggest-attribute") + +DOCTEST_MSVC_SUPPRESS_WARNING_PUSH +DOCTEST_MSVC_SUPPRESS_WARNING(4267) // 'var' : conversion from 'x' to 'y', possible loss of data +DOCTEST_MSVC_SUPPRESS_WARNING(4530) // C++ exception handler used, but unwind semantics not enabled +DOCTEST_MSVC_SUPPRESS_WARNING(4577) // 'noexcept' used with no exception handling mode specified +DOCTEST_MSVC_SUPPRESS_WARNING(4774) // format string expected in argument is not a string literal +DOCTEST_MSVC_SUPPRESS_WARNING(4365) // conversion from 'int' to 'unsigned', signed/unsigned mismatch +DOCTEST_MSVC_SUPPRESS_WARNING(5039) // pointer to potentially throwing function passed to extern C +DOCTEST_MSVC_SUPPRESS_WARNING(4800) // forcing value to bool 'true' or 'false' (performance warning) +DOCTEST_MSVC_SUPPRESS_WARNING(5245) // unreferenced function with internal linkage has been removed + +DOCTEST_MAKE_STD_HEADERS_CLEAN_FROM_WARNINGS_ON_WALL_BEGIN + +// required includes - will go only in one translation unit! +#include +#include +#include +// borland (Embarcadero) compiler requires math.h and not cmath - https://github.com/doctest/doctest/pull/37 +#ifdef __BORLANDC__ +#include +#endif // __BORLANDC__ +#include +#include +#include +#include +#include +#include +#include +#include +#ifndef DOCTEST_CONFIG_NO_INCLUDE_IOSTREAM +#include +#endif // DOCTEST_CONFIG_NO_INCLUDE_IOSTREAM +#include +#include +#include +#ifndef DOCTEST_CONFIG_NO_MULTITHREADING +#include +#include +#define DOCTEST_DECLARE_MUTEX(name) std::mutex name; +#define DOCTEST_DECLARE_STATIC_MUTEX(name) static DOCTEST_DECLARE_MUTEX(name) +#define DOCTEST_LOCK_MUTEX(name) std::lock_guard DOCTEST_ANONYMOUS(DOCTEST_ANON_LOCK_)(name); +#else // DOCTEST_CONFIG_NO_MULTITHREADING +#define DOCTEST_DECLARE_MUTEX(name) +#define DOCTEST_DECLARE_STATIC_MUTEX(name) +#define DOCTEST_LOCK_MUTEX(name) +#endif // DOCTEST_CONFIG_NO_MULTITHREADING +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef DOCTEST_PLATFORM_MAC +#include +#include +#include +#endif // DOCTEST_PLATFORM_MAC + +#ifdef DOCTEST_PLATFORM_WINDOWS + +// defines for a leaner windows.h +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#define DOCTEST_UNDEF_WIN32_LEAN_AND_MEAN +#endif // WIN32_LEAN_AND_MEAN +#ifndef NOMINMAX +#define NOMINMAX +#define DOCTEST_UNDEF_NOMINMAX +#endif // NOMINMAX + +// not sure what AfxWin.h is for - here I do what Catch does +#ifdef __AFXDLL +#include +#else +#include +#endif +#include + +#else // DOCTEST_PLATFORM_WINDOWS + +#include +#include + +#endif // DOCTEST_PLATFORM_WINDOWS + +// this is a fix for https://github.com/doctest/doctest/issues/348 +// https://mail.gnome.org/archives/xml/2012-January/msg00000.html +#if !defined(HAVE_UNISTD_H) && !defined(STDOUT_FILENO) +#define STDOUT_FILENO fileno(stdout) +#endif // HAVE_UNISTD_H + +DOCTEST_MAKE_STD_HEADERS_CLEAN_FROM_WARNINGS_ON_WALL_END + +// counts the number of elements in a C array +#define DOCTEST_COUNTOF(x) (sizeof(x) / sizeof(x[0])) + +#ifdef DOCTEST_CONFIG_DISABLE +#define DOCTEST_BRANCH_ON_DISABLED(if_disabled, if_not_disabled) if_disabled +#else // DOCTEST_CONFIG_DISABLE +#define DOCTEST_BRANCH_ON_DISABLED(if_disabled, if_not_disabled) if_not_disabled +#endif // DOCTEST_CONFIG_DISABLE + +#ifndef DOCTEST_CONFIG_OPTIONS_PREFIX +#define DOCTEST_CONFIG_OPTIONS_PREFIX "dt-" +#endif + +#ifndef DOCTEST_THREAD_LOCAL +#if defined(DOCTEST_CONFIG_NO_MULTITHREADING) || DOCTEST_MSVC && (DOCTEST_MSVC < DOCTEST_COMPILER(19, 0, 0)) +#define DOCTEST_THREAD_LOCAL +#else // DOCTEST_MSVC +#define DOCTEST_THREAD_LOCAL thread_local +#endif // DOCTEST_MSVC +#endif // DOCTEST_THREAD_LOCAL + +#ifndef DOCTEST_MULTI_LANE_ATOMICS_THREAD_LANES +#define DOCTEST_MULTI_LANE_ATOMICS_THREAD_LANES 32 +#endif + +#ifndef DOCTEST_MULTI_LANE_ATOMICS_CACHE_LINE_SIZE +#define DOCTEST_MULTI_LANE_ATOMICS_CACHE_LINE_SIZE 64 +#endif + +#ifdef DOCTEST_CONFIG_NO_UNPREFIXED_OPTIONS +#define DOCTEST_OPTIONS_PREFIX_DISPLAY DOCTEST_CONFIG_OPTIONS_PREFIX +#else +#define DOCTEST_OPTIONS_PREFIX_DISPLAY "" +#endif + +#if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP) +#define DOCTEST_CONFIG_NO_MULTI_LANE_ATOMICS +#endif + +#ifndef DOCTEST_CDECL +#define DOCTEST_CDECL __cdecl +#endif + +namespace doctest { + +bool is_running_in_test = false; + +namespace { + using namespace detail; + + template + DOCTEST_NORETURN void throw_exception(Ex const& e) { +#ifndef DOCTEST_CONFIG_NO_EXCEPTIONS + throw e; +#else // DOCTEST_CONFIG_NO_EXCEPTIONS +#ifdef DOCTEST_CONFIG_HANDLE_EXCEPTION + DOCTEST_CONFIG_HANDLE_EXCEPTION(e); +#else // DOCTEST_CONFIG_HANDLE_EXCEPTION +#ifndef DOCTEST_CONFIG_NO_INCLUDE_IOSTREAM + std::cerr << "doctest will terminate because it needed to throw an exception.\n" + << "The message was: " << e.what() << '\n'; +#endif // DOCTEST_CONFIG_NO_INCLUDE_IOSTREAM +#endif // DOCTEST_CONFIG_HANDLE_EXCEPTION + std::terminate(); +#endif // DOCTEST_CONFIG_NO_EXCEPTIONS + } + +#ifndef DOCTEST_INTERNAL_ERROR +#define DOCTEST_INTERNAL_ERROR(msg) \ + throw_exception(std::logic_error( \ + __FILE__ ":" DOCTEST_TOSTR(__LINE__) ": Internal doctest error: " msg)) +#endif // DOCTEST_INTERNAL_ERROR + + // case insensitive strcmp + int stricmp(const char* a, const char* b) { + for(;; a++, b++) { + const int d = tolower(*a) - tolower(*b); + if(d != 0 || !*a) + return d; + } + } + + struct Endianness + { + enum Arch + { + Big, + Little + }; + + static Arch which() { + int x = 1; + // casting any data pointer to char* is allowed + auto ptr = reinterpret_cast(&x); + if(*ptr) + return Little; + return Big; + } + }; +} // namespace + +namespace detail { + DOCTEST_THREAD_LOCAL class + { + std::vector stack; + std::stringstream ss; + + public: + std::ostream* push() { + stack.push_back(ss.tellp()); + return &ss; + } + + String pop() { + if (stack.empty()) + DOCTEST_INTERNAL_ERROR("TLSS was empty when trying to pop!"); + + std::streampos pos = stack.back(); + stack.pop_back(); + unsigned sz = static_cast(ss.tellp() - pos); + ss.rdbuf()->pubseekpos(pos, std::ios::in | std::ios::out); + return String(ss, sz); + } + } g_oss; + + std::ostream* tlssPush() { + return g_oss.push(); + } + + String tlssPop() { + return g_oss.pop(); + } + +#ifndef DOCTEST_CONFIG_DISABLE + +namespace timer_large_integer +{ + +#if defined(DOCTEST_PLATFORM_WINDOWS) + using type = ULONGLONG; +#else // DOCTEST_PLATFORM_WINDOWS + using type = std::uint64_t; +#endif // DOCTEST_PLATFORM_WINDOWS +} + +using ticks_t = timer_large_integer::type; + +#ifdef DOCTEST_CONFIG_GETCURRENTTICKS + ticks_t getCurrentTicks() { return DOCTEST_CONFIG_GETCURRENTTICKS(); } +#elif defined(DOCTEST_PLATFORM_WINDOWS) + ticks_t getCurrentTicks() { + static LARGE_INTEGER hz = { {0} }, hzo = { {0} }; + if(!hz.QuadPart) { + QueryPerformanceFrequency(&hz); + QueryPerformanceCounter(&hzo); + } + LARGE_INTEGER t; + QueryPerformanceCounter(&t); + return ((t.QuadPart - hzo.QuadPart) * LONGLONG(1000000)) / hz.QuadPart; + } +#else // DOCTEST_PLATFORM_WINDOWS + ticks_t getCurrentTicks() { + timeval t; + gettimeofday(&t, nullptr); + return static_cast(t.tv_sec) * 1000000 + static_cast(t.tv_usec); + } +#endif // DOCTEST_PLATFORM_WINDOWS + + struct Timer + { + void start() { m_ticks = getCurrentTicks(); } + unsigned int getElapsedMicroseconds() const { + return static_cast(getCurrentTicks() - m_ticks); + } + //unsigned int getElapsedMilliseconds() const { + // return static_cast(getElapsedMicroseconds() / 1000); + //} + double getElapsedSeconds() const { return static_cast(getCurrentTicks() - m_ticks) / 1000000.0; } + + private: + ticks_t m_ticks = 0; + }; + +#ifdef DOCTEST_CONFIG_NO_MULTITHREADING + template + using Atomic = T; +#else // DOCTEST_CONFIG_NO_MULTITHREADING + template + using Atomic = std::atomic; +#endif // DOCTEST_CONFIG_NO_MULTITHREADING + +#if defined(DOCTEST_CONFIG_NO_MULTI_LANE_ATOMICS) || defined(DOCTEST_CONFIG_NO_MULTITHREADING) + template + using MultiLaneAtomic = Atomic; +#else // DOCTEST_CONFIG_NO_MULTI_LANE_ATOMICS + // Provides a multilane implementation of an atomic variable that supports add, sub, load, + // store. Instead of using a single atomic variable, this splits up into multiple ones, + // each sitting on a separate cache line. The goal is to provide a speedup when most + // operations are modifying. It achieves this with two properties: + // + // * Multiple atomics are used, so chance of congestion from the same atomic is reduced. + // * Each atomic sits on a separate cache line, so false sharing is reduced. + // + // The disadvantage is that there is a small overhead due to the use of TLS, and load/store + // is slower because all atomics have to be accessed. + template + class MultiLaneAtomic + { + struct CacheLineAlignedAtomic + { + Atomic atomic{}; + char padding[DOCTEST_MULTI_LANE_ATOMICS_CACHE_LINE_SIZE - sizeof(Atomic)]; + }; + CacheLineAlignedAtomic m_atomics[DOCTEST_MULTI_LANE_ATOMICS_THREAD_LANES]; + + static_assert(sizeof(CacheLineAlignedAtomic) == DOCTEST_MULTI_LANE_ATOMICS_CACHE_LINE_SIZE, + "guarantee one atomic takes exactly one cache line"); + + public: + T operator++() DOCTEST_NOEXCEPT { return fetch_add(1) + 1; } + + T operator++(int) DOCTEST_NOEXCEPT { return fetch_add(1); } + + T fetch_add(T arg, std::memory_order order = std::memory_order_seq_cst) DOCTEST_NOEXCEPT { + return myAtomic().fetch_add(arg, order); + } + + T fetch_sub(T arg, std::memory_order order = std::memory_order_seq_cst) DOCTEST_NOEXCEPT { + return myAtomic().fetch_sub(arg, order); + } + + operator T() const DOCTEST_NOEXCEPT { return load(); } + + T load(std::memory_order order = std::memory_order_seq_cst) const DOCTEST_NOEXCEPT { + auto result = T(); + for(auto const& c : m_atomics) { + result += c.atomic.load(order); + } + return result; + } + + T operator=(T desired) DOCTEST_NOEXCEPT { // lgtm [cpp/assignment-does-not-return-this] + store(desired); + return desired; + } + + void store(T desired, std::memory_order order = std::memory_order_seq_cst) DOCTEST_NOEXCEPT { + // first value becomes desired", all others become 0. + for(auto& c : m_atomics) { + c.atomic.store(desired, order); + desired = {}; + } + } + + private: + // Each thread has a different atomic that it operates on. If more than NumLanes threads + // use this, some will use the same atomic. So performance will degrade a bit, but still + // everything will work. + // + // The logic here is a bit tricky. The call should be as fast as possible, so that there + // is minimal to no overhead in determining the correct atomic for the current thread. + // + // 1. A global static counter laneCounter counts continuously up. + // 2. Each successive thread will use modulo operation of that counter so it gets an atomic + // assigned in a round-robin fashion. + // 3. This tlsLaneIdx is stored in the thread local data, so it is directly available with + // little overhead. + Atomic& myAtomic() DOCTEST_NOEXCEPT { + static Atomic laneCounter; + DOCTEST_THREAD_LOCAL size_t tlsLaneIdx = + laneCounter++ % DOCTEST_MULTI_LANE_ATOMICS_THREAD_LANES; + + return m_atomics[tlsLaneIdx].atomic; + } + }; +#endif // DOCTEST_CONFIG_NO_MULTI_LANE_ATOMICS + + // this holds both parameters from the command line and runtime data for tests + struct ContextState : ContextOptions, TestRunStats, CurrentTestCaseStats + { + MultiLaneAtomic numAssertsCurrentTest_atomic; + MultiLaneAtomic numAssertsFailedCurrentTest_atomic; + + std::vector> filters = decltype(filters)(9); // 9 different filters + + std::vector reporters_currently_used; + + assert_handler ah = nullptr; + + Timer timer; + + std::vector stringifiedContexts; // logging from INFO() due to an exception + + // stuff for subcases + bool reachedLeaf; + std::vector subcaseStack; + std::vector nextSubcaseStack; + std::unordered_set fullyTraversedSubcases; + size_t currentSubcaseDepth; + Atomic shouldLogCurrentException; + + void resetRunData() { + numTestCases = 0; + numTestCasesPassingFilters = 0; + numTestSuitesPassingFilters = 0; + numTestCasesFailed = 0; + numAsserts = 0; + numAssertsFailed = 0; + numAssertsCurrentTest = 0; + numAssertsFailedCurrentTest = 0; + } + + void finalizeTestCaseData() { + seconds = timer.getElapsedSeconds(); + + // update the non-atomic counters + numAsserts += numAssertsCurrentTest_atomic; + numAssertsFailed += numAssertsFailedCurrentTest_atomic; + numAssertsCurrentTest = numAssertsCurrentTest_atomic; + numAssertsFailedCurrentTest = numAssertsFailedCurrentTest_atomic; + + if(numAssertsFailedCurrentTest) + failure_flags |= TestCaseFailureReason::AssertFailure; + + if(Approx(currentTest->m_timeout).epsilon(DBL_EPSILON) != 0 && + Approx(seconds).epsilon(DBL_EPSILON) > currentTest->m_timeout) + failure_flags |= TestCaseFailureReason::Timeout; + + if(currentTest->m_should_fail) { + if(failure_flags) { + failure_flags |= TestCaseFailureReason::ShouldHaveFailedAndDid; + } else { + failure_flags |= TestCaseFailureReason::ShouldHaveFailedButDidnt; + } + } else if(failure_flags && currentTest->m_may_fail) { + failure_flags |= TestCaseFailureReason::CouldHaveFailedAndDid; + } else if(currentTest->m_expected_failures > 0) { + if(numAssertsFailedCurrentTest == currentTest->m_expected_failures) { + failure_flags |= TestCaseFailureReason::FailedExactlyNumTimes; + } else { + failure_flags |= TestCaseFailureReason::DidntFailExactlyNumTimes; + } + } + + bool ok_to_fail = (TestCaseFailureReason::ShouldHaveFailedAndDid & failure_flags) || + (TestCaseFailureReason::CouldHaveFailedAndDid & failure_flags) || + (TestCaseFailureReason::FailedExactlyNumTimes & failure_flags); + + // if any subcase has failed - the whole test case has failed + testCaseSuccess = !(failure_flags && !ok_to_fail); + if(!testCaseSuccess) + numTestCasesFailed++; + } + }; + + ContextState* g_cs = nullptr; + + // used to avoid locks for the debug output + // TODO: figure out if this is indeed necessary/correct - seems like either there still + // could be a race or that there wouldn't be a race even if using the context directly + DOCTEST_THREAD_LOCAL bool g_no_colors; + +#endif // DOCTEST_CONFIG_DISABLE +} // namespace detail + +char* String::allocate(size_type sz) { + if (sz <= last) { + buf[sz] = '\0'; + setLast(last - sz); + return buf; + } else { + setOnHeap(); + data.size = sz; + data.capacity = data.size + 1; + data.ptr = new char[data.capacity]; + data.ptr[sz] = '\0'; + return data.ptr; + } +} + +void String::setOnHeap() noexcept { *reinterpret_cast(&buf[last]) = 128; } +void String::setLast(size_type in) noexcept { buf[last] = char(in); } +void String::setSize(size_type sz) noexcept { + if (isOnStack()) { buf[sz] = '\0'; setLast(last - sz); } + else { data.ptr[sz] = '\0'; data.size = sz; } +} + +void String::copy(const String& other) { + if(other.isOnStack()) { + memcpy(buf, other.buf, len); + } else { + memcpy(allocate(other.data.size), other.data.ptr, other.data.size); + } +} + +String::String() noexcept { + buf[0] = '\0'; + setLast(); +} + +String::~String() { + if(!isOnStack()) + delete[] data.ptr; +} // NOLINT(clang-analyzer-cplusplus.NewDeleteLeaks) + +String::String(const char* in) + : String(in, strlen(in)) {} + +String::String(const char* in, size_type in_size) { + memcpy(allocate(in_size), in, in_size); +} + +String::String(std::istream& in, size_type in_size) { + in.read(allocate(in_size), in_size); +} + +String::String(const String& other) { copy(other); } + +String& String::operator=(const String& other) { + if(this != &other) { + if(!isOnStack()) + delete[] data.ptr; + + copy(other); + } + + return *this; +} + +String& String::operator+=(const String& other) { + const size_type my_old_size = size(); + const size_type other_size = other.size(); + const size_type total_size = my_old_size + other_size; + if(isOnStack()) { + if(total_size < len) { + // append to the current stack space + memcpy(buf + my_old_size, other.c_str(), other_size + 1); + // NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks) + setLast(last - total_size); + } else { + // alloc new chunk + char* temp = new char[total_size + 1]; + // copy current data to new location before writing in the union + memcpy(temp, buf, my_old_size); // skip the +1 ('\0') for speed + // update data in union + setOnHeap(); + data.size = total_size; + data.capacity = data.size + 1; + data.ptr = temp; + // transfer the rest of the data + memcpy(data.ptr + my_old_size, other.c_str(), other_size + 1); + } + } else { + if(data.capacity > total_size) { + // append to the current heap block + data.size = total_size; + memcpy(data.ptr + my_old_size, other.c_str(), other_size + 1); + } else { + // resize + data.capacity *= 2; + if(data.capacity <= total_size) + data.capacity = total_size + 1; + // alloc new chunk + char* temp = new char[data.capacity]; + // copy current data to new location before releasing it + memcpy(temp, data.ptr, my_old_size); // skip the +1 ('\0') for speed + // release old chunk + delete[] data.ptr; + // update the rest of the union members + data.size = total_size; + data.ptr = temp; + // transfer the rest of the data + memcpy(data.ptr + my_old_size, other.c_str(), other_size + 1); + } + } + + return *this; +} + +String::String(String&& other) noexcept { + memcpy(buf, other.buf, len); + other.buf[0] = '\0'; + other.setLast(); +} + +String& String::operator=(String&& other) noexcept { + if(this != &other) { + if(!isOnStack()) + delete[] data.ptr; + memcpy(buf, other.buf, len); + other.buf[0] = '\0'; + other.setLast(); + } + return *this; +} + +char String::operator[](size_type i) const { + return const_cast(this)->operator[](i); +} + +char& String::operator[](size_type i) { + if(isOnStack()) + return reinterpret_cast(buf)[i]; + return data.ptr[i]; +} + +DOCTEST_GCC_SUPPRESS_WARNING_WITH_PUSH("-Wmaybe-uninitialized") +String::size_type String::size() const { + if(isOnStack()) + return last - (size_type(buf[last]) & 31); // using "last" would work only if "len" is 32 + return data.size; +} +DOCTEST_GCC_SUPPRESS_WARNING_POP + +String::size_type String::capacity() const { + if(isOnStack()) + return len; + return data.capacity; +} + +String String::substr(size_type pos, size_type cnt) && { + cnt = std::min(cnt, size() - 1 - pos); + char* cptr = c_str(); + memmove(cptr, cptr + pos, cnt); + setSize(cnt); + return std::move(*this); +} + +String String::substr(size_type pos, size_type cnt) const & { + cnt = std::min(cnt, size() - 1 - pos); + return String{ c_str() + pos, cnt }; +} + +String::size_type String::find(char ch, size_type pos) const { + const char* begin = c_str(); + const char* end = begin + size(); + const char* it = begin + pos; + for (; it < end && *it != ch; it++); + if (it < end) { return static_cast(it - begin); } + else { return npos; } +} + +String::size_type String::rfind(char ch, size_type pos) const { + const char* begin = c_str(); + const char* it = begin + std::min(pos, size() - 1); + for (; it >= begin && *it != ch; it--); + if (it >= begin) { return static_cast(it - begin); } + else { return npos; } +} + +int String::compare(const char* other, bool no_case) const { + if(no_case) + return doctest::stricmp(c_str(), other); + return std::strcmp(c_str(), other); +} + +int String::compare(const String& other, bool no_case) const { + return compare(other.c_str(), no_case); +} + +String operator+(const String& lhs, const String& rhs) { return String(lhs) += rhs; } + +bool operator==(const String& lhs, const String& rhs) { return lhs.compare(rhs) == 0; } +bool operator!=(const String& lhs, const String& rhs) { return lhs.compare(rhs) != 0; } +bool operator< (const String& lhs, const String& rhs) { return lhs.compare(rhs) < 0; } +bool operator> (const String& lhs, const String& rhs) { return lhs.compare(rhs) > 0; } +bool operator<=(const String& lhs, const String& rhs) { return (lhs != rhs) ? lhs.compare(rhs) < 0 : true; } +bool operator>=(const String& lhs, const String& rhs) { return (lhs != rhs) ? lhs.compare(rhs) > 0 : true; } + +std::ostream& operator<<(std::ostream& s, const String& in) { return s << in.c_str(); } + +Contains::Contains(const String& str) : string(str) { } + +bool Contains::checkWith(const String& other) const { + return strstr(other.c_str(), string.c_str()) != nullptr; +} + +String toString(const Contains& in) { + return "Contains( " + in.string + " )"; +} + +bool operator==(const String& lhs, const Contains& rhs) { return rhs.checkWith(lhs); } +bool operator==(const Contains& lhs, const String& rhs) { return lhs.checkWith(rhs); } +bool operator!=(const String& lhs, const Contains& rhs) { return !rhs.checkWith(lhs); } +bool operator!=(const Contains& lhs, const String& rhs) { return !lhs.checkWith(rhs); } + +namespace { + void color_to_stream(std::ostream&, Color::Enum) DOCTEST_BRANCH_ON_DISABLED({}, ;) +} // namespace + +namespace Color { + std::ostream& operator<<(std::ostream& s, Color::Enum code) { + color_to_stream(s, code); + return s; + } +} // namespace Color + +// clang-format off +const char* assertString(assertType::Enum at) { + DOCTEST_MSVC_SUPPRESS_WARNING_WITH_PUSH(4061) // enum 'x' in switch of enum 'y' is not explicitly handled + #define DOCTEST_GENERATE_ASSERT_TYPE_CASE(assert_type) case assertType::DT_ ## assert_type: return #assert_type + #define DOCTEST_GENERATE_ASSERT_TYPE_CASES(assert_type) \ + DOCTEST_GENERATE_ASSERT_TYPE_CASE(WARN_ ## assert_type); \ + DOCTEST_GENERATE_ASSERT_TYPE_CASE(CHECK_ ## assert_type); \ + DOCTEST_GENERATE_ASSERT_TYPE_CASE(REQUIRE_ ## assert_type) + switch(at) { + DOCTEST_GENERATE_ASSERT_TYPE_CASE(WARN); + DOCTEST_GENERATE_ASSERT_TYPE_CASE(CHECK); + DOCTEST_GENERATE_ASSERT_TYPE_CASE(REQUIRE); + + DOCTEST_GENERATE_ASSERT_TYPE_CASES(FALSE); + + DOCTEST_GENERATE_ASSERT_TYPE_CASES(THROWS); + + DOCTEST_GENERATE_ASSERT_TYPE_CASES(THROWS_AS); + + DOCTEST_GENERATE_ASSERT_TYPE_CASES(THROWS_WITH); + + DOCTEST_GENERATE_ASSERT_TYPE_CASES(THROWS_WITH_AS); + + DOCTEST_GENERATE_ASSERT_TYPE_CASES(NOTHROW); + + DOCTEST_GENERATE_ASSERT_TYPE_CASES(EQ); + DOCTEST_GENERATE_ASSERT_TYPE_CASES(NE); + DOCTEST_GENERATE_ASSERT_TYPE_CASES(GT); + DOCTEST_GENERATE_ASSERT_TYPE_CASES(LT); + DOCTEST_GENERATE_ASSERT_TYPE_CASES(GE); + DOCTEST_GENERATE_ASSERT_TYPE_CASES(LE); + + DOCTEST_GENERATE_ASSERT_TYPE_CASES(UNARY); + DOCTEST_GENERATE_ASSERT_TYPE_CASES(UNARY_FALSE); + + default: DOCTEST_INTERNAL_ERROR("Tried stringifying invalid assert type!"); + } + DOCTEST_MSVC_SUPPRESS_WARNING_POP +} +// clang-format on + +const char* failureString(assertType::Enum at) { + if(at & assertType::is_warn) //!OCLINT bitwise operator in conditional + return "WARNING"; + if(at & assertType::is_check) //!OCLINT bitwise operator in conditional + return "ERROR"; + if(at & assertType::is_require) //!OCLINT bitwise operator in conditional + return "FATAL ERROR"; + return ""; +} + +DOCTEST_CLANG_SUPPRESS_WARNING_WITH_PUSH("-Wnull-dereference") +DOCTEST_GCC_SUPPRESS_WARNING_WITH_PUSH("-Wnull-dereference") +// depending on the current options this will remove the path of filenames +const char* skipPathFromFilename(const char* file) { +#ifndef DOCTEST_CONFIG_DISABLE + if(getContextOptions()->no_path_in_filenames) { + auto back = std::strrchr(file, '\\'); + auto forward = std::strrchr(file, '/'); + if(back || forward) { + if(back > forward) + forward = back; + return forward + 1; + } + } +#endif // DOCTEST_CONFIG_DISABLE + return file; +} +DOCTEST_CLANG_SUPPRESS_WARNING_POP +DOCTEST_GCC_SUPPRESS_WARNING_POP + +bool SubcaseSignature::operator==(const SubcaseSignature& other) const { + return m_line == other.m_line + && std::strcmp(m_file, other.m_file) == 0 + && m_name == other.m_name; +} + +bool SubcaseSignature::operator<(const SubcaseSignature& other) const { + if(m_line != other.m_line) + return m_line < other.m_line; + if(std::strcmp(m_file, other.m_file) != 0) + return std::strcmp(m_file, other.m_file) < 0; + return m_name.compare(other.m_name) < 0; +} + +DOCTEST_DEFINE_INTERFACE(IContextScope) + +namespace detail { + void filldata::fill(std::ostream* stream, const void* in) { + if (in) { *stream << in; } + else { *stream << "nullptr"; } + } + + template + String toStreamLit(T t) { + std::ostream* os = tlssPush(); + os->operator<<(t); + return tlssPop(); + } +} + +#ifdef DOCTEST_CONFIG_TREAT_CHAR_STAR_AS_STRING +String toString(const char* in) { return String("\"") + (in ? in : "{null string}") + "\""; } +#endif // DOCTEST_CONFIG_TREAT_CHAR_STAR_AS_STRING + +#if DOCTEST_MSVC >= DOCTEST_COMPILER(19, 20, 0) +// see this issue on why this is needed: https://github.com/doctest/doctest/issues/183 +String toString(const std::string& in) { return in.c_str(); } +#endif // VS 2019 + +String toString(String in) { return in; } + +String toString(std::nullptr_t) { return "nullptr"; } + +String toString(bool in) { return in ? "true" : "false"; } + +String toString(float in) { return toStreamLit(in); } +String toString(double in) { return toStreamLit(in); } +String toString(double long in) { return toStreamLit(in); } + +String toString(char in) { return toStreamLit(static_cast(in)); } +String toString(char signed in) { return toStreamLit(static_cast(in)); } +String toString(char unsigned in) { return toStreamLit(static_cast(in)); } +String toString(short in) { return toStreamLit(in); } +String toString(short unsigned in) { return toStreamLit(in); } +String toString(signed in) { return toStreamLit(in); } +String toString(unsigned in) { return toStreamLit(in); } +String toString(long in) { return toStreamLit(in); } +String toString(long unsigned in) { return toStreamLit(in); } +String toString(long long in) { return toStreamLit(in); } +String toString(long long unsigned in) { return toStreamLit(in); } + +Approx::Approx(double value) + : m_epsilon(static_cast(std::numeric_limits::epsilon()) * 100) + , m_scale(1.0) + , m_value(value) {} + +Approx Approx::operator()(double value) const { + Approx approx(value); + approx.epsilon(m_epsilon); + approx.scale(m_scale); + return approx; +} + +Approx& Approx::epsilon(double newEpsilon) { + m_epsilon = newEpsilon; + return *this; +} +Approx& Approx::scale(double newScale) { + m_scale = newScale; + return *this; +} + +bool operator==(double lhs, const Approx& rhs) { + // Thanks to Richard Harris for his help refining this formula + return std::fabs(lhs - rhs.m_value) < + rhs.m_epsilon * (rhs.m_scale + std::max(std::fabs(lhs), std::fabs(rhs.m_value))); +} +bool operator==(const Approx& lhs, double rhs) { return operator==(rhs, lhs); } +bool operator!=(double lhs, const Approx& rhs) { return !operator==(lhs, rhs); } +bool operator!=(const Approx& lhs, double rhs) { return !operator==(rhs, lhs); } +bool operator<=(double lhs, const Approx& rhs) { return lhs < rhs.m_value || lhs == rhs; } +bool operator<=(const Approx& lhs, double rhs) { return lhs.m_value < rhs || lhs == rhs; } +bool operator>=(double lhs, const Approx& rhs) { return lhs > rhs.m_value || lhs == rhs; } +bool operator>=(const Approx& lhs, double rhs) { return lhs.m_value > rhs || lhs == rhs; } +bool operator<(double lhs, const Approx& rhs) { return lhs < rhs.m_value && lhs != rhs; } +bool operator<(const Approx& lhs, double rhs) { return lhs.m_value < rhs && lhs != rhs; } +bool operator>(double lhs, const Approx& rhs) { return lhs > rhs.m_value && lhs != rhs; } +bool operator>(const Approx& lhs, double rhs) { return lhs.m_value > rhs && lhs != rhs; } + +String toString(const Approx& in) { + return "Approx( " + doctest::toString(in.m_value) + " )"; +} +const ContextOptions* getContextOptions() { return DOCTEST_BRANCH_ON_DISABLED(nullptr, g_cs); } + +DOCTEST_MSVC_SUPPRESS_WARNING_WITH_PUSH(4738) +template +IsNaN::operator bool() const { + return std::isnan(value) ^ flipped; +} +DOCTEST_MSVC_SUPPRESS_WARNING_POP +template struct DOCTEST_INTERFACE_DEF IsNaN; +template struct DOCTEST_INTERFACE_DEF IsNaN; +template struct DOCTEST_INTERFACE_DEF IsNaN; +template +String toString(IsNaN in) { return String(in.flipped ? "! " : "") + "IsNaN( " + doctest::toString(in.value) + " )"; } +String toString(IsNaN in) { return toString(in); } +String toString(IsNaN in) { return toString(in); } +String toString(IsNaN in) { return toString(in); } + +} // namespace doctest + +#ifdef DOCTEST_CONFIG_DISABLE +namespace doctest { +Context::Context(int, const char* const*) {} +Context::~Context() = default; +void Context::applyCommandLine(int, const char* const*) {} +void Context::addFilter(const char*, const char*) {} +void Context::clearFilters() {} +void Context::setOption(const char*, bool) {} +void Context::setOption(const char*, int) {} +void Context::setOption(const char*, const char*) {} +bool Context::shouldExit() { return false; } +void Context::setAsDefaultForAssertsOutOfTestCases() {} +void Context::setAssertHandler(detail::assert_handler) {} +void Context::setCout(std::ostream*) {} +int Context::run() { return 0; } + +int IReporter::get_num_active_contexts() { return 0; } +const IContextScope* const* IReporter::get_active_contexts() { return nullptr; } +int IReporter::get_num_stringified_contexts() { return 0; } +const String* IReporter::get_stringified_contexts() { return nullptr; } + +int registerReporter(const char*, int, IReporter*) { return 0; } + +} // namespace doctest +#else // DOCTEST_CONFIG_DISABLE + +#if !defined(DOCTEST_CONFIG_COLORS_NONE) +#if !defined(DOCTEST_CONFIG_COLORS_WINDOWS) && !defined(DOCTEST_CONFIG_COLORS_ANSI) +#ifdef DOCTEST_PLATFORM_WINDOWS +#define DOCTEST_CONFIG_COLORS_WINDOWS +#else // linux +#define DOCTEST_CONFIG_COLORS_ANSI +#endif // platform +#endif // DOCTEST_CONFIG_COLORS_WINDOWS && DOCTEST_CONFIG_COLORS_ANSI +#endif // DOCTEST_CONFIG_COLORS_NONE + +namespace doctest_detail_test_suite_ns { +// holds the current test suite +doctest::detail::TestSuite& getCurrentTestSuite() { + static doctest::detail::TestSuite data{}; + return data; +} +} // namespace doctest_detail_test_suite_ns + +namespace doctest { +namespace { + // the int (priority) is part of the key for automatic sorting - sadly one can register a + // reporter with a duplicate name and a different priority but hopefully that won't happen often :| + using reporterMap = std::map, reporterCreatorFunc>; + + reporterMap& getReporters() { + static reporterMap data; + return data; + } + reporterMap& getListeners() { + static reporterMap data; + return data; + } +} // namespace +namespace detail { +#define DOCTEST_ITERATE_THROUGH_REPORTERS(function, ...) \ + for(auto& curr_rep : g_cs->reporters_currently_used) \ + curr_rep->function(__VA_ARGS__) + + bool checkIfShouldThrow(assertType::Enum at) { + if(at & assertType::is_require) //!OCLINT bitwise operator in conditional + return true; + + if((at & assertType::is_check) //!OCLINT bitwise operator in conditional + && getContextOptions()->abort_after > 0 && + (g_cs->numAssertsFailed + g_cs->numAssertsFailedCurrentTest_atomic) >= + getContextOptions()->abort_after) + return true; + + return false; + } + +#ifndef DOCTEST_CONFIG_NO_EXCEPTIONS + DOCTEST_NORETURN void throwException() { + g_cs->shouldLogCurrentException = false; + throw TestFailureException(); // NOLINT(hicpp-exception-baseclass) + } +#else // DOCTEST_CONFIG_NO_EXCEPTIONS + void throwException() {} +#endif // DOCTEST_CONFIG_NO_EXCEPTIONS +} // namespace detail + +namespace { + using namespace detail; + // matching of a string against a wildcard mask (case sensitivity configurable) taken from + // https://www.codeproject.com/Articles/1088/Wildcard-string-compare-globbing + int wildcmp(const char* str, const char* wild, bool caseSensitive) { + const char* cp = str; + const char* mp = wild; + + while((*str) && (*wild != '*')) { + if((caseSensitive ? (*wild != *str) : (tolower(*wild) != tolower(*str))) && + (*wild != '?')) { + return 0; + } + wild++; + str++; + } + + while(*str) { + if(*wild == '*') { + if(!*++wild) { + return 1; + } + mp = wild; + cp = str + 1; + } else if((caseSensitive ? (*wild == *str) : (tolower(*wild) == tolower(*str))) || + (*wild == '?')) { + wild++; + str++; + } else { + wild = mp; //!OCLINT parameter reassignment + str = cp++; //!OCLINT parameter reassignment + } + } + + while(*wild == '*') { + wild++; + } + return !*wild; + } + + // checks if the name matches any of the filters (and can be configured what to do when empty) + bool matchesAny(const char* name, const std::vector& filters, bool matchEmpty, + bool caseSensitive) { + if (filters.empty() && matchEmpty) + return true; + for (auto& curr : filters) + if (wildcmp(name, curr.c_str(), caseSensitive)) + return true; + return false; + } + + DOCTEST_NO_SANITIZE_INTEGER + unsigned long long hash(unsigned long long a, unsigned long long b) { + return (a << 5) + b; + } + + // C string hash function (djb2) - taken from http://www.cse.yorku.ca/~oz/hash.html + DOCTEST_NO_SANITIZE_INTEGER + unsigned long long hash(const char* str) { + unsigned long long hash = 5381; + char c; + while ((c = *str++)) + hash = ((hash << 5) + hash) + c; // hash * 33 + c + return hash; + } + + unsigned long long hash(const SubcaseSignature& sig) { + return hash(hash(hash(sig.m_file), hash(sig.m_name.c_str())), sig.m_line); + } + + unsigned long long hash(const std::vector& sigs, size_t count) { + unsigned long long running = 0; + auto end = sigs.begin() + count; + for (auto it = sigs.begin(); it != end; it++) { + running = hash(running, hash(*it)); + } + return running; + } + + unsigned long long hash(const std::vector& sigs) { + unsigned long long running = 0; + for (const SubcaseSignature& sig : sigs) { + running = hash(running, hash(sig)); + } + return running; + } +} // namespace +namespace detail { + bool Subcase::checkFilters() { + if (g_cs->subcaseStack.size() < size_t(g_cs->subcase_filter_levels)) { + if (!matchesAny(m_signature.m_name.c_str(), g_cs->filters[6], true, g_cs->case_sensitive)) + return true; + if (matchesAny(m_signature.m_name.c_str(), g_cs->filters[7], false, g_cs->case_sensitive)) + return true; + } + return false; + } + + Subcase::Subcase(const String& name, const char* file, int line) + : m_signature({name, file, line}) { + if (!g_cs->reachedLeaf) { + if (g_cs->nextSubcaseStack.size() <= g_cs->subcaseStack.size() + || g_cs->nextSubcaseStack[g_cs->subcaseStack.size()] == m_signature) { + // Going down. + if (checkFilters()) { return; } + + g_cs->subcaseStack.push_back(m_signature); + g_cs->currentSubcaseDepth++; + m_entered = true; + DOCTEST_ITERATE_THROUGH_REPORTERS(subcase_start, m_signature); + } + } else { + if (g_cs->subcaseStack[g_cs->currentSubcaseDepth] == m_signature) { + // This subcase is reentered via control flow. + g_cs->currentSubcaseDepth++; + m_entered = true; + DOCTEST_ITERATE_THROUGH_REPORTERS(subcase_start, m_signature); + } else if (g_cs->nextSubcaseStack.size() <= g_cs->currentSubcaseDepth + && g_cs->fullyTraversedSubcases.find(hash(hash(g_cs->subcaseStack, g_cs->currentSubcaseDepth), hash(m_signature))) + == g_cs->fullyTraversedSubcases.end()) { + if (checkFilters()) { return; } + // This subcase is part of the one to be executed next. + g_cs->nextSubcaseStack.clear(); + g_cs->nextSubcaseStack.insert(g_cs->nextSubcaseStack.end(), + g_cs->subcaseStack.begin(), g_cs->subcaseStack.begin() + g_cs->currentSubcaseDepth); + g_cs->nextSubcaseStack.push_back(m_signature); + } + } + } + + DOCTEST_MSVC_SUPPRESS_WARNING_WITH_PUSH(4996) // std::uncaught_exception is deprecated in C++17 + DOCTEST_GCC_SUPPRESS_WARNING_WITH_PUSH("-Wdeprecated-declarations") + DOCTEST_CLANG_SUPPRESS_WARNING_WITH_PUSH("-Wdeprecated-declarations") + + Subcase::~Subcase() { + if (m_entered) { + g_cs->currentSubcaseDepth--; + + if (!g_cs->reachedLeaf) { + // Leaf. + g_cs->fullyTraversedSubcases.insert(hash(g_cs->subcaseStack)); + g_cs->nextSubcaseStack.clear(); + g_cs->reachedLeaf = true; + } else if (g_cs->nextSubcaseStack.empty()) { + // All children are finished. + g_cs->fullyTraversedSubcases.insert(hash(g_cs->subcaseStack)); + } + +#if defined(__cpp_lib_uncaught_exceptions) && __cpp_lib_uncaught_exceptions >= 201411L && (!defined(__MAC_OS_X_VERSION_MIN_REQUIRED) || __MAC_OS_X_VERSION_MIN_REQUIRED >= 101200) + if(std::uncaught_exceptions() > 0 +#else + if(std::uncaught_exception() +#endif + && g_cs->shouldLogCurrentException) { + DOCTEST_ITERATE_THROUGH_REPORTERS( + test_case_exception, {"exception thrown in subcase - will translate later " + "when the whole test case has been exited (cannot " + "translate while there is an active exception)", + false}); + g_cs->shouldLogCurrentException = false; + } + + DOCTEST_ITERATE_THROUGH_REPORTERS(subcase_end, DOCTEST_EMPTY); + } + } + + DOCTEST_CLANG_SUPPRESS_WARNING_POP + DOCTEST_GCC_SUPPRESS_WARNING_POP + DOCTEST_MSVC_SUPPRESS_WARNING_POP + + Subcase::operator bool() const { return m_entered; } + + Result::Result(bool passed, const String& decomposition) + : m_passed(passed) + , m_decomp(decomposition) {} + + ExpressionDecomposer::ExpressionDecomposer(assertType::Enum at) + : m_at(at) {} + + TestSuite& TestSuite::operator*(const char* in) { + m_test_suite = in; + return *this; + } + + TestCase::TestCase(funcType test, const char* file, unsigned line, const TestSuite& test_suite, + const String& type, int template_id) { + m_file = file; + m_line = line; + m_name = nullptr; // will be later overridden in operator* + m_test_suite = test_suite.m_test_suite; + m_description = test_suite.m_description; + m_skip = test_suite.m_skip; + m_no_breaks = test_suite.m_no_breaks; + m_no_output = test_suite.m_no_output; + m_may_fail = test_suite.m_may_fail; + m_should_fail = test_suite.m_should_fail; + m_expected_failures = test_suite.m_expected_failures; + m_timeout = test_suite.m_timeout; + + m_test = test; + m_type = type; + m_template_id = template_id; + } + + TestCase::TestCase(const TestCase& other) + : TestCaseData() { + *this = other; + } + + DOCTEST_MSVC_SUPPRESS_WARNING_WITH_PUSH(26434) // hides a non-virtual function + TestCase& TestCase::operator=(const TestCase& other) { + TestCaseData::operator=(other); + m_test = other.m_test; + m_type = other.m_type; + m_template_id = other.m_template_id; + m_full_name = other.m_full_name; + + if(m_template_id != -1) + m_name = m_full_name.c_str(); + return *this; + } + DOCTEST_MSVC_SUPPRESS_WARNING_POP + + TestCase& TestCase::operator*(const char* in) { + m_name = in; + // make a new name with an appended type for templated test case + if(m_template_id != -1) { + m_full_name = String(m_name) + "<" + m_type + ">"; + // redirect the name to point to the newly constructed full name + m_name = m_full_name.c_str(); + } + return *this; + } + + bool TestCase::operator<(const TestCase& other) const { + // this will be used only to differentiate between test cases - not relevant for sorting + if(m_line != other.m_line) + return m_line < other.m_line; + const int name_cmp = strcmp(m_name, other.m_name); + if(name_cmp != 0) + return name_cmp < 0; + const int file_cmp = m_file.compare(other.m_file); + if(file_cmp != 0) + return file_cmp < 0; + return m_template_id < other.m_template_id; + } + + // all the registered tests + std::set& getRegisteredTests() { + static std::set data; + return data; + } +} // namespace detail +namespace { + using namespace detail; + // for sorting tests by file/line + bool fileOrderComparator(const TestCase* lhs, const TestCase* rhs) { + // this is needed because MSVC gives different case for drive letters + // for __FILE__ when evaluated in a header and a source file + const int res = lhs->m_file.compare(rhs->m_file, bool(DOCTEST_MSVC)); + if(res != 0) + return res < 0; + if(lhs->m_line != rhs->m_line) + return lhs->m_line < rhs->m_line; + return lhs->m_template_id < rhs->m_template_id; + } + + // for sorting tests by suite/file/line + bool suiteOrderComparator(const TestCase* lhs, const TestCase* rhs) { + const int res = std::strcmp(lhs->m_test_suite, rhs->m_test_suite); + if(res != 0) + return res < 0; + return fileOrderComparator(lhs, rhs); + } + + // for sorting tests by name/suite/file/line + bool nameOrderComparator(const TestCase* lhs, const TestCase* rhs) { + const int res = std::strcmp(lhs->m_name, rhs->m_name); + if(res != 0) + return res < 0; + return suiteOrderComparator(lhs, rhs); + } + + DOCTEST_CLANG_SUPPRESS_WARNING_WITH_PUSH("-Wdeprecated-declarations") + void color_to_stream(std::ostream& s, Color::Enum code) { + static_cast(s); // for DOCTEST_CONFIG_COLORS_NONE or DOCTEST_CONFIG_COLORS_WINDOWS + static_cast(code); // for DOCTEST_CONFIG_COLORS_NONE +#ifdef DOCTEST_CONFIG_COLORS_ANSI + if(g_no_colors || + (isatty(STDOUT_FILENO) == false && getContextOptions()->force_colors == false)) + return; + + auto col = ""; + // clang-format off + switch(code) { //!OCLINT missing break in switch statement / unnecessary default statement in covered switch statement + case Color::Red: col = "[0;31m"; break; + case Color::Green: col = "[0;32m"; break; + case Color::Blue: col = "[0;34m"; break; + case Color::Cyan: col = "[0;36m"; break; + case Color::Yellow: col = "[0;33m"; break; + case Color::Grey: col = "[1;30m"; break; + case Color::LightGrey: col = "[0;37m"; break; + case Color::BrightRed: col = "[1;31m"; break; + case Color::BrightGreen: col = "[1;32m"; break; + case Color::BrightWhite: col = "[1;37m"; break; + case Color::Bright: // invalid + case Color::None: + case Color::White: + default: col = "[0m"; + } + // clang-format on + s << "\033" << col; +#endif // DOCTEST_CONFIG_COLORS_ANSI + +#ifdef DOCTEST_CONFIG_COLORS_WINDOWS + if(g_no_colors || + (_isatty(_fileno(stdout)) == false && getContextOptions()->force_colors == false)) + return; + + static struct ConsoleHelper { + HANDLE stdoutHandle; + WORD origFgAttrs; + WORD origBgAttrs; + + ConsoleHelper() { + stdoutHandle = GetStdHandle(STD_OUTPUT_HANDLE); + CONSOLE_SCREEN_BUFFER_INFO csbiInfo; + GetConsoleScreenBufferInfo(stdoutHandle, &csbiInfo); + origFgAttrs = csbiInfo.wAttributes & ~(BACKGROUND_GREEN | BACKGROUND_RED | + BACKGROUND_BLUE | BACKGROUND_INTENSITY); + origBgAttrs = csbiInfo.wAttributes & ~(FOREGROUND_GREEN | FOREGROUND_RED | + FOREGROUND_BLUE | FOREGROUND_INTENSITY); + } + } ch; + +#define DOCTEST_SET_ATTR(x) SetConsoleTextAttribute(ch.stdoutHandle, x | ch.origBgAttrs) + + // clang-format off + switch (code) { + case Color::White: DOCTEST_SET_ATTR(FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE); break; + case Color::Red: DOCTEST_SET_ATTR(FOREGROUND_RED); break; + case Color::Green: DOCTEST_SET_ATTR(FOREGROUND_GREEN); break; + case Color::Blue: DOCTEST_SET_ATTR(FOREGROUND_BLUE); break; + case Color::Cyan: DOCTEST_SET_ATTR(FOREGROUND_BLUE | FOREGROUND_GREEN); break; + case Color::Yellow: DOCTEST_SET_ATTR(FOREGROUND_RED | FOREGROUND_GREEN); break; + case Color::Grey: DOCTEST_SET_ATTR(0); break; + case Color::LightGrey: DOCTEST_SET_ATTR(FOREGROUND_INTENSITY); break; + case Color::BrightRed: DOCTEST_SET_ATTR(FOREGROUND_INTENSITY | FOREGROUND_RED); break; + case Color::BrightGreen: DOCTEST_SET_ATTR(FOREGROUND_INTENSITY | FOREGROUND_GREEN); break; + case Color::BrightWhite: DOCTEST_SET_ATTR(FOREGROUND_INTENSITY | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE); break; + case Color::None: + case Color::Bright: // invalid + default: DOCTEST_SET_ATTR(ch.origFgAttrs); + } + // clang-format on +#endif // DOCTEST_CONFIG_COLORS_WINDOWS + } + DOCTEST_CLANG_SUPPRESS_WARNING_POP + + std::vector& getExceptionTranslators() { + static std::vector data; + return data; + } + + String translateActiveException() { +#ifndef DOCTEST_CONFIG_NO_EXCEPTIONS + String res; + auto& translators = getExceptionTranslators(); + for(auto& curr : translators) + if(curr->translate(res)) + return res; + // clang-format off + DOCTEST_GCC_SUPPRESS_WARNING_WITH_PUSH("-Wcatch-value") + try { + throw; + } catch(std::exception& ex) { + return ex.what(); + } catch(std::string& msg) { + return msg.c_str(); + } catch(const char* msg) { + return msg; + } catch(...) { + return "unknown exception"; + } + DOCTEST_GCC_SUPPRESS_WARNING_POP +// clang-format on +#else // DOCTEST_CONFIG_NO_EXCEPTIONS + return ""; +#endif // DOCTEST_CONFIG_NO_EXCEPTIONS + } +} // namespace + +namespace detail { + // used by the macros for registering tests + int regTest(const TestCase& tc) { + getRegisteredTests().insert(tc); + return 0; + } + + // sets the current test suite + int setTestSuite(const TestSuite& ts) { + doctest_detail_test_suite_ns::getCurrentTestSuite() = ts; + return 0; + } + +#ifdef DOCTEST_IS_DEBUGGER_ACTIVE + bool isDebuggerActive() { return DOCTEST_IS_DEBUGGER_ACTIVE(); } +#else // DOCTEST_IS_DEBUGGER_ACTIVE +#ifdef DOCTEST_PLATFORM_LINUX + class ErrnoGuard { + public: + ErrnoGuard() : m_oldErrno(errno) {} + ~ErrnoGuard() { errno = m_oldErrno; } + private: + int m_oldErrno; + }; + // See the comments in Catch2 for the reasoning behind this implementation: + // https://github.com/catchorg/Catch2/blob/v2.13.1/include/internal/catch_debugger.cpp#L79-L102 + bool isDebuggerActive() { + ErrnoGuard guard; + std::ifstream in("/proc/self/status"); + for(std::string line; std::getline(in, line);) { + static const int PREFIX_LEN = 11; + if(line.compare(0, PREFIX_LEN, "TracerPid:\t") == 0) { + return line.length() > PREFIX_LEN && line[PREFIX_LEN] != '0'; + } + } + return false; + } +#elif defined(DOCTEST_PLATFORM_MAC) + // The following function is taken directly from the following technical note: + // https://developer.apple.com/library/archive/qa/qa1361/_index.html + // Returns true if the current process is being debugged (either + // running under the debugger or has a debugger attached post facto). + bool isDebuggerActive() { + int mib[4]; + kinfo_proc info; + size_t size; + // Initialize the flags so that, if sysctl fails for some bizarre + // reason, we get a predictable result. + info.kp_proc.p_flag = 0; + // Initialize mib, which tells sysctl the info we want, in this case + // we're looking for information about a specific process ID. + mib[0] = CTL_KERN; + mib[1] = KERN_PROC; + mib[2] = KERN_PROC_PID; + mib[3] = getpid(); + // Call sysctl. + size = sizeof(info); + if(sysctl(mib, DOCTEST_COUNTOF(mib), &info, &size, 0, 0) != 0) { + std::cerr << "\nCall to sysctl failed - unable to determine if debugger is active **\n"; + return false; + } + // We're being debugged if the P_TRACED flag is set. + return ((info.kp_proc.p_flag & P_TRACED) != 0); + } +#elif DOCTEST_MSVC || defined(__MINGW32__) || defined(__MINGW64__) + bool isDebuggerActive() { return ::IsDebuggerPresent() != 0; } +#else + bool isDebuggerActive() { return false; } +#endif // Platform +#endif // DOCTEST_IS_DEBUGGER_ACTIVE + + void registerExceptionTranslatorImpl(const IExceptionTranslator* et) { + if(std::find(getExceptionTranslators().begin(), getExceptionTranslators().end(), et) == + getExceptionTranslators().end()) + getExceptionTranslators().push_back(et); + } + + DOCTEST_THREAD_LOCAL std::vector g_infoContexts; // for logging with INFO() + + ContextScopeBase::ContextScopeBase() { + g_infoContexts.push_back(this); + } + + ContextScopeBase::ContextScopeBase(ContextScopeBase&& other) noexcept { + if (other.need_to_destroy) { + other.destroy(); + } + other.need_to_destroy = false; + g_infoContexts.push_back(this); + } + + DOCTEST_MSVC_SUPPRESS_WARNING_WITH_PUSH(4996) // std::uncaught_exception is deprecated in C++17 + DOCTEST_GCC_SUPPRESS_WARNING_WITH_PUSH("-Wdeprecated-declarations") + DOCTEST_CLANG_SUPPRESS_WARNING_WITH_PUSH("-Wdeprecated-declarations") + + // destroy cannot be inlined into the destructor because that would mean calling stringify after + // ContextScope has been destroyed (base class destructors run after derived class destructors). + // Instead, ContextScope calls this method directly from its destructor. + void ContextScopeBase::destroy() { +#if defined(__cpp_lib_uncaught_exceptions) && __cpp_lib_uncaught_exceptions >= 201411L && (!defined(__MAC_OS_X_VERSION_MIN_REQUIRED) || __MAC_OS_X_VERSION_MIN_REQUIRED >= 101200) + if(std::uncaught_exceptions() > 0) { +#else + if(std::uncaught_exception()) { +#endif + std::ostringstream s; + this->stringify(&s); + g_cs->stringifiedContexts.push_back(s.str().c_str()); + } + g_infoContexts.pop_back(); + } + + DOCTEST_CLANG_SUPPRESS_WARNING_POP + DOCTEST_GCC_SUPPRESS_WARNING_POP + DOCTEST_MSVC_SUPPRESS_WARNING_POP +} // namespace detail +namespace { + using namespace detail; + +#if !defined(DOCTEST_CONFIG_POSIX_SIGNALS) && !defined(DOCTEST_CONFIG_WINDOWS_SEH) + struct FatalConditionHandler + { + static void reset() {} + static void allocateAltStackMem() {} + static void freeAltStackMem() {} + }; +#else // DOCTEST_CONFIG_POSIX_SIGNALS || DOCTEST_CONFIG_WINDOWS_SEH + + void reportFatal(const std::string&); + +#ifdef DOCTEST_PLATFORM_WINDOWS + + struct SignalDefs + { + DWORD id; + const char* name; + }; + // There is no 1-1 mapping between signals and windows exceptions. + // Windows can easily distinguish between SO and SigSegV, + // but SigInt, SigTerm, etc are handled differently. + SignalDefs signalDefs[] = { + {static_cast(EXCEPTION_ILLEGAL_INSTRUCTION), + "SIGILL - Illegal instruction signal"}, + {static_cast(EXCEPTION_STACK_OVERFLOW), "SIGSEGV - Stack overflow"}, + {static_cast(EXCEPTION_ACCESS_VIOLATION), + "SIGSEGV - Segmentation violation signal"}, + {static_cast(EXCEPTION_INT_DIVIDE_BY_ZERO), "Divide by zero error"}, + }; + + struct FatalConditionHandler + { + static LONG CALLBACK handleException(PEXCEPTION_POINTERS ExceptionInfo) { + // Multiple threads may enter this filter/handler at once. We want the error message to be printed on the + // console just once no matter how many threads have crashed. + DOCTEST_DECLARE_STATIC_MUTEX(mutex) + static bool execute = true; + { + DOCTEST_LOCK_MUTEX(mutex) + if(execute) { + bool reported = false; + for(size_t i = 0; i < DOCTEST_COUNTOF(signalDefs); ++i) { + if(ExceptionInfo->ExceptionRecord->ExceptionCode == signalDefs[i].id) { + reportFatal(signalDefs[i].name); + reported = true; + break; + } + } + if(reported == false) + reportFatal("Unhandled SEH exception caught"); + if(isDebuggerActive() && !g_cs->no_breaks) + DOCTEST_BREAK_INTO_DEBUGGER(); + } + execute = false; + } + std::exit(EXIT_FAILURE); + } + + static void allocateAltStackMem() {} + static void freeAltStackMem() {} + + FatalConditionHandler() { + isSet = true; + // 32k seems enough for doctest to handle stack overflow, + // but the value was found experimentally, so there is no strong guarantee + guaranteeSize = 32 * 1024; + // Register an unhandled exception filter + previousTop = SetUnhandledExceptionFilter(handleException); + // Pass in guarantee size to be filled + SetThreadStackGuarantee(&guaranteeSize); + + // On Windows uncaught exceptions from another thread, exceptions from + // destructors, or calls to std::terminate are not a SEH exception + + // The terminal handler gets called when: + // - std::terminate is called FROM THE TEST RUNNER THREAD + // - an exception is thrown from a destructor FROM THE TEST RUNNER THREAD + original_terminate_handler = std::get_terminate(); + std::set_terminate([]() DOCTEST_NOEXCEPT { + reportFatal("Terminate handler called"); + if(isDebuggerActive() && !g_cs->no_breaks) + DOCTEST_BREAK_INTO_DEBUGGER(); + std::exit(EXIT_FAILURE); // explicitly exit - otherwise the SIGABRT handler may be called as well + }); + + // SIGABRT is raised when: + // - std::terminate is called FROM A DIFFERENT THREAD + // - an exception is thrown from a destructor FROM A DIFFERENT THREAD + // - an uncaught exception is thrown FROM A DIFFERENT THREAD + prev_sigabrt_handler = std::signal(SIGABRT, [](int signal) DOCTEST_NOEXCEPT { + if(signal == SIGABRT) { + reportFatal("SIGABRT - Abort (abnormal termination) signal"); + if(isDebuggerActive() && !g_cs->no_breaks) + DOCTEST_BREAK_INTO_DEBUGGER(); + std::exit(EXIT_FAILURE); + } + }); + + // The following settings are taken from google test, and more + // specifically from UnitTest::Run() inside of gtest.cc + + // the user does not want to see pop-up dialogs about crashes + prev_error_mode_1 = SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT | + SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX); + // This forces the abort message to go to stderr in all circumstances. + prev_error_mode_2 = _set_error_mode(_OUT_TO_STDERR); + // In the debug version, Visual Studio pops up a separate dialog + // offering a choice to debug the aborted program - we want to disable that. + prev_abort_behavior = _set_abort_behavior(0x0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT); + // In debug mode, the Windows CRT can crash with an assertion over invalid + // input (e.g. passing an invalid file descriptor). The default handling + // for these assertions is to pop up a dialog and wait for user input. + // Instead ask the CRT to dump such assertions to stderr non-interactively. + prev_report_mode = _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG); + prev_report_file = _CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR); + } + + static void reset() { + if(isSet) { + // Unregister handler and restore the old guarantee + SetUnhandledExceptionFilter(previousTop); + SetThreadStackGuarantee(&guaranteeSize); + std::set_terminate(original_terminate_handler); + std::signal(SIGABRT, prev_sigabrt_handler); + SetErrorMode(prev_error_mode_1); + _set_error_mode(prev_error_mode_2); + _set_abort_behavior(prev_abort_behavior, _WRITE_ABORT_MSG | _CALL_REPORTFAULT); + static_cast(_CrtSetReportMode(_CRT_ASSERT, prev_report_mode)); + static_cast(_CrtSetReportFile(_CRT_ASSERT, prev_report_file)); + isSet = false; + } + } + + ~FatalConditionHandler() { reset(); } + + private: + static UINT prev_error_mode_1; + static int prev_error_mode_2; + static unsigned int prev_abort_behavior; + static int prev_report_mode; + static _HFILE prev_report_file; + static void (DOCTEST_CDECL *prev_sigabrt_handler)(int); + static std::terminate_handler original_terminate_handler; + static bool isSet; + static ULONG guaranteeSize; + static LPTOP_LEVEL_EXCEPTION_FILTER previousTop; + }; + + UINT FatalConditionHandler::prev_error_mode_1; + int FatalConditionHandler::prev_error_mode_2; + unsigned int FatalConditionHandler::prev_abort_behavior; + int FatalConditionHandler::prev_report_mode; + _HFILE FatalConditionHandler::prev_report_file; + void (DOCTEST_CDECL *FatalConditionHandler::prev_sigabrt_handler)(int); + std::terminate_handler FatalConditionHandler::original_terminate_handler; + bool FatalConditionHandler::isSet = false; + ULONG FatalConditionHandler::guaranteeSize = 0; + LPTOP_LEVEL_EXCEPTION_FILTER FatalConditionHandler::previousTop = nullptr; + +#else // DOCTEST_PLATFORM_WINDOWS + + struct SignalDefs + { + int id; + const char* name; + }; + SignalDefs signalDefs[] = {{SIGINT, "SIGINT - Terminal interrupt signal"}, + {SIGILL, "SIGILL - Illegal instruction signal"}, + {SIGFPE, "SIGFPE - Floating point error signal"}, + {SIGSEGV, "SIGSEGV - Segmentation violation signal"}, + {SIGTERM, "SIGTERM - Termination request signal"}, + {SIGABRT, "SIGABRT - Abort (abnormal termination) signal"}}; + + struct FatalConditionHandler + { + static bool isSet; + static struct sigaction oldSigActions[DOCTEST_COUNTOF(signalDefs)]; + static stack_t oldSigStack; + static size_t altStackSize; + static char* altStackMem; + + static void handleSignal(int sig) { + const char* name = ""; + for(std::size_t i = 0; i < DOCTEST_COUNTOF(signalDefs); ++i) { + SignalDefs& def = signalDefs[i]; + if(sig == def.id) { + name = def.name; + break; + } + } + reset(); + reportFatal(name); + raise(sig); + } + + static void allocateAltStackMem() { + altStackMem = new char[altStackSize]; + } + + static void freeAltStackMem() { + delete[] altStackMem; + } + + FatalConditionHandler() { + isSet = true; + stack_t sigStack; + sigStack.ss_sp = altStackMem; + sigStack.ss_size = altStackSize; + sigStack.ss_flags = 0; + sigaltstack(&sigStack, &oldSigStack); + struct sigaction sa = {}; + sa.sa_handler = handleSignal; + sa.sa_flags = SA_ONSTACK; + for(std::size_t i = 0; i < DOCTEST_COUNTOF(signalDefs); ++i) { + sigaction(signalDefs[i].id, &sa, &oldSigActions[i]); + } + } + + ~FatalConditionHandler() { reset(); } + static void reset() { + if(isSet) { + // Set signals back to previous values -- hopefully nobody overwrote them in the meantime + for(std::size_t i = 0; i < DOCTEST_COUNTOF(signalDefs); ++i) { + sigaction(signalDefs[i].id, &oldSigActions[i], nullptr); + } + // Return the old stack + sigaltstack(&oldSigStack, nullptr); + isSet = false; + } + } + }; + + bool FatalConditionHandler::isSet = false; + struct sigaction FatalConditionHandler::oldSigActions[DOCTEST_COUNTOF(signalDefs)] = {}; + stack_t FatalConditionHandler::oldSigStack = {}; + size_t FatalConditionHandler::altStackSize = 4 * SIGSTKSZ; + char* FatalConditionHandler::altStackMem = nullptr; + +#endif // DOCTEST_PLATFORM_WINDOWS +#endif // DOCTEST_CONFIG_POSIX_SIGNALS || DOCTEST_CONFIG_WINDOWS_SEH + +} // namespace + +namespace { + using namespace detail; + +#ifdef DOCTEST_PLATFORM_WINDOWS +#define DOCTEST_OUTPUT_DEBUG_STRING(text) ::OutputDebugStringA(text) +#else + // TODO: integration with XCode and other IDEs +#define DOCTEST_OUTPUT_DEBUG_STRING(text) +#endif // Platform + + void addAssert(assertType::Enum at) { + if((at & assertType::is_warn) == 0) //!OCLINT bitwise operator in conditional + g_cs->numAssertsCurrentTest_atomic++; + } + + void addFailedAssert(assertType::Enum at) { + if((at & assertType::is_warn) == 0) //!OCLINT bitwise operator in conditional + g_cs->numAssertsFailedCurrentTest_atomic++; + } + +#if defined(DOCTEST_CONFIG_POSIX_SIGNALS) || defined(DOCTEST_CONFIG_WINDOWS_SEH) + void reportFatal(const std::string& message) { + g_cs->failure_flags |= TestCaseFailureReason::Crash; + + DOCTEST_ITERATE_THROUGH_REPORTERS(test_case_exception, {message.c_str(), true}); + + while (g_cs->subcaseStack.size()) { + g_cs->subcaseStack.pop_back(); + DOCTEST_ITERATE_THROUGH_REPORTERS(subcase_end, DOCTEST_EMPTY); + } + + g_cs->finalizeTestCaseData(); + + DOCTEST_ITERATE_THROUGH_REPORTERS(test_case_end, *g_cs); + + DOCTEST_ITERATE_THROUGH_REPORTERS(test_run_end, *g_cs); + } +#endif // DOCTEST_CONFIG_POSIX_SIGNALS || DOCTEST_CONFIG_WINDOWS_SEH +} // namespace + +AssertData::AssertData(assertType::Enum at, const char* file, int line, const char* expr, + const char* exception_type, const StringContains& exception_string) + : m_test_case(g_cs->currentTest), m_at(at), m_file(file), m_line(line), m_expr(expr), + m_failed(true), m_threw(false), m_threw_as(false), m_exception_type(exception_type), + m_exception_string(exception_string) { +#if DOCTEST_MSVC + if (m_expr[0] == ' ') // this happens when variadic macros are disabled under MSVC + ++m_expr; +#endif // MSVC +} + +namespace detail { + ResultBuilder::ResultBuilder(assertType::Enum at, const char* file, int line, const char* expr, + const char* exception_type, const String& exception_string) + : AssertData(at, file, line, expr, exception_type, exception_string) { } + + ResultBuilder::ResultBuilder(assertType::Enum at, const char* file, int line, const char* expr, + const char* exception_type, const Contains& exception_string) + : AssertData(at, file, line, expr, exception_type, exception_string) { } + + void ResultBuilder::setResult(const Result& res) { + m_decomp = res.m_decomp; + m_failed = !res.m_passed; + } + + void ResultBuilder::translateException() { + m_threw = true; + m_exception = translateActiveException(); + } + + bool ResultBuilder::log() { + if(m_at & assertType::is_throws) { //!OCLINT bitwise operator in conditional + m_failed = !m_threw; + } else if((m_at & assertType::is_throws_as) && (m_at & assertType::is_throws_with)) { //!OCLINT + m_failed = !m_threw_as || !m_exception_string.check(m_exception); + } else if(m_at & assertType::is_throws_as) { //!OCLINT bitwise operator in conditional + m_failed = !m_threw_as; + } else if(m_at & assertType::is_throws_with) { //!OCLINT bitwise operator in conditional + m_failed = !m_exception_string.check(m_exception); + } else if(m_at & assertType::is_nothrow) { //!OCLINT bitwise operator in conditional + m_failed = m_threw; + } + + if(m_exception.size()) + m_exception = "\"" + m_exception + "\""; + + if(is_running_in_test) { + addAssert(m_at); + DOCTEST_ITERATE_THROUGH_REPORTERS(log_assert, *this); + + if(m_failed) + addFailedAssert(m_at); + } else if(m_failed) { + failed_out_of_a_testing_context(*this); + } + + return m_failed && isDebuggerActive() && !getContextOptions()->no_breaks && + (g_cs->currentTest == nullptr || !g_cs->currentTest->m_no_breaks); // break into debugger + } + + void ResultBuilder::react() const { + if(m_failed && checkIfShouldThrow(m_at)) + throwException(); + } + + void failed_out_of_a_testing_context(const AssertData& ad) { + if(g_cs->ah) + g_cs->ah(ad); + else + std::abort(); + } + + bool decomp_assert(assertType::Enum at, const char* file, int line, const char* expr, + const Result& result) { + bool failed = !result.m_passed; + + // ################################################################################### + // IF THE DEBUGGER BREAKS HERE - GO 1 LEVEL UP IN THE CALLSTACK FOR THE FAILING ASSERT + // THIS IS THE EFFECT OF HAVING 'DOCTEST_CONFIG_SUPER_FAST_ASSERTS' DEFINED + // ################################################################################### + DOCTEST_ASSERT_OUT_OF_TESTS(result.m_decomp); + DOCTEST_ASSERT_IN_TESTS(result.m_decomp); + return !failed; + } + + MessageBuilder::MessageBuilder(const char* file, int line, assertType::Enum severity) { + m_stream = tlssPush(); + m_file = file; + m_line = line; + m_severity = severity; + } + + MessageBuilder::~MessageBuilder() { + if (!logged) + tlssPop(); + } + + DOCTEST_DEFINE_INTERFACE(IExceptionTranslator) + + bool MessageBuilder::log() { + if (!logged) { + m_string = tlssPop(); + logged = true; + } + + DOCTEST_ITERATE_THROUGH_REPORTERS(log_message, *this); + + const bool isWarn = m_severity & assertType::is_warn; + + // warn is just a message in this context so we don't treat it as an assert + if(!isWarn) { + addAssert(m_severity); + addFailedAssert(m_severity); + } + + return isDebuggerActive() && !getContextOptions()->no_breaks && !isWarn && + (g_cs->currentTest == nullptr || !g_cs->currentTest->m_no_breaks); // break into debugger + } + + void MessageBuilder::react() { + if(m_severity & assertType::is_require) //!OCLINT bitwise operator in conditional + throwException(); + } +} // namespace detail +namespace { + using namespace detail; + + // clang-format off + +// ================================================================================================= +// The following code has been taken verbatim from Catch2/include/internal/catch_xmlwriter.h/cpp +// This is done so cherry-picking bug fixes is trivial - even the style/formatting is untouched. +// ================================================================================================= + + class XmlEncode { + public: + enum ForWhat { ForTextNodes, ForAttributes }; + + XmlEncode( std::string const& str, ForWhat forWhat = ForTextNodes ); + + void encodeTo( std::ostream& os ) const; + + friend std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode ); + + private: + std::string m_str; + ForWhat m_forWhat; + }; + + class XmlWriter { + public: + + class ScopedElement { + public: + ScopedElement( XmlWriter* writer ); + + ScopedElement( ScopedElement&& other ) DOCTEST_NOEXCEPT; + ScopedElement& operator=( ScopedElement&& other ) DOCTEST_NOEXCEPT; + + ~ScopedElement(); + + ScopedElement& writeText( std::string const& text, bool indent = true ); + + template + ScopedElement& writeAttribute( std::string const& name, T const& attribute ) { + m_writer->writeAttribute( name, attribute ); + return *this; + } + + private: + mutable XmlWriter* m_writer = nullptr; + }; + +#ifndef DOCTEST_CONFIG_NO_INCLUDE_IOSTREAM + XmlWriter( std::ostream& os = std::cout ); +#else // DOCTEST_CONFIG_NO_INCLUDE_IOSTREAM + XmlWriter( std::ostream& os ); +#endif // DOCTEST_CONFIG_NO_INCLUDE_IOSTREAM + ~XmlWriter(); + + XmlWriter( XmlWriter const& ) = delete; + XmlWriter& operator=( XmlWriter const& ) = delete; + + XmlWriter& startElement( std::string const& name ); + + ScopedElement scopedElement( std::string const& name ); + + XmlWriter& endElement(); + + XmlWriter& writeAttribute( std::string const& name, std::string const& attribute ); + + XmlWriter& writeAttribute( std::string const& name, const char* attribute ); + + XmlWriter& writeAttribute( std::string const& name, bool attribute ); + + template + XmlWriter& writeAttribute( std::string const& name, T const& attribute ) { + std::stringstream rss; + rss << attribute; + return writeAttribute( name, rss.str() ); + } + + XmlWriter& writeText( std::string const& text, bool indent = true ); + + //XmlWriter& writeComment( std::string const& text ); + + //void writeStylesheetRef( std::string const& url ); + + //XmlWriter& writeBlankLine(); + + void ensureTagClosed(); + + void writeDeclaration(); + + private: + + void newlineIfNecessary(); + + bool m_tagIsOpen = false; + bool m_needsNewline = false; + std::vector m_tags; + std::string m_indent; + std::ostream& m_os; + }; + +// ================================================================================================= +// The following code has been taken verbatim from Catch2/include/internal/catch_xmlwriter.h/cpp +// This is done so cherry-picking bug fixes is trivial - even the style/formatting is untouched. +// ================================================================================================= + +using uchar = unsigned char; + +namespace { + + size_t trailingBytes(unsigned char c) { + if ((c & 0xE0) == 0xC0) { + return 2; + } + if ((c & 0xF0) == 0xE0) { + return 3; + } + if ((c & 0xF8) == 0xF0) { + return 4; + } + DOCTEST_INTERNAL_ERROR("Invalid multibyte utf-8 start byte encountered"); + } + + uint32_t headerValue(unsigned char c) { + if ((c & 0xE0) == 0xC0) { + return c & 0x1F; + } + if ((c & 0xF0) == 0xE0) { + return c & 0x0F; + } + if ((c & 0xF8) == 0xF0) { + return c & 0x07; + } + DOCTEST_INTERNAL_ERROR("Invalid multibyte utf-8 start byte encountered"); + } + + void hexEscapeChar(std::ostream& os, unsigned char c) { + std::ios_base::fmtflags f(os.flags()); + os << "\\x" + << std::uppercase << std::hex << std::setfill('0') << std::setw(2) + << static_cast(c); + os.flags(f); + } + +} // anonymous namespace + + XmlEncode::XmlEncode( std::string const& str, ForWhat forWhat ) + : m_str( str ), + m_forWhat( forWhat ) + {} + + void XmlEncode::encodeTo( std::ostream& os ) const { + // Apostrophe escaping not necessary if we always use " to write attributes + // (see: https://www.w3.org/TR/xml/#syntax) + + for( std::size_t idx = 0; idx < m_str.size(); ++ idx ) { + uchar c = m_str[idx]; + switch (c) { + case '<': os << "<"; break; + case '&': os << "&"; break; + + case '>': + // See: https://www.w3.org/TR/xml/#syntax + if (idx > 2 && m_str[idx - 1] == ']' && m_str[idx - 2] == ']') + os << ">"; + else + os << c; + break; + + case '\"': + if (m_forWhat == ForAttributes) + os << """; + else + os << c; + break; + + default: + // Check for control characters and invalid utf-8 + + // Escape control characters in standard ascii + // see https://stackoverflow.com/questions/404107/why-are-control-characters-illegal-in-xml-1-0 + if (c < 0x09 || (c > 0x0D && c < 0x20) || c == 0x7F) { + hexEscapeChar(os, c); + break; + } + + // Plain ASCII: Write it to stream + if (c < 0x7F) { + os << c; + break; + } + + // UTF-8 territory + // Check if the encoding is valid and if it is not, hex escape bytes. + // Important: We do not check the exact decoded values for validity, only the encoding format + // First check that this bytes is a valid lead byte: + // This means that it is not encoded as 1111 1XXX + // Or as 10XX XXXX + if (c < 0xC0 || + c >= 0xF8) { + hexEscapeChar(os, c); + break; + } + + auto encBytes = trailingBytes(c); + // Are there enough bytes left to avoid accessing out-of-bounds memory? + if (idx + encBytes - 1 >= m_str.size()) { + hexEscapeChar(os, c); + break; + } + // The header is valid, check data + // The next encBytes bytes must together be a valid utf-8 + // This means: bitpattern 10XX XXXX and the extracted value is sane (ish) + bool valid = true; + uint32_t value = headerValue(c); + for (std::size_t n = 1; n < encBytes; ++n) { + uchar nc = m_str[idx + n]; + valid &= ((nc & 0xC0) == 0x80); + value = (value << 6) | (nc & 0x3F); + } + + if ( + // Wrong bit pattern of following bytes + (!valid) || + // Overlong encodings + (value < 0x80) || + ( value < 0x800 && encBytes > 2) || // removed "0x80 <= value &&" because redundant + (0x800 < value && value < 0x10000 && encBytes > 3) || + // Encoded value out of range + (value >= 0x110000) + ) { + hexEscapeChar(os, c); + break; + } + + // If we got here, this is in fact a valid(ish) utf-8 sequence + for (std::size_t n = 0; n < encBytes; ++n) { + os << m_str[idx + n]; + } + idx += encBytes - 1; + break; + } + } + } + + std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode ) { + xmlEncode.encodeTo( os ); + return os; + } + + XmlWriter::ScopedElement::ScopedElement( XmlWriter* writer ) + : m_writer( writer ) + {} + + XmlWriter::ScopedElement::ScopedElement( ScopedElement&& other ) DOCTEST_NOEXCEPT + : m_writer( other.m_writer ){ + other.m_writer = nullptr; + } + XmlWriter::ScopedElement& XmlWriter::ScopedElement::operator=( ScopedElement&& other ) DOCTEST_NOEXCEPT { + if ( m_writer ) { + m_writer->endElement(); + } + m_writer = other.m_writer; + other.m_writer = nullptr; + return *this; + } + + + XmlWriter::ScopedElement::~ScopedElement() { + if( m_writer ) + m_writer->endElement(); + } + + XmlWriter::ScopedElement& XmlWriter::ScopedElement::writeText( std::string const& text, bool indent ) { + m_writer->writeText( text, indent ); + return *this; + } + + XmlWriter::XmlWriter( std::ostream& os ) : m_os( os ) + { + // writeDeclaration(); // called explicitly by the reporters that use the writer class - see issue #627 + } + + XmlWriter::~XmlWriter() { + while( !m_tags.empty() ) + endElement(); + } + + XmlWriter& XmlWriter::startElement( std::string const& name ) { + ensureTagClosed(); + newlineIfNecessary(); + m_os << m_indent << '<' << name; + m_tags.push_back( name ); + m_indent += " "; + m_tagIsOpen = true; + return *this; + } + + XmlWriter::ScopedElement XmlWriter::scopedElement( std::string const& name ) { + ScopedElement scoped( this ); + startElement( name ); + return scoped; + } + + XmlWriter& XmlWriter::endElement() { + newlineIfNecessary(); + m_indent = m_indent.substr( 0, m_indent.size()-2 ); + if( m_tagIsOpen ) { + m_os << "/>"; + m_tagIsOpen = false; + } + else { + m_os << m_indent << ""; + } + m_os << std::endl; + m_tags.pop_back(); + return *this; + } + + XmlWriter& XmlWriter::writeAttribute( std::string const& name, std::string const& attribute ) { + if( !name.empty() && !attribute.empty() ) + m_os << ' ' << name << "=\"" << XmlEncode( attribute, XmlEncode::ForAttributes ) << '"'; + return *this; + } + + XmlWriter& XmlWriter::writeAttribute( std::string const& name, const char* attribute ) { + if( !name.empty() && attribute && attribute[0] != '\0' ) + m_os << ' ' << name << "=\"" << XmlEncode( attribute, XmlEncode::ForAttributes ) << '"'; + return *this; + } + + XmlWriter& XmlWriter::writeAttribute( std::string const& name, bool attribute ) { + m_os << ' ' << name << "=\"" << ( attribute ? "true" : "false" ) << '"'; + return *this; + } + + XmlWriter& XmlWriter::writeText( std::string const& text, bool indent ) { + if( !text.empty() ){ + bool tagWasOpen = m_tagIsOpen; + ensureTagClosed(); + if( tagWasOpen && indent ) + m_os << m_indent; + m_os << XmlEncode( text ); + m_needsNewline = true; + } + return *this; + } + + //XmlWriter& XmlWriter::writeComment( std::string const& text ) { + // ensureTagClosed(); + // m_os << m_indent << ""; + // m_needsNewline = true; + // return *this; + //} + + //void XmlWriter::writeStylesheetRef( std::string const& url ) { + // m_os << "\n"; + //} + + //XmlWriter& XmlWriter::writeBlankLine() { + // ensureTagClosed(); + // m_os << '\n'; + // return *this; + //} + + void XmlWriter::ensureTagClosed() { + if( m_tagIsOpen ) { + m_os << ">" << std::endl; + m_tagIsOpen = false; + } + } + + void XmlWriter::writeDeclaration() { + m_os << "\n"; + } + + void XmlWriter::newlineIfNecessary() { + if( m_needsNewline ) { + m_os << std::endl; + m_needsNewline = false; + } + } + +// ================================================================================================= +// End of copy-pasted code from Catch +// ================================================================================================= + + // clang-format on + + struct XmlReporter : public IReporter + { + XmlWriter xml; + DOCTEST_DECLARE_MUTEX(mutex) + + // caching pointers/references to objects of these types - safe to do + const ContextOptions& opt; + const TestCaseData* tc = nullptr; + + XmlReporter(const ContextOptions& co) + : xml(*co.cout) + , opt(co) {} + + void log_contexts() { + int num_contexts = get_num_active_contexts(); + if(num_contexts) { + auto contexts = get_active_contexts(); + std::stringstream ss; + for(int i = 0; i < num_contexts; ++i) { + contexts[i]->stringify(&ss); + xml.scopedElement("Info").writeText(ss.str()); + ss.str(""); + } + } + } + + unsigned line(unsigned l) const { return opt.no_line_numbers ? 0 : l; } + + void test_case_start_impl(const TestCaseData& in) { + bool open_ts_tag = false; + if(tc != nullptr) { // we have already opened a test suite + if(std::strcmp(tc->m_test_suite, in.m_test_suite) != 0) { + xml.endElement(); + open_ts_tag = true; + } + } + else { + open_ts_tag = true; // first test case ==> first test suite + } + + if(open_ts_tag) { + xml.startElement("TestSuite"); + xml.writeAttribute("name", in.m_test_suite); + } + + tc = ∈ + xml.startElement("TestCase") + .writeAttribute("name", in.m_name) + .writeAttribute("filename", skipPathFromFilename(in.m_file.c_str())) + .writeAttribute("line", line(in.m_line)) + .writeAttribute("description", in.m_description); + + if(Approx(in.m_timeout) != 0) + xml.writeAttribute("timeout", in.m_timeout); + if(in.m_may_fail) + xml.writeAttribute("may_fail", true); + if(in.m_should_fail) + xml.writeAttribute("should_fail", true); + } + + // ========================================================================================= + // WHAT FOLLOWS ARE OVERRIDES OF THE VIRTUAL METHODS OF THE REPORTER INTERFACE + // ========================================================================================= + + void report_query(const QueryData& in) override { + test_run_start(); + if(opt.list_reporters) { + for(auto& curr : getListeners()) + xml.scopedElement("Listener") + .writeAttribute("priority", curr.first.first) + .writeAttribute("name", curr.first.second); + for(auto& curr : getReporters()) + xml.scopedElement("Reporter") + .writeAttribute("priority", curr.first.first) + .writeAttribute("name", curr.first.second); + } else if(opt.count || opt.list_test_cases) { + for(unsigned i = 0; i < in.num_data; ++i) { + xml.scopedElement("TestCase").writeAttribute("name", in.data[i]->m_name) + .writeAttribute("testsuite", in.data[i]->m_test_suite) + .writeAttribute("filename", skipPathFromFilename(in.data[i]->m_file.c_str())) + .writeAttribute("line", line(in.data[i]->m_line)) + .writeAttribute("skipped", in.data[i]->m_skip); + } + xml.scopedElement("OverallResultsTestCases") + .writeAttribute("unskipped", in.run_stats->numTestCasesPassingFilters); + } else if(opt.list_test_suites) { + for(unsigned i = 0; i < in.num_data; ++i) + xml.scopedElement("TestSuite").writeAttribute("name", in.data[i]->m_test_suite); + xml.scopedElement("OverallResultsTestCases") + .writeAttribute("unskipped", in.run_stats->numTestCasesPassingFilters); + xml.scopedElement("OverallResultsTestSuites") + .writeAttribute("unskipped", in.run_stats->numTestSuitesPassingFilters); + } + xml.endElement(); + } + + void test_run_start() override { + xml.writeDeclaration(); + + // remove .exe extension - mainly to have the same output on UNIX and Windows + std::string binary_name = skipPathFromFilename(opt.binary_name.c_str()); +#ifdef DOCTEST_PLATFORM_WINDOWS + if(binary_name.rfind(".exe") != std::string::npos) + binary_name = binary_name.substr(0, binary_name.length() - 4); +#endif // DOCTEST_PLATFORM_WINDOWS + + xml.startElement("doctest").writeAttribute("binary", binary_name); + if(opt.no_version == false) + xml.writeAttribute("version", DOCTEST_VERSION_STR); + + // only the consequential ones (TODO: filters) + xml.scopedElement("Options") + .writeAttribute("order_by", opt.order_by.c_str()) + .writeAttribute("rand_seed", opt.rand_seed) + .writeAttribute("first", opt.first) + .writeAttribute("last", opt.last) + .writeAttribute("abort_after", opt.abort_after) + .writeAttribute("subcase_filter_levels", opt.subcase_filter_levels) + .writeAttribute("case_sensitive", opt.case_sensitive) + .writeAttribute("no_throw", opt.no_throw) + .writeAttribute("no_skip", opt.no_skip); + } + + void test_run_end(const TestRunStats& p) override { + if(tc) // the TestSuite tag - only if there has been at least 1 test case + xml.endElement(); + + xml.scopedElement("OverallResultsAsserts") + .writeAttribute("successes", p.numAsserts - p.numAssertsFailed) + .writeAttribute("failures", p.numAssertsFailed); + + xml.startElement("OverallResultsTestCases") + .writeAttribute("successes", + p.numTestCasesPassingFilters - p.numTestCasesFailed) + .writeAttribute("failures", p.numTestCasesFailed); + if(opt.no_skipped_summary == false) + xml.writeAttribute("skipped", p.numTestCases - p.numTestCasesPassingFilters); + xml.endElement(); + + xml.endElement(); + } + + void test_case_start(const TestCaseData& in) override { + test_case_start_impl(in); + xml.ensureTagClosed(); + } + + void test_case_reenter(const TestCaseData&) override {} + + void test_case_end(const CurrentTestCaseStats& st) override { + xml.startElement("OverallResultsAsserts") + .writeAttribute("successes", + st.numAssertsCurrentTest - st.numAssertsFailedCurrentTest) + .writeAttribute("failures", st.numAssertsFailedCurrentTest) + .writeAttribute("test_case_success", st.testCaseSuccess); + if(opt.duration) + xml.writeAttribute("duration", st.seconds); + if(tc->m_expected_failures) + xml.writeAttribute("expected_failures", tc->m_expected_failures); + xml.endElement(); + + xml.endElement(); + } + + void test_case_exception(const TestCaseException& e) override { + DOCTEST_LOCK_MUTEX(mutex) + + xml.scopedElement("Exception") + .writeAttribute("crash", e.is_crash) + .writeText(e.error_string.c_str()); + } + + void subcase_start(const SubcaseSignature& in) override { + xml.startElement("SubCase") + .writeAttribute("name", in.m_name) + .writeAttribute("filename", skipPathFromFilename(in.m_file)) + .writeAttribute("line", line(in.m_line)); + xml.ensureTagClosed(); + } + + void subcase_end() override { xml.endElement(); } + + void log_assert(const AssertData& rb) override { + if(!rb.m_failed && !opt.success) + return; + + DOCTEST_LOCK_MUTEX(mutex) + + xml.startElement("Expression") + .writeAttribute("success", !rb.m_failed) + .writeAttribute("type", assertString(rb.m_at)) + .writeAttribute("filename", skipPathFromFilename(rb.m_file)) + .writeAttribute("line", line(rb.m_line)); + + xml.scopedElement("Original").writeText(rb.m_expr); + + if(rb.m_threw) + xml.scopedElement("Exception").writeText(rb.m_exception.c_str()); + + if(rb.m_at & assertType::is_throws_as) + xml.scopedElement("ExpectedException").writeText(rb.m_exception_type); + if(rb.m_at & assertType::is_throws_with) + xml.scopedElement("ExpectedExceptionString").writeText(rb.m_exception_string.c_str()); + if((rb.m_at & assertType::is_normal) && !rb.m_threw) + xml.scopedElement("Expanded").writeText(rb.m_decomp.c_str()); + + log_contexts(); + + xml.endElement(); + } + + void log_message(const MessageData& mb) override { + DOCTEST_LOCK_MUTEX(mutex) + + xml.startElement("Message") + .writeAttribute("type", failureString(mb.m_severity)) + .writeAttribute("filename", skipPathFromFilename(mb.m_file)) + .writeAttribute("line", line(mb.m_line)); + + xml.scopedElement("Text").writeText(mb.m_string.c_str()); + + log_contexts(); + + xml.endElement(); + } + + void test_case_skipped(const TestCaseData& in) override { + if(opt.no_skipped_summary == false) { + test_case_start_impl(in); + xml.writeAttribute("skipped", "true"); + xml.endElement(); + } + } + }; + + DOCTEST_REGISTER_REPORTER("xml", 0, XmlReporter); + + void fulltext_log_assert_to_stream(std::ostream& s, const AssertData& rb) { + if((rb.m_at & (assertType::is_throws_as | assertType::is_throws_with)) == + 0) //!OCLINT bitwise operator in conditional + s << Color::Cyan << assertString(rb.m_at) << "( " << rb.m_expr << " ) " + << Color::None; + + if(rb.m_at & assertType::is_throws) { //!OCLINT bitwise operator in conditional + s << (rb.m_threw ? "threw as expected!" : "did NOT throw at all!") << "\n"; + } else if((rb.m_at & assertType::is_throws_as) && + (rb.m_at & assertType::is_throws_with)) { //!OCLINT + s << Color::Cyan << assertString(rb.m_at) << "( " << rb.m_expr << ", \"" + << rb.m_exception_string.c_str() + << "\", " << rb.m_exception_type << " ) " << Color::None; + if(rb.m_threw) { + if(!rb.m_failed) { + s << "threw as expected!\n"; + } else { + s << "threw a DIFFERENT exception! (contents: " << rb.m_exception << ")\n"; + } + } else { + s << "did NOT throw at all!\n"; + } + } else if(rb.m_at & + assertType::is_throws_as) { //!OCLINT bitwise operator in conditional + s << Color::Cyan << assertString(rb.m_at) << "( " << rb.m_expr << ", " + << rb.m_exception_type << " ) " << Color::None + << (rb.m_threw ? (rb.m_threw_as ? "threw as expected!" : + "threw a DIFFERENT exception: ") : + "did NOT throw at all!") + << Color::Cyan << rb.m_exception << "\n"; + } else if(rb.m_at & + assertType::is_throws_with) { //!OCLINT bitwise operator in conditional + s << Color::Cyan << assertString(rb.m_at) << "( " << rb.m_expr << ", \"" + << rb.m_exception_string.c_str() + << "\" ) " << Color::None + << (rb.m_threw ? (!rb.m_failed ? "threw as expected!" : + "threw a DIFFERENT exception: ") : + "did NOT throw at all!") + << Color::Cyan << rb.m_exception << "\n"; + } else if(rb.m_at & assertType::is_nothrow) { //!OCLINT bitwise operator in conditional + s << (rb.m_threw ? "THREW exception: " : "didn't throw!") << Color::Cyan + << rb.m_exception << "\n"; + } else { + s << (rb.m_threw ? "THREW exception: " : + (!rb.m_failed ? "is correct!\n" : "is NOT correct!\n")); + if(rb.m_threw) + s << rb.m_exception << "\n"; + else + s << " values: " << assertString(rb.m_at) << "( " << rb.m_decomp << " )\n"; + } + } + + // TODO: + // - log_message() + // - respond to queries + // - honor remaining options + // - more attributes in tags + struct JUnitReporter : public IReporter + { + XmlWriter xml; + DOCTEST_DECLARE_MUTEX(mutex) + Timer timer; + std::vector deepestSubcaseStackNames; + + struct JUnitTestCaseData + { + static std::string getCurrentTimestamp() { + // Beware, this is not reentrant because of backward compatibility issues + // Also, UTC only, again because of backward compatibility (%z is C++11) + time_t rawtime; + std::time(&rawtime); + auto const timeStampSize = sizeof("2017-01-16T17:06:45Z"); + + std::tm timeInfo; +#ifdef DOCTEST_PLATFORM_WINDOWS + gmtime_s(&timeInfo, &rawtime); +#else // DOCTEST_PLATFORM_WINDOWS + gmtime_r(&rawtime, &timeInfo); +#endif // DOCTEST_PLATFORM_WINDOWS + + char timeStamp[timeStampSize]; + const char* const fmt = "%Y-%m-%dT%H:%M:%SZ"; + + std::strftime(timeStamp, timeStampSize, fmt, &timeInfo); + return std::string(timeStamp); + } + + struct JUnitTestMessage + { + JUnitTestMessage(const std::string& _message, const std::string& _type, const std::string& _details) + : message(_message), type(_type), details(_details) {} + + JUnitTestMessage(const std::string& _message, const std::string& _details) + : message(_message), type(), details(_details) {} + + std::string message, type, details; + }; + + struct JUnitTestCase + { + JUnitTestCase(const std::string& _classname, const std::string& _name) + : classname(_classname), name(_name), time(0), failures() {} + + std::string classname, name; + double time; + std::vector failures, errors; + }; + + void add(const std::string& classname, const std::string& name) { + testcases.emplace_back(classname, name); + } + + void appendSubcaseNamesToLastTestcase(std::vector nameStack) { + for(auto& curr: nameStack) + if(curr.size()) + testcases.back().name += std::string("/") + curr.c_str(); + } + + void addTime(double time) { + if(time < 1e-4) + time = 0; + testcases.back().time = time; + totalSeconds += time; + } + + void addFailure(const std::string& message, const std::string& type, const std::string& details) { + testcases.back().failures.emplace_back(message, type, details); + ++totalFailures; + } + + void addError(const std::string& message, const std::string& details) { + testcases.back().errors.emplace_back(message, details); + ++totalErrors; + } + + std::vector testcases; + double totalSeconds = 0; + int totalErrors = 0, totalFailures = 0; + }; + + JUnitTestCaseData testCaseData; + + // caching pointers/references to objects of these types - safe to do + const ContextOptions& opt; + const TestCaseData* tc = nullptr; + + JUnitReporter(const ContextOptions& co) + : xml(*co.cout) + , opt(co) {} + + unsigned line(unsigned l) const { return opt.no_line_numbers ? 0 : l; } + + // ========================================================================================= + // WHAT FOLLOWS ARE OVERRIDES OF THE VIRTUAL METHODS OF THE REPORTER INTERFACE + // ========================================================================================= + + void report_query(const QueryData&) override { + xml.writeDeclaration(); + } + + void test_run_start() override { + xml.writeDeclaration(); + } + + void test_run_end(const TestRunStats& p) override { + // remove .exe extension - mainly to have the same output on UNIX and Windows + std::string binary_name = skipPathFromFilename(opt.binary_name.c_str()); +#ifdef DOCTEST_PLATFORM_WINDOWS + if(binary_name.rfind(".exe") != std::string::npos) + binary_name = binary_name.substr(0, binary_name.length() - 4); +#endif // DOCTEST_PLATFORM_WINDOWS + xml.startElement("testsuites"); + xml.startElement("testsuite").writeAttribute("name", binary_name) + .writeAttribute("errors", testCaseData.totalErrors) + .writeAttribute("failures", testCaseData.totalFailures) + .writeAttribute("tests", p.numAsserts); + if(opt.no_time_in_output == false) { + xml.writeAttribute("time", testCaseData.totalSeconds); + xml.writeAttribute("timestamp", JUnitTestCaseData::getCurrentTimestamp()); + } + if(opt.no_version == false) + xml.writeAttribute("doctest_version", DOCTEST_VERSION_STR); + + for(const auto& testCase : testCaseData.testcases) { + xml.startElement("testcase") + .writeAttribute("classname", testCase.classname) + .writeAttribute("name", testCase.name); + if(opt.no_time_in_output == false) + xml.writeAttribute("time", testCase.time); + // This is not ideal, but it should be enough to mimic gtest's junit output. + xml.writeAttribute("status", "run"); + + for(const auto& failure : testCase.failures) { + xml.scopedElement("failure") + .writeAttribute("message", failure.message) + .writeAttribute("type", failure.type) + .writeText(failure.details, false); + } + + for(const auto& error : testCase.errors) { + xml.scopedElement("error") + .writeAttribute("message", error.message) + .writeText(error.details); + } + + xml.endElement(); + } + xml.endElement(); + xml.endElement(); + } + + void test_case_start(const TestCaseData& in) override { + testCaseData.add(skipPathFromFilename(in.m_file.c_str()), in.m_name); + timer.start(); + } + + void test_case_reenter(const TestCaseData& in) override { + testCaseData.addTime(timer.getElapsedSeconds()); + testCaseData.appendSubcaseNamesToLastTestcase(deepestSubcaseStackNames); + deepestSubcaseStackNames.clear(); + + timer.start(); + testCaseData.add(skipPathFromFilename(in.m_file.c_str()), in.m_name); + } + + void test_case_end(const CurrentTestCaseStats&) override { + testCaseData.addTime(timer.getElapsedSeconds()); + testCaseData.appendSubcaseNamesToLastTestcase(deepestSubcaseStackNames); + deepestSubcaseStackNames.clear(); + } + + void test_case_exception(const TestCaseException& e) override { + DOCTEST_LOCK_MUTEX(mutex) + testCaseData.addError("exception", e.error_string.c_str()); + } + + void subcase_start(const SubcaseSignature& in) override { + deepestSubcaseStackNames.push_back(in.m_name); + } + + void subcase_end() override {} + + void log_assert(const AssertData& rb) override { + if(!rb.m_failed) // report only failures & ignore the `success` option + return; + + DOCTEST_LOCK_MUTEX(mutex) + + std::ostringstream os; + os << skipPathFromFilename(rb.m_file) << (opt.gnu_file_line ? ":" : "(") + << line(rb.m_line) << (opt.gnu_file_line ? ":" : "):") << std::endl; + + fulltext_log_assert_to_stream(os, rb); + log_contexts(os); + testCaseData.addFailure(rb.m_decomp.c_str(), assertString(rb.m_at), os.str()); + } + + void log_message(const MessageData& mb) override { + if(mb.m_severity & assertType::is_warn) // report only failures + return; + + DOCTEST_LOCK_MUTEX(mutex) + + std::ostringstream os; + os << skipPathFromFilename(mb.m_file) << (opt.gnu_file_line ? ":" : "(") + << line(mb.m_line) << (opt.gnu_file_line ? ":" : "):") << std::endl; + + os << mb.m_string.c_str() << "\n"; + log_contexts(os); + + testCaseData.addFailure(mb.m_string.c_str(), + mb.m_severity & assertType::is_check ? "FAIL_CHECK" : "FAIL", os.str()); + } + + void test_case_skipped(const TestCaseData&) override {} + + void log_contexts(std::ostringstream& s) { + int num_contexts = get_num_active_contexts(); + if(num_contexts) { + auto contexts = get_active_contexts(); + + s << " logged: "; + for(int i = 0; i < num_contexts; ++i) { + s << (i == 0 ? "" : " "); + contexts[i]->stringify(&s); + s << std::endl; + } + } + } + }; + + DOCTEST_REGISTER_REPORTER("junit", 0, JUnitReporter); + + struct Whitespace + { + int nrSpaces; + explicit Whitespace(int nr) + : nrSpaces(nr) {} + }; + + std::ostream& operator<<(std::ostream& out, const Whitespace& ws) { + if(ws.nrSpaces != 0) + out << std::setw(ws.nrSpaces) << ' '; + return out; + } + + struct ConsoleReporter : public IReporter + { + std::ostream& s; + bool hasLoggedCurrentTestStart; + std::vector subcasesStack; + size_t currentSubcaseLevel; + DOCTEST_DECLARE_MUTEX(mutex) + + // caching pointers/references to objects of these types - safe to do + const ContextOptions& opt; + const TestCaseData* tc; + + ConsoleReporter(const ContextOptions& co) + : s(*co.cout) + , opt(co) {} + + ConsoleReporter(const ContextOptions& co, std::ostream& ostr) + : s(ostr) + , opt(co) {} + + // ========================================================================================= + // WHAT FOLLOWS ARE HELPERS USED BY THE OVERRIDES OF THE VIRTUAL METHODS OF THE INTERFACE + // ========================================================================================= + + void separator_to_stream() { + s << Color::Yellow + << "===============================================================================" + "\n"; + } + + const char* getSuccessOrFailString(bool success, assertType::Enum at, + const char* success_str) { + if(success) + return success_str; + return failureString(at); + } + + Color::Enum getSuccessOrFailColor(bool success, assertType::Enum at) { + return success ? Color::BrightGreen : + (at & assertType::is_warn) ? Color::Yellow : Color::Red; + } + + void successOrFailColoredStringToStream(bool success, assertType::Enum at, + const char* success_str = "SUCCESS") { + s << getSuccessOrFailColor(success, at) + << getSuccessOrFailString(success, at, success_str) << ": "; + } + + void log_contexts() { + int num_contexts = get_num_active_contexts(); + if(num_contexts) { + auto contexts = get_active_contexts(); + + s << Color::None << " logged: "; + for(int i = 0; i < num_contexts; ++i) { + s << (i == 0 ? "" : " "); + contexts[i]->stringify(&s); + s << "\n"; + } + } + + s << "\n"; + } + + // this was requested to be made virtual so users could override it + virtual void file_line_to_stream(const char* file, int line, + const char* tail = "") { + s << Color::LightGrey << skipPathFromFilename(file) << (opt.gnu_file_line ? ":" : "(") + << (opt.no_line_numbers ? 0 : line) // 0 or the real num depending on the option + << (opt.gnu_file_line ? ":" : "):") << tail; + } + + void logTestStart() { + if(hasLoggedCurrentTestStart) + return; + + separator_to_stream(); + file_line_to_stream(tc->m_file.c_str(), tc->m_line, "\n"); + if(tc->m_description) + s << Color::Yellow << "DESCRIPTION: " << Color::None << tc->m_description << "\n"; + if(tc->m_test_suite && tc->m_test_suite[0] != '\0') + s << Color::Yellow << "TEST SUITE: " << Color::None << tc->m_test_suite << "\n"; + if(strncmp(tc->m_name, " Scenario:", 11) != 0) + s << Color::Yellow << "TEST CASE: "; + s << Color::None << tc->m_name << "\n"; + + for(size_t i = 0; i < currentSubcaseLevel; ++i) { + if(subcasesStack[i].m_name[0] != '\0') + s << " " << subcasesStack[i].m_name << "\n"; + } + + if(currentSubcaseLevel != subcasesStack.size()) { + s << Color::Yellow << "\nDEEPEST SUBCASE STACK REACHED (DIFFERENT FROM THE CURRENT ONE):\n" << Color::None; + for(size_t i = 0; i < subcasesStack.size(); ++i) { + if(subcasesStack[i].m_name[0] != '\0') + s << " " << subcasesStack[i].m_name << "\n"; + } + } + + s << "\n"; + + hasLoggedCurrentTestStart = true; + } + + void printVersion() { + if(opt.no_version == false) + s << Color::Cyan << "[doctest] " << Color::None << "doctest version is \"" + << DOCTEST_VERSION_STR << "\"\n"; + } + + void printIntro() { + if(opt.no_intro == false) { + printVersion(); + s << Color::Cyan << "[doctest] " << Color::None + << "run with \"--" DOCTEST_OPTIONS_PREFIX_DISPLAY "help\" for options\n"; + } + } + + void printHelp() { + int sizePrefixDisplay = static_cast(strlen(DOCTEST_OPTIONS_PREFIX_DISPLAY)); + printVersion(); + // clang-format off + s << Color::Cyan << "[doctest]\n" << Color::None; + s << Color::Cyan << "[doctest] " << Color::None; + s << "boolean values: \"1/on/yes/true\" or \"0/off/no/false\"\n"; + s << Color::Cyan << "[doctest] " << Color::None; + s << "filter values: \"str1,str2,str3\" (comma separated strings)\n"; + s << Color::Cyan << "[doctest]\n" << Color::None; + s << Color::Cyan << "[doctest] " << Color::None; + s << "filters use wildcards for matching strings\n"; + s << Color::Cyan << "[doctest] " << Color::None; + s << "something passes a filter if any of the strings in a filter matches\n"; +#ifndef DOCTEST_CONFIG_NO_UNPREFIXED_OPTIONS + s << Color::Cyan << "[doctest]\n" << Color::None; + s << Color::Cyan << "[doctest] " << Color::None; + s << "ALL FLAGS, OPTIONS AND FILTERS ALSO AVAILABLE WITH A \"" DOCTEST_CONFIG_OPTIONS_PREFIX "\" PREFIX!!!\n"; +#endif + s << Color::Cyan << "[doctest]\n" << Color::None; + s << Color::Cyan << "[doctest] " << Color::None; + s << "Query flags - the program quits after them. Available:\n\n"; + s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "?, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "help, -" DOCTEST_OPTIONS_PREFIX_DISPLAY "h " + << Whitespace(sizePrefixDisplay*0) << "prints this message\n"; + s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "v, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "version " + << Whitespace(sizePrefixDisplay*1) << "prints the version\n"; + s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "c, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "count " + << Whitespace(sizePrefixDisplay*1) << "prints the number of matching tests\n"; + s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "ltc, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "list-test-cases " + << Whitespace(sizePrefixDisplay*1) << "lists all matching tests by name\n"; + s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "lts, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "list-test-suites " + << Whitespace(sizePrefixDisplay*1) << "lists all matching test suites\n"; + s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "lr, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "list-reporters " + << Whitespace(sizePrefixDisplay*1) << "lists all registered reporters\n\n"; + // ================================================================================== << 79 + s << Color::Cyan << "[doctest] " << Color::None; + s << "The available / options/filters are:\n\n"; + s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "tc, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "test-case= " + << Whitespace(sizePrefixDisplay*1) << "filters tests by their name\n"; + s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "tce, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "test-case-exclude= " + << Whitespace(sizePrefixDisplay*1) << "filters OUT tests by their name\n"; + s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "sf, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "source-file= " + << Whitespace(sizePrefixDisplay*1) << "filters tests by their file\n"; + s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "sfe, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "source-file-exclude= " + << Whitespace(sizePrefixDisplay*1) << "filters OUT tests by their file\n"; + s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "ts, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "test-suite= " + << Whitespace(sizePrefixDisplay*1) << "filters tests by their test suite\n"; + s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "tse, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "test-suite-exclude= " + << Whitespace(sizePrefixDisplay*1) << "filters OUT tests by their test suite\n"; + s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "sc, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "subcase= " + << Whitespace(sizePrefixDisplay*1) << "filters subcases by their name\n"; + s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "sce, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "subcase-exclude= " + << Whitespace(sizePrefixDisplay*1) << "filters OUT subcases by their name\n"; + s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "r, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "reporters= " + << Whitespace(sizePrefixDisplay*1) << "reporters to use (console is default)\n"; + s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "o, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "out= " + << Whitespace(sizePrefixDisplay*1) << "output filename\n"; + s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "ob, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "order-by= " + << Whitespace(sizePrefixDisplay*1) << "how the tests should be ordered\n"; + s << Whitespace(sizePrefixDisplay*3) << " - [file/suite/name/rand/none]\n"; + s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "rs, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "rand-seed= " + << Whitespace(sizePrefixDisplay*1) << "seed for random ordering\n"; + s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "f, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "first= " + << Whitespace(sizePrefixDisplay*1) << "the first test passing the filters to\n"; + s << Whitespace(sizePrefixDisplay*3) << " execute - for range-based execution\n"; + s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "l, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "last= " + << Whitespace(sizePrefixDisplay*1) << "the last test passing the filters to\n"; + s << Whitespace(sizePrefixDisplay*3) << " execute - for range-based execution\n"; + s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "aa, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "abort-after= " + << Whitespace(sizePrefixDisplay*1) << "stop after failed assertions\n"; + s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "scfl,--" DOCTEST_OPTIONS_PREFIX_DISPLAY "subcase-filter-levels= " + << Whitespace(sizePrefixDisplay*1) << "apply filters for the first levels\n"; + s << Color::Cyan << "\n[doctest] " << Color::None; + s << "Bool options - can be used like flags and true is assumed. Available:\n\n"; + s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "s, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "success= " + << Whitespace(sizePrefixDisplay*1) << "include successful assertions in output\n"; + s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "cs, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "case-sensitive= " + << Whitespace(sizePrefixDisplay*1) << "filters being treated as case sensitive\n"; + s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "e, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "exit= " + << Whitespace(sizePrefixDisplay*1) << "exits after the tests finish\n"; + s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "d, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "duration= " + << Whitespace(sizePrefixDisplay*1) << "prints the time duration of each test\n"; + s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "m, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "minimal= " + << Whitespace(sizePrefixDisplay*1) << "minimal console output (only failures)\n"; + s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "q, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "quiet= " + << Whitespace(sizePrefixDisplay*1) << "no console output\n"; + s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "nt, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "no-throw= " + << Whitespace(sizePrefixDisplay*1) << "skips exceptions-related assert checks\n"; + s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "ne, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "no-exitcode= " + << Whitespace(sizePrefixDisplay*1) << "returns (or exits) always with success\n"; + s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "nr, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "no-run= " + << Whitespace(sizePrefixDisplay*1) << "skips all runtime doctest operations\n"; + s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "ni, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "no-intro= " + << Whitespace(sizePrefixDisplay*1) << "omit the framework intro in the output\n"; + s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "nv, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "no-version= " + << Whitespace(sizePrefixDisplay*1) << "omit the framework version in the output\n"; + s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "nc, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "no-colors= " + << Whitespace(sizePrefixDisplay*1) << "disables colors in output\n"; + s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "fc, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "force-colors= " + << Whitespace(sizePrefixDisplay*1) << "use colors even when not in a tty\n"; + s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "nb, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "no-breaks= " + << Whitespace(sizePrefixDisplay*1) << "disables breakpoints in debuggers\n"; + s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "ns, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "no-skip= " + << Whitespace(sizePrefixDisplay*1) << "don't skip test cases marked as skip\n"; + s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "gfl, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "gnu-file-line= " + << Whitespace(sizePrefixDisplay*1) << ":n: vs (n): for line numbers in output\n"; + s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "npf, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "no-path-filenames= " + << Whitespace(sizePrefixDisplay*1) << "only filenames and no paths in output\n"; + s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "nln, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "no-line-numbers= " + << Whitespace(sizePrefixDisplay*1) << "0 instead of real line numbers in output\n"; + // ================================================================================== << 79 + // clang-format on + + s << Color::Cyan << "\n[doctest] " << Color::None; + s << "for more information visit the project documentation\n\n"; + } + + void printRegisteredReporters() { + printVersion(); + auto printReporters = [this] (const reporterMap& reporters, const char* type) { + if(reporters.size()) { + s << Color::Cyan << "[doctest] " << Color::None << "listing all registered " << type << "\n"; + for(auto& curr : reporters) + s << "priority: " << std::setw(5) << curr.first.first + << " name: " << curr.first.second << "\n"; + } + }; + printReporters(getListeners(), "listeners"); + printReporters(getReporters(), "reporters"); + } + + // ========================================================================================= + // WHAT FOLLOWS ARE OVERRIDES OF THE VIRTUAL METHODS OF THE REPORTER INTERFACE + // ========================================================================================= + + void report_query(const QueryData& in) override { + if(opt.version) { + printVersion(); + } else if(opt.help) { + printHelp(); + } else if(opt.list_reporters) { + printRegisteredReporters(); + } else if(opt.count || opt.list_test_cases) { + if(opt.list_test_cases) { + s << Color::Cyan << "[doctest] " << Color::None + << "listing all test case names\n"; + separator_to_stream(); + } + + for(unsigned i = 0; i < in.num_data; ++i) + s << Color::None << in.data[i]->m_name << "\n"; + + separator_to_stream(); + + s << Color::Cyan << "[doctest] " << Color::None + << "unskipped test cases passing the current filters: " + << g_cs->numTestCasesPassingFilters << "\n"; + + } else if(opt.list_test_suites) { + s << Color::Cyan << "[doctest] " << Color::None << "listing all test suites\n"; + separator_to_stream(); + + for(unsigned i = 0; i < in.num_data; ++i) + s << Color::None << in.data[i]->m_test_suite << "\n"; + + separator_to_stream(); + + s << Color::Cyan << "[doctest] " << Color::None + << "unskipped test cases passing the current filters: " + << g_cs->numTestCasesPassingFilters << "\n"; + s << Color::Cyan << "[doctest] " << Color::None + << "test suites with unskipped test cases passing the current filters: " + << g_cs->numTestSuitesPassingFilters << "\n"; + } + } + + void test_run_start() override { + if(!opt.minimal) + printIntro(); + } + + void test_run_end(const TestRunStats& p) override { + if(opt.minimal && p.numTestCasesFailed == 0) + return; + + separator_to_stream(); + s << std::dec; + + auto totwidth = int(std::ceil(log10(static_cast(std::max(p.numTestCasesPassingFilters, static_cast(p.numAsserts))) + 1))); + auto passwidth = int(std::ceil(log10(static_cast(std::max(p.numTestCasesPassingFilters - p.numTestCasesFailed, static_cast(p.numAsserts - p.numAssertsFailed))) + 1))); + auto failwidth = int(std::ceil(log10(static_cast(std::max(p.numTestCasesFailed, static_cast(p.numAssertsFailed))) + 1))); + const bool anythingFailed = p.numTestCasesFailed > 0 || p.numAssertsFailed > 0; + s << Color::Cyan << "[doctest] " << Color::None << "test cases: " << std::setw(totwidth) + << p.numTestCasesPassingFilters << " | " + << ((p.numTestCasesPassingFilters == 0 || anythingFailed) ? Color::None : + Color::Green) + << std::setw(passwidth) << p.numTestCasesPassingFilters - p.numTestCasesFailed << " passed" + << Color::None << " | " << (p.numTestCasesFailed > 0 ? Color::Red : Color::None) + << std::setw(failwidth) << p.numTestCasesFailed << " failed" << Color::None << " |"; + if(opt.no_skipped_summary == false) { + const int numSkipped = p.numTestCases - p.numTestCasesPassingFilters; + s << " " << (numSkipped == 0 ? Color::None : Color::Yellow) << numSkipped + << " skipped" << Color::None; + } + s << "\n"; + s << Color::Cyan << "[doctest] " << Color::None << "assertions: " << std::setw(totwidth) + << p.numAsserts << " | " + << ((p.numAsserts == 0 || anythingFailed) ? Color::None : Color::Green) + << std::setw(passwidth) << (p.numAsserts - p.numAssertsFailed) << " passed" << Color::None + << " | " << (p.numAssertsFailed > 0 ? Color::Red : Color::None) << std::setw(failwidth) + << p.numAssertsFailed << " failed" << Color::None << " |\n"; + s << Color::Cyan << "[doctest] " << Color::None + << "Status: " << (p.numTestCasesFailed > 0 ? Color::Red : Color::Green) + << ((p.numTestCasesFailed > 0) ? "FAILURE!" : "SUCCESS!") << Color::None << std::endl; + } + + void test_case_start(const TestCaseData& in) override { + hasLoggedCurrentTestStart = false; + tc = ∈ + subcasesStack.clear(); + currentSubcaseLevel = 0; + } + + void test_case_reenter(const TestCaseData&) override { + subcasesStack.clear(); + } + + void test_case_end(const CurrentTestCaseStats& st) override { + if(tc->m_no_output) + return; + + // log the preamble of the test case only if there is something + // else to print - something other than that an assert has failed + if(opt.duration || + (st.failure_flags && st.failure_flags != static_cast(TestCaseFailureReason::AssertFailure))) + logTestStart(); + + if(opt.duration) + s << Color::None << std::setprecision(6) << std::fixed << st.seconds + << " s: " << tc->m_name << "\n"; + + if(st.failure_flags & TestCaseFailureReason::Timeout) + s << Color::Red << "Test case exceeded time limit of " << std::setprecision(6) + << std::fixed << tc->m_timeout << "!\n"; + + if(st.failure_flags & TestCaseFailureReason::ShouldHaveFailedButDidnt) { + s << Color::Red << "Should have failed but didn't! Marking it as failed!\n"; + } else if(st.failure_flags & TestCaseFailureReason::ShouldHaveFailedAndDid) { + s << Color::Yellow << "Failed as expected so marking it as not failed\n"; + } else if(st.failure_flags & TestCaseFailureReason::CouldHaveFailedAndDid) { + s << Color::Yellow << "Allowed to fail so marking it as not failed\n"; + } else if(st.failure_flags & TestCaseFailureReason::DidntFailExactlyNumTimes) { + s << Color::Red << "Didn't fail exactly " << tc->m_expected_failures + << " times so marking it as failed!\n"; + } else if(st.failure_flags & TestCaseFailureReason::FailedExactlyNumTimes) { + s << Color::Yellow << "Failed exactly " << tc->m_expected_failures + << " times as expected so marking it as not failed!\n"; + } + if(st.failure_flags & TestCaseFailureReason::TooManyFailedAsserts) { + s << Color::Red << "Aborting - too many failed asserts!\n"; + } + s << Color::None; // lgtm [cpp/useless-expression] + } + + void test_case_exception(const TestCaseException& e) override { + DOCTEST_LOCK_MUTEX(mutex) + if(tc->m_no_output) + return; + + logTestStart(); + + file_line_to_stream(tc->m_file.c_str(), tc->m_line, " "); + successOrFailColoredStringToStream(false, e.is_crash ? assertType::is_require : + assertType::is_check); + s << Color::Red << (e.is_crash ? "test case CRASHED: " : "test case THREW exception: ") + << Color::Cyan << e.error_string << "\n"; + + int num_stringified_contexts = get_num_stringified_contexts(); + if(num_stringified_contexts) { + auto stringified_contexts = get_stringified_contexts(); + s << Color::None << " logged: "; + for(int i = num_stringified_contexts; i > 0; --i) { + s << (i == num_stringified_contexts ? "" : " ") + << stringified_contexts[i - 1] << "\n"; + } + } + s << "\n" << Color::None; + } + + void subcase_start(const SubcaseSignature& subc) override { + subcasesStack.push_back(subc); + ++currentSubcaseLevel; + hasLoggedCurrentTestStart = false; + } + + void subcase_end() override { + --currentSubcaseLevel; + hasLoggedCurrentTestStart = false; + } + + void log_assert(const AssertData& rb) override { + if((!rb.m_failed && !opt.success) || tc->m_no_output) + return; + + DOCTEST_LOCK_MUTEX(mutex) + + logTestStart(); + + file_line_to_stream(rb.m_file, rb.m_line, " "); + successOrFailColoredStringToStream(!rb.m_failed, rb.m_at); + + fulltext_log_assert_to_stream(s, rb); + + log_contexts(); + } + + void log_message(const MessageData& mb) override { + if(tc->m_no_output) + return; + + DOCTEST_LOCK_MUTEX(mutex) + + logTestStart(); + + file_line_to_stream(mb.m_file, mb.m_line, " "); + s << getSuccessOrFailColor(false, mb.m_severity) + << getSuccessOrFailString(mb.m_severity & assertType::is_warn, mb.m_severity, + "MESSAGE") << ": "; + s << Color::None << mb.m_string << "\n"; + log_contexts(); + } + + void test_case_skipped(const TestCaseData&) override {} + }; + + DOCTEST_REGISTER_REPORTER("console", 0, ConsoleReporter); + +#ifdef DOCTEST_PLATFORM_WINDOWS + struct DebugOutputWindowReporter : public ConsoleReporter + { + DOCTEST_THREAD_LOCAL static std::ostringstream oss; + + DebugOutputWindowReporter(const ContextOptions& co) + : ConsoleReporter(co, oss) {} + +#define DOCTEST_DEBUG_OUTPUT_REPORTER_OVERRIDE(func, type, arg) \ + void func(type arg) override { \ + bool with_col = g_no_colors; \ + g_no_colors = false; \ + ConsoleReporter::func(arg); \ + if(oss.tellp() != std::streampos{}) { \ + DOCTEST_OUTPUT_DEBUG_STRING(oss.str().c_str()); \ + oss.str(""); \ + } \ + g_no_colors = with_col; \ + } + + DOCTEST_DEBUG_OUTPUT_REPORTER_OVERRIDE(test_run_start, DOCTEST_EMPTY, DOCTEST_EMPTY) + DOCTEST_DEBUG_OUTPUT_REPORTER_OVERRIDE(test_run_end, const TestRunStats&, in) + DOCTEST_DEBUG_OUTPUT_REPORTER_OVERRIDE(test_case_start, const TestCaseData&, in) + DOCTEST_DEBUG_OUTPUT_REPORTER_OVERRIDE(test_case_reenter, const TestCaseData&, in) + DOCTEST_DEBUG_OUTPUT_REPORTER_OVERRIDE(test_case_end, const CurrentTestCaseStats&, in) + DOCTEST_DEBUG_OUTPUT_REPORTER_OVERRIDE(test_case_exception, const TestCaseException&, in) + DOCTEST_DEBUG_OUTPUT_REPORTER_OVERRIDE(subcase_start, const SubcaseSignature&, in) + DOCTEST_DEBUG_OUTPUT_REPORTER_OVERRIDE(subcase_end, DOCTEST_EMPTY, DOCTEST_EMPTY) + DOCTEST_DEBUG_OUTPUT_REPORTER_OVERRIDE(log_assert, const AssertData&, in) + DOCTEST_DEBUG_OUTPUT_REPORTER_OVERRIDE(log_message, const MessageData&, in) + DOCTEST_DEBUG_OUTPUT_REPORTER_OVERRIDE(test_case_skipped, const TestCaseData&, in) + }; + + DOCTEST_THREAD_LOCAL std::ostringstream DebugOutputWindowReporter::oss; +#endif // DOCTEST_PLATFORM_WINDOWS + + // the implementation of parseOption() + bool parseOptionImpl(int argc, const char* const* argv, const char* pattern, String* value) { + // going from the end to the beginning and stopping on the first occurrence from the end + for(int i = argc; i > 0; --i) { + auto index = i - 1; + auto temp = std::strstr(argv[index], pattern); + if(temp && (value || strlen(temp) == strlen(pattern))) { //!OCLINT prefer early exits and continue + // eliminate matches in which the chars before the option are not '-' + bool noBadCharsFound = true; + auto curr = argv[index]; + while(curr != temp) { + if(*curr++ != '-') { + noBadCharsFound = false; + break; + } + } + if(noBadCharsFound && argv[index][0] == '-') { + if(value) { + // parsing the value of an option + temp += strlen(pattern); + const unsigned len = strlen(temp); + if(len) { + *value = temp; + return true; + } + } else { + // just a flag - no value + return true; + } + } + } + } + return false; + } + + // parses an option and returns the string after the '=' character + bool parseOption(int argc, const char* const* argv, const char* pattern, String* value = nullptr, + const String& defaultVal = String()) { + if(value) + *value = defaultVal; +#ifndef DOCTEST_CONFIG_NO_UNPREFIXED_OPTIONS + // offset (normally 3 for "dt-") to skip prefix + if(parseOptionImpl(argc, argv, pattern + strlen(DOCTEST_CONFIG_OPTIONS_PREFIX), value)) + return true; +#endif // DOCTEST_CONFIG_NO_UNPREFIXED_OPTIONS + return parseOptionImpl(argc, argv, pattern, value); + } + + // locates a flag on the command line + bool parseFlag(int argc, const char* const* argv, const char* pattern) { + return parseOption(argc, argv, pattern); + } + + // parses a comma separated list of words after a pattern in one of the arguments in argv + bool parseCommaSepArgs(int argc, const char* const* argv, const char* pattern, + std::vector& res) { + String filtersString; + if(parseOption(argc, argv, pattern, &filtersString)) { + // tokenize with "," as a separator, unless escaped with backslash + std::ostringstream s; + auto flush = [&s, &res]() { + auto string = s.str(); + if(string.size() > 0) { + res.push_back(string.c_str()); + } + s.str(""); + }; + + bool seenBackslash = false; + const char* current = filtersString.c_str(); + const char* end = current + strlen(current); + while(current != end) { + char character = *current++; + if(seenBackslash) { + seenBackslash = false; + if(character == ',' || character == '\\') { + s.put(character); + continue; + } + s.put('\\'); + } + if(character == '\\') { + seenBackslash = true; + } else if(character == ',') { + flush(); + } else { + s.put(character); + } + } + + if(seenBackslash) { + s.put('\\'); + } + flush(); + return true; + } + return false; + } + + enum optionType + { + option_bool, + option_int + }; + + // parses an int/bool option from the command line + bool parseIntOption(int argc, const char* const* argv, const char* pattern, optionType type, + int& res) { + String parsedValue; + if(!parseOption(argc, argv, pattern, &parsedValue)) + return false; + + if(type) { + // integer + // TODO: change this to use std::stoi or something else! currently it uses undefined behavior - assumes '0' on failed parse... + int theInt = std::atoi(parsedValue.c_str()); + if (theInt != 0) { + res = theInt; //!OCLINT parameter reassignment + return true; + } + } else { + // boolean + const char positive[][5] = { "1", "true", "on", "yes" }; // 5 - strlen("true") + 1 + const char negative[][6] = { "0", "false", "off", "no" }; // 6 - strlen("false") + 1 + + // if the value matches any of the positive/negative possibilities + for (unsigned i = 0; i < 4; i++) { + if (parsedValue.compare(positive[i], true) == 0) { + res = 1; //!OCLINT parameter reassignment + return true; + } + if (parsedValue.compare(negative[i], true) == 0) { + res = 0; //!OCLINT parameter reassignment + return true; + } + } + } + return false; + } +} // namespace + +Context::Context(int argc, const char* const* argv) + : p(new detail::ContextState) { + parseArgs(argc, argv, true); + if(argc) + p->binary_name = argv[0]; +} + +Context::~Context() { + if(g_cs == p) + g_cs = nullptr; + delete p; +} + +void Context::applyCommandLine(int argc, const char* const* argv) { + parseArgs(argc, argv); + if(argc) + p->binary_name = argv[0]; +} + +// parses args +void Context::parseArgs(int argc, const char* const* argv, bool withDefaults) { + using namespace detail; + + // clang-format off + parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "source-file=", p->filters[0]); + parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "sf=", p->filters[0]); + parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "source-file-exclude=",p->filters[1]); + parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "sfe=", p->filters[1]); + parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "test-suite=", p->filters[2]); + parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "ts=", p->filters[2]); + parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "test-suite-exclude=", p->filters[3]); + parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "tse=", p->filters[3]); + parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "test-case=", p->filters[4]); + parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "tc=", p->filters[4]); + parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "test-case-exclude=", p->filters[5]); + parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "tce=", p->filters[5]); + parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "subcase=", p->filters[6]); + parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "sc=", p->filters[6]); + parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "subcase-exclude=", p->filters[7]); + parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "sce=", p->filters[7]); + parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "reporters=", p->filters[8]); + parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "r=", p->filters[8]); + // clang-format on + + int intRes = 0; + String strRes; + +#define DOCTEST_PARSE_AS_BOOL_OR_FLAG(name, sname, var, default) \ + if(parseIntOption(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX name "=", option_bool, intRes) || \ + parseIntOption(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX sname "=", option_bool, intRes)) \ + p->var = static_cast(intRes); \ + else if(parseFlag(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX name) || \ + parseFlag(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX sname)) \ + p->var = true; \ + else if(withDefaults) \ + p->var = default + +#define DOCTEST_PARSE_INT_OPTION(name, sname, var, default) \ + if(parseIntOption(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX name "=", option_int, intRes) || \ + parseIntOption(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX sname "=", option_int, intRes)) \ + p->var = intRes; \ + else if(withDefaults) \ + p->var = default + +#define DOCTEST_PARSE_STR_OPTION(name, sname, var, default) \ + if(parseOption(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX name "=", &strRes, default) || \ + parseOption(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX sname "=", &strRes, default) || \ + withDefaults) \ + p->var = strRes + + // clang-format off + DOCTEST_PARSE_STR_OPTION("out", "o", out, ""); + DOCTEST_PARSE_STR_OPTION("order-by", "ob", order_by, "file"); + DOCTEST_PARSE_INT_OPTION("rand-seed", "rs", rand_seed, 0); + + DOCTEST_PARSE_INT_OPTION("first", "f", first, 0); + DOCTEST_PARSE_INT_OPTION("last", "l", last, UINT_MAX); + + DOCTEST_PARSE_INT_OPTION("abort-after", "aa", abort_after, 0); + DOCTEST_PARSE_INT_OPTION("subcase-filter-levels", "scfl", subcase_filter_levels, INT_MAX); + + DOCTEST_PARSE_AS_BOOL_OR_FLAG("success", "s", success, false); + DOCTEST_PARSE_AS_BOOL_OR_FLAG("case-sensitive", "cs", case_sensitive, false); + DOCTEST_PARSE_AS_BOOL_OR_FLAG("exit", "e", exit, false); + DOCTEST_PARSE_AS_BOOL_OR_FLAG("duration", "d", duration, false); + DOCTEST_PARSE_AS_BOOL_OR_FLAG("minimal", "m", minimal, false); + DOCTEST_PARSE_AS_BOOL_OR_FLAG("quiet", "q", quiet, false); + DOCTEST_PARSE_AS_BOOL_OR_FLAG("no-throw", "nt", no_throw, false); + DOCTEST_PARSE_AS_BOOL_OR_FLAG("no-exitcode", "ne", no_exitcode, false); + DOCTEST_PARSE_AS_BOOL_OR_FLAG("no-run", "nr", no_run, false); + DOCTEST_PARSE_AS_BOOL_OR_FLAG("no-intro", "ni", no_intro, false); + DOCTEST_PARSE_AS_BOOL_OR_FLAG("no-version", "nv", no_version, false); + DOCTEST_PARSE_AS_BOOL_OR_FLAG("no-colors", "nc", no_colors, false); + DOCTEST_PARSE_AS_BOOL_OR_FLAG("force-colors", "fc", force_colors, false); + DOCTEST_PARSE_AS_BOOL_OR_FLAG("no-breaks", "nb", no_breaks, false); + DOCTEST_PARSE_AS_BOOL_OR_FLAG("no-skip", "ns", no_skip, false); + DOCTEST_PARSE_AS_BOOL_OR_FLAG("gnu-file-line", "gfl", gnu_file_line, !bool(DOCTEST_MSVC)); + DOCTEST_PARSE_AS_BOOL_OR_FLAG("no-path-filenames", "npf", no_path_in_filenames, false); + DOCTEST_PARSE_AS_BOOL_OR_FLAG("no-line-numbers", "nln", no_line_numbers, false); + DOCTEST_PARSE_AS_BOOL_OR_FLAG("no-debug-output", "ndo", no_debug_output, false); + DOCTEST_PARSE_AS_BOOL_OR_FLAG("no-skipped-summary", "nss", no_skipped_summary, false); + DOCTEST_PARSE_AS_BOOL_OR_FLAG("no-time-in-output", "ntio", no_time_in_output, false); + // clang-format on + + if(withDefaults) { + p->help = false; + p->version = false; + p->count = false; + p->list_test_cases = false; + p->list_test_suites = false; + p->list_reporters = false; + } + if(parseFlag(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "help") || + parseFlag(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "h") || + parseFlag(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "?")) { + p->help = true; + p->exit = true; + } + if(parseFlag(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "version") || + parseFlag(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "v")) { + p->version = true; + p->exit = true; + } + if(parseFlag(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "count") || + parseFlag(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "c")) { + p->count = true; + p->exit = true; + } + if(parseFlag(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "list-test-cases") || + parseFlag(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "ltc")) { + p->list_test_cases = true; + p->exit = true; + } + if(parseFlag(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "list-test-suites") || + parseFlag(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "lts")) { + p->list_test_suites = true; + p->exit = true; + } + if(parseFlag(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "list-reporters") || + parseFlag(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "lr")) { + p->list_reporters = true; + p->exit = true; + } +} + +// allows the user to add procedurally to the filters from the command line +void Context::addFilter(const char* filter, const char* value) { setOption(filter, value); } + +// allows the user to clear all filters from the command line +void Context::clearFilters() { + for(auto& curr : p->filters) + curr.clear(); +} + +// allows the user to override procedurally the bool options from the command line +void Context::setOption(const char* option, bool value) { + setOption(option, value ? "true" : "false"); +} + +// allows the user to override procedurally the int options from the command line +void Context::setOption(const char* option, int value) { + setOption(option, toString(value).c_str()); +} + +// allows the user to override procedurally the string options from the command line +void Context::setOption(const char* option, const char* value) { + auto argv = String("-") + option + "=" + value; + auto lvalue = argv.c_str(); + parseArgs(1, &lvalue); +} + +// users should query this in their main() and exit the program if true +bool Context::shouldExit() { return p->exit; } + +void Context::setAsDefaultForAssertsOutOfTestCases() { g_cs = p; } + +void Context::setAssertHandler(detail::assert_handler ah) { p->ah = ah; } + +void Context::setCout(std::ostream* out) { p->cout = out; } + +static class DiscardOStream : public std::ostream +{ +private: + class : public std::streambuf + { + private: + // allowing some buffering decreases the amount of calls to overflow + char buf[1024]; + + protected: + std::streamsize xsputn(const char_type*, std::streamsize count) override { return count; } + + int_type overflow(int_type ch) override { + setp(std::begin(buf), std::end(buf)); + return traits_type::not_eof(ch); + } + } discardBuf; + +public: + DiscardOStream() + : std::ostream(&discardBuf) {} +} discardOut; + +// the main function that does all the filtering and test running +int Context::run() { + using namespace detail; + + // save the old context state in case such was setup - for using asserts out of a testing context + auto old_cs = g_cs; + // this is the current contest + g_cs = p; + is_running_in_test = true; + + g_no_colors = p->no_colors; + p->resetRunData(); + + std::fstream fstr; + if(p->cout == nullptr) { + if(p->quiet) { + p->cout = &discardOut; + } else if(p->out.size()) { + // to a file if specified + fstr.open(p->out.c_str(), std::fstream::out); + p->cout = &fstr; + } else { +#ifndef DOCTEST_CONFIG_NO_INCLUDE_IOSTREAM + // stdout by default + p->cout = &std::cout; +#else // DOCTEST_CONFIG_NO_INCLUDE_IOSTREAM + return EXIT_FAILURE; +#endif // DOCTEST_CONFIG_NO_INCLUDE_IOSTREAM + } + } + + FatalConditionHandler::allocateAltStackMem(); + + auto cleanup_and_return = [&]() { + FatalConditionHandler::freeAltStackMem(); + + if(fstr.is_open()) + fstr.close(); + + // restore context + g_cs = old_cs; + is_running_in_test = false; + + // we have to free the reporters which were allocated when the run started + for(auto& curr : p->reporters_currently_used) + delete curr; + p->reporters_currently_used.clear(); + + if(p->numTestCasesFailed && !p->no_exitcode) + return EXIT_FAILURE; + return EXIT_SUCCESS; + }; + + // setup default reporter if none is given through the command line + if(p->filters[8].empty()) + p->filters[8].push_back("console"); + + // check to see if any of the registered reporters has been selected + for(auto& curr : getReporters()) { + if(matchesAny(curr.first.second.c_str(), p->filters[8], false, p->case_sensitive)) + p->reporters_currently_used.push_back(curr.second(*g_cs)); + } + + // TODO: check if there is nothing in reporters_currently_used + + // prepend all listeners + for(auto& curr : getListeners()) + p->reporters_currently_used.insert(p->reporters_currently_used.begin(), curr.second(*g_cs)); + +#ifdef DOCTEST_PLATFORM_WINDOWS + if(isDebuggerActive() && p->no_debug_output == false) + p->reporters_currently_used.push_back(new DebugOutputWindowReporter(*g_cs)); +#endif // DOCTEST_PLATFORM_WINDOWS + + // handle version, help and no_run + if(p->no_run || p->version || p->help || p->list_reporters) { + DOCTEST_ITERATE_THROUGH_REPORTERS(report_query, QueryData()); + + return cleanup_and_return(); + } + + std::vector testArray; + for(auto& curr : getRegisteredTests()) + testArray.push_back(&curr); + p->numTestCases = testArray.size(); + + // sort the collected records + if(!testArray.empty()) { + if(p->order_by.compare("file", true) == 0) { + std::sort(testArray.begin(), testArray.end(), fileOrderComparator); + } else if(p->order_by.compare("suite", true) == 0) { + std::sort(testArray.begin(), testArray.end(), suiteOrderComparator); + } else if(p->order_by.compare("name", true) == 0) { + std::sort(testArray.begin(), testArray.end(), nameOrderComparator); + } else if(p->order_by.compare("rand", true) == 0) { + std::srand(p->rand_seed); + + // random_shuffle implementation + const auto first = &testArray[0]; + for(size_t i = testArray.size() - 1; i > 0; --i) { + int idxToSwap = std::rand() % (i + 1); + + const auto temp = first[i]; + + first[i] = first[idxToSwap]; + first[idxToSwap] = temp; + } + } else if(p->order_by.compare("none", true) == 0) { + // means no sorting - beneficial for death tests which call into the executable + // with a specific test case in mind - we don't want to slow down the startup times + } + } + + std::set testSuitesPassingFilt; + + bool query_mode = p->count || p->list_test_cases || p->list_test_suites; + std::vector queryResults; + + if(!query_mode) + DOCTEST_ITERATE_THROUGH_REPORTERS(test_run_start, DOCTEST_EMPTY); + + // invoke the registered functions if they match the filter criteria (or just count them) + for(auto& curr : testArray) { + const auto& tc = *curr; + + bool skip_me = false; + if(tc.m_skip && !p->no_skip) + skip_me = true; + + if(!matchesAny(tc.m_file.c_str(), p->filters[0], true, p->case_sensitive)) + skip_me = true; + if(matchesAny(tc.m_file.c_str(), p->filters[1], false, p->case_sensitive)) + skip_me = true; + if(!matchesAny(tc.m_test_suite, p->filters[2], true, p->case_sensitive)) + skip_me = true; + if(matchesAny(tc.m_test_suite, p->filters[3], false, p->case_sensitive)) + skip_me = true; + if(!matchesAny(tc.m_name, p->filters[4], true, p->case_sensitive)) + skip_me = true; + if(matchesAny(tc.m_name, p->filters[5], false, p->case_sensitive)) + skip_me = true; + + if(!skip_me) + p->numTestCasesPassingFilters++; + + // skip the test if it is not in the execution range + if((p->last < p->numTestCasesPassingFilters && p->first <= p->last) || + (p->first > p->numTestCasesPassingFilters)) + skip_me = true; + + if(skip_me) { + if(!query_mode) + DOCTEST_ITERATE_THROUGH_REPORTERS(test_case_skipped, tc); + continue; + } + + // do not execute the test if we are to only count the number of filter passing tests + if(p->count) + continue; + + // print the name of the test and don't execute it + if(p->list_test_cases) { + queryResults.push_back(&tc); + continue; + } + + // print the name of the test suite if not done already and don't execute it + if(p->list_test_suites) { + if((testSuitesPassingFilt.count(tc.m_test_suite) == 0) && tc.m_test_suite[0] != '\0') { + queryResults.push_back(&tc); + testSuitesPassingFilt.insert(tc.m_test_suite); + p->numTestSuitesPassingFilters++; + } + continue; + } + + // execute the test if it passes all the filtering + { + p->currentTest = &tc; + + p->failure_flags = TestCaseFailureReason::None; + p->seconds = 0; + + // reset atomic counters + p->numAssertsFailedCurrentTest_atomic = 0; + p->numAssertsCurrentTest_atomic = 0; + + p->fullyTraversedSubcases.clear(); + + DOCTEST_ITERATE_THROUGH_REPORTERS(test_case_start, tc); + + p->timer.start(); + + bool run_test = true; + + do { + // reset some of the fields for subcases (except for the set of fully passed ones) + p->reachedLeaf = false; + // May not be empty if previous subcase exited via exception. + p->subcaseStack.clear(); + p->currentSubcaseDepth = 0; + + p->shouldLogCurrentException = true; + + // reset stuff for logging with INFO() + p->stringifiedContexts.clear(); + +#ifndef DOCTEST_CONFIG_NO_EXCEPTIONS + try { +#endif // DOCTEST_CONFIG_NO_EXCEPTIONS +// MSVC 2015 diagnoses fatalConditionHandler as unused (because reset() is a static method) +DOCTEST_MSVC_SUPPRESS_WARNING_WITH_PUSH(4101) // unreferenced local variable + FatalConditionHandler fatalConditionHandler; // Handle signals + // execute the test + tc.m_test(); + fatalConditionHandler.reset(); +DOCTEST_MSVC_SUPPRESS_WARNING_POP +#ifndef DOCTEST_CONFIG_NO_EXCEPTIONS + } catch(const TestFailureException&) { + p->failure_flags |= TestCaseFailureReason::AssertFailure; + } catch(...) { + DOCTEST_ITERATE_THROUGH_REPORTERS(test_case_exception, + {translateActiveException(), false}); + p->failure_flags |= TestCaseFailureReason::Exception; + } +#endif // DOCTEST_CONFIG_NO_EXCEPTIONS + + // exit this loop if enough assertions have failed - even if there are more subcases + if(p->abort_after > 0 && + p->numAssertsFailed + p->numAssertsFailedCurrentTest_atomic >= p->abort_after) { + run_test = false; + p->failure_flags |= TestCaseFailureReason::TooManyFailedAsserts; + } + + if(!p->nextSubcaseStack.empty() && run_test) + DOCTEST_ITERATE_THROUGH_REPORTERS(test_case_reenter, tc); + if(p->nextSubcaseStack.empty()) + run_test = false; + } while(run_test); + + p->finalizeTestCaseData(); + + DOCTEST_ITERATE_THROUGH_REPORTERS(test_case_end, *g_cs); + + p->currentTest = nullptr; + + // stop executing tests if enough assertions have failed + if(p->abort_after > 0 && p->numAssertsFailed >= p->abort_after) + break; + } + } + + if(!query_mode) { + DOCTEST_ITERATE_THROUGH_REPORTERS(test_run_end, *g_cs); + } else { + QueryData qdata; + qdata.run_stats = g_cs; + qdata.data = queryResults.data(); + qdata.num_data = unsigned(queryResults.size()); + DOCTEST_ITERATE_THROUGH_REPORTERS(report_query, qdata); + } + + return cleanup_and_return(); +} + +DOCTEST_DEFINE_INTERFACE(IReporter) + +int IReporter::get_num_active_contexts() { return detail::g_infoContexts.size(); } +const IContextScope* const* IReporter::get_active_contexts() { + return get_num_active_contexts() ? &detail::g_infoContexts[0] : nullptr; +} + +int IReporter::get_num_stringified_contexts() { return detail::g_cs->stringifiedContexts.size(); } +const String* IReporter::get_stringified_contexts() { + return get_num_stringified_contexts() ? &detail::g_cs->stringifiedContexts[0] : nullptr; +} + +namespace detail { + void registerReporterImpl(const char* name, int priority, reporterCreatorFunc c, bool isReporter) { + if(isReporter) + getReporters().insert(reporterMap::value_type(reporterMap::key_type(priority, name), c)); + else + getListeners().insert(reporterMap::value_type(reporterMap::key_type(priority, name), c)); + } +} // namespace detail + +} // namespace doctest + +#endif // DOCTEST_CONFIG_DISABLE + +#ifdef DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN +DOCTEST_MSVC_SUPPRESS_WARNING_WITH_PUSH(4007) // 'function' : must be 'attribute' - see issue #182 +int main(int argc, char** argv) { return doctest::Context(argc, argv).run(); } +DOCTEST_MSVC_SUPPRESS_WARNING_POP +#endif // DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN + +DOCTEST_CLANG_SUPPRESS_WARNING_POP +DOCTEST_MSVC_SUPPRESS_WARNING_POP +DOCTEST_GCC_SUPPRESS_WARNING_POP + +DOCTEST_SUPPRESS_COMMON_WARNINGS_POP + +#endif // DOCTEST_LIBRARY_IMPLEMENTATION +#endif // DOCTEST_CONFIG_IMPLEMENT + +#ifdef DOCTEST_UNDEF_WIN32_LEAN_AND_MEAN +#undef WIN32_LEAN_AND_MEAN +#undef DOCTEST_UNDEF_WIN32_LEAN_AND_MEAN +#endif // DOCTEST_UNDEF_WIN32_LEAN_AND_MEAN + +#ifdef DOCTEST_UNDEF_NOMINMAX +#undef NOMINMAX +#undef DOCTEST_UNDEF_NOMINMAX +#endif // DOCTEST_UNDEF_NOMINMAX