Files
Library/include/Void/Containers/Ring.hpp
T
faumarayandClaude Fable 5 28b94883fd Restructure into umbrella modules (~55 -> 16 targets)
Headers move, CMake targets merge, C++ namespaces stay unchanged:
- Core: Scope, Lazy, Counted, Flags, Hash, Bits, Uuid, TypeList, TypeMap, Variant
- Functional: Pipeline, Either, Result, Retry
- Containers: Ring, Pool, PriorityQueue, LRU, Trie, Graph, DisjointSet, Bitset, Interval
- Math: +Matrix, Numeric, Random, Histogram
- Text: Str, Format, Tokenizer, Diff, Encoding, Semver
- Data: Json, Csv, Ini
- Async: Coro, Concurrency, EventBus, Observable
- Time: +Bench
- Log: Log facade + Logging framework (facade now header-only, breaking
  the Stacktrace<->Log link cycle the merge would have created)
- System: FileSystem + Process
- Configuration: +Argparse
- Unchanged: Stacktrace, Plugin, StateMachine, Testing, TestingMock, Detail

Module system fixes:
- OPTIONAL_DEPS resolution deferred to void_finalize_modules() so it no
  longer depends on the alphabetical discovery order of src/ subdirs
  (Testing -> Text would have been silently dropped).
- Every header-only module now has a tracked module.cmake; previously the
  empty src/<Name> marker dirs were untracked, so a fresh clone would have
  silently skipped those modules.
- VOID_HAS_LOGGING/CONCURRENCY/STR consumers renamed to LOG/ASYNC/TEXT.

Tests move to tests/standalone/<Umbrella>/<Feature>.cpp (Result suite files
prefixed: ResultBasic etc.). Test count verified identical (831) before and
after. README/CLAUDE.md module tables updated.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-12 18:50:02 +03:00

180 lines
5.9 KiB
C++

#pragma once
#include <atomic>
#include <cassert>
#include <cstddef>
#include <new>
#include <optional>
#include <type_traits>
namespace Void::Ring
{
// ── SpscRing<T, N> ────────────────────────────────────────────────────────────
// Single-producer / single-consumer lock-free ring buffer.
// Capacity is N (must be a power of two). The buffer holds at most N-1 items.
// All operations are wait-free.
template <typename T, std::size_t N>
requires(N >= 2 && (N & (N - 1)) == 0) // power of two
class SpscRing
{
public:
SpscRing() = default;
SpscRing(const SpscRing&) = delete;
SpscRing& operator=(const SpscRing&) = delete;
// Producer side — push returns false when the buffer is full.
[[nodiscard]] bool push(const T& val)
noexcept(std::is_nothrow_copy_constructible_v<T>)
{
const std::size_t head = head_.load(std::memory_order_relaxed);
const std::size_t next = (head + 1) & mask_;
if (next == tail_.load(std::memory_order_acquire)) return false;
std::construct_at(slot_ptr(head), val);
head_.store(next, std::memory_order_release);
return true;
}
[[nodiscard]] bool push(T&& val)
noexcept(std::is_nothrow_move_constructible_v<T>)
{
const std::size_t head = head_.load(std::memory_order_relaxed);
const std::size_t next = (head + 1) & mask_;
if (next == tail_.load(std::memory_order_acquire)) return false;
std::construct_at(slot_ptr(head), std::move(val));
head_.store(next, std::memory_order_release);
return true;
}
// Consumer side — pop returns nullopt when the buffer is empty.
[[nodiscard]] std::optional<T> pop() noexcept(
std::is_nothrow_move_constructible_v<T> &&
std::is_nothrow_destructible_v<T>)
{
const std::size_t tail = tail_.load(std::memory_order_relaxed);
if (tail == head_.load(std::memory_order_acquire)) return std::nullopt;
T val{std::move(*slot_ptr(tail))};
std::destroy_at(slot_ptr(tail));
tail_.store((tail + 1) & mask_, std::memory_order_release);
return val;
}
[[nodiscard]] bool empty() const noexcept
{
return tail_.load(std::memory_order_acquire) ==
head_.load(std::memory_order_acquire);
}
[[nodiscard]] bool full() const noexcept
{
const std::size_t next =
(head_.load(std::memory_order_acquire) + 1) & mask_;
return next == tail_.load(std::memory_order_acquire);
}
[[nodiscard]] static constexpr std::size_t capacity() noexcept
{
return N - 1;
}
private:
T* slot_ptr(std::size_t i) noexcept
{
return std::launder(reinterpret_cast<T*>(&storage_[i]));
}
static constexpr std::size_t mask_ = N - 1;
struct alignas(alignof(T)) Slot
{
std::byte storage[sizeof(T)];
};
// Pad to separate cache lines to avoid false sharing.
alignas(64) std::atomic<std::size_t> head_{0};
alignas(64) std::atomic<std::size_t> tail_{0};
Slot storage_[N];
};
// ── MpscRing<T, N> ────────────────────────────────────────────────────────────
// Multi-producer / single-consumer ring buffer using a compare-exchange loop
// on the head pointer. Consumer is still single-threaded.
template <typename T, std::size_t N>
requires(N >= 2 && (N & (N - 1)) == 0)
class MpscRing
{
public:
MpscRing() = default;
MpscRing(const MpscRing&) = delete;
MpscRing& operator=(const MpscRing&) = delete;
[[nodiscard]] bool push(T val) noexcept(
std::is_nothrow_move_constructible_v<T>)
{
std::size_t head = head_.load(std::memory_order_relaxed);
std::size_t next;
do {
next = (head + 1) & mask_;
if (next == tail_.load(std::memory_order_acquire)) return false;
} while (!head_.compare_exchange_weak(head, next,
std::memory_order_acq_rel,
std::memory_order_relaxed));
std::construct_at(slot_ptr(head), std::move(val));
// Signal that this slot is ready.
ready_[head].store(true, std::memory_order_release);
return true;
}
[[nodiscard]] std::optional<T> pop() noexcept(
std::is_nothrow_move_constructible_v<T>)
{
const std::size_t tail = tail_.load(std::memory_order_relaxed);
if (tail == head_.load(std::memory_order_acquire)) return std::nullopt;
// Spin until the producing thread has written the value.
while (!ready_[tail].load(std::memory_order_acquire)) {
// wait — producer is still copying; this is still wait-free on the
// hot path (single iteration in practice).
}
T val{std::move(*slot_ptr(tail))};
std::destroy_at(slot_ptr(tail));
ready_[tail].store(false, std::memory_order_release);
tail_.store((tail + 1) & mask_, std::memory_order_release);
return val;
}
[[nodiscard]] bool empty() const noexcept
{
return tail_.load(std::memory_order_acquire) ==
head_.load(std::memory_order_acquire);
}
[[nodiscard]] static constexpr std::size_t capacity() noexcept
{
return N - 1;
}
private:
T* slot_ptr(std::size_t i) noexcept
{
return std::launder(reinterpret_cast<T*>(&storage_[i]));
}
static constexpr std::size_t mask_ = N - 1;
struct alignas(alignof(T)) Slot
{
std::byte storage[sizeof(T)];
};
alignas(64) std::atomic<std::size_t> head_{0};
alignas(64) std::atomic<std::size_t> tail_{0};
Slot storage_[N];
std::atomic<bool> ready_[N]{};
};
} // namespace Void::Ring