fix: revert all unrelated upstream develop changes from phase-7 PR

Reverts 259 files that carried unrelated upstream changes through the
phase-6 merge: enum class removals (cppcoreguidelines-use-enum-class),
scoped_lock→lock_guard conversions (modernize-use-scoped-lock),
nodestore Backend API changes (void const* key), .clang-tidy config,
test infrastructure deletions, and miscellaneous develop changes.

These changes belong on develop, not in the telemetry PR chain.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
Pratik Mankawde
2026-04-30 16:59:24 +01:00
parent f44b89b99d
commit f4555c80fe
261 changed files with 4172 additions and 1770 deletions

View File

@@ -7,6 +7,7 @@ Checks: "-*,
bugprone-bad-signal-to-kill-thread, bugprone-bad-signal-to-kill-thread,
bugprone-bool-pointer-implicit-conversion, bugprone-bool-pointer-implicit-conversion,
bugprone-casting-through-void, bugprone-casting-through-void,
bugprone-capturing-this-in-member-variable,
bugprone-chained-comparison, bugprone-chained-comparison,
bugprone-compare-pointer-to-member-virtual-function, bugprone-compare-pointer-to-member-virtual-function,
bugprone-copy-constructor-init, bugprone-copy-constructor-init,
@@ -28,6 +29,7 @@ Checks: "-*,
bugprone-misplaced-operator-in-strlen-in-alloc, bugprone-misplaced-operator-in-strlen-in-alloc,
bugprone-misplaced-pointer-arithmetic-in-alloc, bugprone-misplaced-pointer-arithmetic-in-alloc,
bugprone-misplaced-widening-cast, bugprone-misplaced-widening-cast,
bugprone-misleading-setter-of-reference,
bugprone-move-forwarding-reference, bugprone-move-forwarding-reference,
bugprone-multi-level-implicit-pointer-conversion, bugprone-multi-level-implicit-pointer-conversion,
bugprone-multiple-new-in-one-expression, bugprone-multiple-new-in-one-expression,
@@ -85,6 +87,7 @@ Checks: "-*,
cppcoreguidelines-pro-type-static-cast-downcast, cppcoreguidelines-pro-type-static-cast-downcast,
cppcoreguidelines-rvalue-reference-param-not-moved, cppcoreguidelines-rvalue-reference-param-not-moved,
cppcoreguidelines-use-default-member-init, cppcoreguidelines-use-default-member-init,
cppcoreguidelines-use-enum-class,
cppcoreguidelines-virtual-class-destructor, cppcoreguidelines-virtual-class-destructor,
hicpp-ignored-remove-result, hicpp-ignored-remove-result,
misc-const-correctness, misc-const-correctness,
@@ -109,6 +112,7 @@ Checks: "-*,
modernize-use-nodiscard, modernize-use-nodiscard,
modernize-use-override, modernize-use-override,
modernize-use-ranges, modernize-use-ranges,
modernize-use-scoped-lock,
modernize-use-starts-ends-with, modernize-use-starts-ends-with,
modernize-use-std-numbers, modernize-use-std-numbers,
modernize-use-using, modernize-use-using,
@@ -122,6 +126,7 @@ Checks: "-*,
performance-move-constructor-init, performance-move-constructor-init,
performance-no-automatic-move, performance-no-automatic-move,
performance-trivially-destructible, performance-trivially-destructible,
readability-ambiguous-smartptr-reset-call,
readability-avoid-nested-conditional-operator, readability-avoid-nested-conditional-operator,
readability-avoid-return-with-void-value, readability-avoid-return-with-void-value,
readability-braces-around-statements, readability-braces-around-statements,

0
.github/scripts/levelization/generate.py vendored Executable file → Normal file
View File

View File

@@ -1,11 +1,11 @@
## Renaming ripple(d) to xrpl(d) ## Renaming ripple(d) to xrpl(d)
In the initial phases of development of the XRPL, the open source codebase was In the initial phases of development of the XRPL, the open source codebase was
called "xrpld" and it remains with that name even today. Today, over 1000 called "rippled" and it remains with that name even today. Today, over 1000
nodes run the application, and code contributions have been submitted by nodes run the application, and code contributions have been submitted by
developers located around the world. The XRPL community is larger than ever. developers located around the world. The XRPL community is larger than ever.
In light of the decentralized and diversified nature of XRPL, we will rename any In light of the decentralized and diversified nature of XRPL, we will rename any
references to `ripple` and `xrpld` to `xrpl` and `xrpld`, when appropriate. references to `ripple` and `rippled` to `xrpl` and `xrpld`, when appropriate.
See [here](https://xls.xrpl.org/xls/XLS-0095-rename-rippled-to-xrpld.html) for See [here](https://xls.xrpl.org/xls/XLS-0095-rename-rippled-to-xrpld.html) for
more information. more information.
@@ -22,17 +22,17 @@ run from the repository root.
2. `.github/scripts/rename/copyright.sh`: This script will remove superfluous 2. `.github/scripts/rename/copyright.sh`: This script will remove superfluous
copyright notices. copyright notices.
3. `.github/scripts/rename/cmake.sh`: This script will rename all CMake files 3. `.github/scripts/rename/cmake.sh`: This script will rename all CMake files
from `RippleXXX.cmake` or `XrpldXXX.cmake` to `XrplXXX.cmake`, and any from `RippleXXX.cmake` or `RippledXXX.cmake` to `XrplXXX.cmake`, and any
references to `ripple` and `xrpld` (with or without capital letters) to references to `ripple` and `rippled` (with or without capital letters) to
`xrpl` and `xrpld`, respectively. The name of the binary will remain as-is, `xrpl` and `xrpld`, respectively. The name of the binary will remain as-is,
and will only be renamed to `xrpld` by a later script. and will only be renamed to `xrpld` by a later script.
4. `.github/scripts/rename/binary.sh`: This script will rename the binary from 4. `.github/scripts/rename/binary.sh`: This script will rename the binary from
`xrpld` to `xrpld`, and reverses the symlink so that `xrpld` points to `rippled` to `xrpld`, and reverses the symlink so that `rippled` points to
the `xrpld` binary. the `xrpld` binary.
5. `.github/scripts/rename/namespace.sh`: This script will rename the C++ 5. `.github/scripts/rename/namespace.sh`: This script will rename the C++
namespaces from `ripple` to `xrpl`. namespaces from `ripple` to `xrpl`.
6. `.github/scripts/rename/config.sh`: This script will rename the config from 6. `.github/scripts/rename/config.sh`: This script will rename the config from
`xrpld.cfg` to `xrpld.cfg`, and updating the code accordingly. The old `rippled.cfg` to `xrpld.cfg`, and updating the code accordingly. The old
filename will still be accepted. filename will still be accepted.
7. `.github/scripts/rename/docs.sh`: This script will rename any lingering 7. `.github/scripts/rename/docs.sh`: This script will rename any lingering
references of `ripple(d)` to `xrpl(d)` in code, comments, and documentation. references of `ripple(d)` to `xrpl(d)` in code, comments, and documentation.

View File

@@ -15,6 +15,7 @@
namespace xrpl { namespace xrpl {
// DEPRECATED use beast::severities::Severity instead // DEPRECATED use beast::severities::Severity instead
// NOLINTNEXTLINE(cppcoreguidelines-use-enum-class)
enum LogSeverity { enum LogSeverity {
lsINVALID = -1, // used to indicate an invalid severity lsINVALID = -1, // used to indicate an invalid severity
lsTRACE = 0, // Very low-level progress information, details inside lsTRACE = 0, // Very low-level progress information, details inside
@@ -207,6 +208,8 @@ public:
fromString(std::string const& s); fromString(std::string const& s);
private: private:
// Need to be named before converting
// NOLINTNEXTLINE(cppcoreguidelines-use-enum-class)
enum { enum {
// Maximum line length for log messages. // Maximum line length for log messages.
// If the message exceeds this length it will be truncated with // If the message exceeds this length it will be truncated with

View File

@@ -131,7 +131,7 @@ public:
* @tparam LockType The type of lock to use * @tparam LockType The type of lock to use
* @return A lock on the mutex and a reference to the protected data * @return A lock on the mutex and a reference to the protected data
*/ */
template <template <typename...> typename LockType = std::lock_guard> template <template <typename...> typename LockType = std::scoped_lock>
Lock<ProtectedDataType const, LockType, MutexType> Lock<ProtectedDataType const, LockType, MutexType>
lock() const lock() const
{ {
@@ -144,7 +144,7 @@ public:
* @tparam LockType The type of lock to use * @tparam LockType The type of lock to use
* @return A lock on the mutex and a reference to the protected data * @return A lock on the mutex and a reference to the protected data
*/ */
template <template <typename...> typename LockType = std::lock_guard> template <template <typename...> typename LockType = std::scoped_lock>
Lock<ProtectedDataType, LockType, MutexType> Lock<ProtectedDataType, LockType, MutexType>
lock() lock()
{ {

View File

@@ -70,7 +70,7 @@ isPowerOfTen(T value)
struct MantissaRange struct MantissaRange
{ {
using rep = std::uint64_t; using rep = std::uint64_t;
enum mantissa_scale { small, large }; enum class mantissa_scale { small, large };
explicit constexpr MantissaRange(mantissa_scale scale_) explicit constexpr MantissaRange(mantissa_scale scale_)
: min(getMin(scale_)), log(logTen(min).value_or(-1)), scale(scale_) : min(getMin(scale_)), log(logTen(min).value_or(-1)), scale(scale_)
@@ -88,9 +88,9 @@ private:
{ {
switch (scale_) switch (scale_)
{ {
case small: case mantissa_scale::small:
return 1'000'000'000'000'000ULL; return 1'000'000'000'000'000ULL;
case large: case mantissa_scale::large:
return 1'000'000'000'000'000'000ULL; return 1'000'000'000'000'000'000ULL;
default: default:
// Since this can never be called outside a non-constexpr // Since this can never be called outside a non-constexpr
@@ -384,7 +384,7 @@ public:
root2(Number f); root2(Number f);
// Thread local rounding control. Default is to_nearest // Thread local rounding control. Default is to_nearest
enum rounding_mode { to_nearest, towards_zero, downward, upward }; enum class rounding_mode { to_nearest, towards_zero, downward, upward };
static rounding_mode static rounding_mode
getround(); getround();
// Returns previously set mode // Returns previously set mode
@@ -443,14 +443,14 @@ private:
static thread_local rounding_mode mode_; static thread_local rounding_mode mode_;
// The available ranges for mantissa // The available ranges for mantissa
constexpr static MantissaRange smallRange{MantissaRange::small}; constexpr static MantissaRange smallRange{MantissaRange::mantissa_scale::small};
static_assert(isPowerOfTen(smallRange.min)); static_assert(isPowerOfTen(smallRange.min));
static_assert(smallRange.min == 1'000'000'000'000'000LL); static_assert(smallRange.min == 1'000'000'000'000'000LL);
static_assert(smallRange.max == 9'999'999'999'999'999LL); static_assert(smallRange.max == 9'999'999'999'999'999LL);
static_assert(smallRange.log == 15); static_assert(smallRange.log == 15);
static_assert(smallRange.min < maxRep); static_assert(smallRange.min < maxRep);
static_assert(smallRange.max < maxRep); static_assert(smallRange.max < maxRep);
constexpr static MantissaRange largeRange{MantissaRange::large}; constexpr static MantissaRange largeRange{MantissaRange::mantissa_scale::large};
static_assert(isPowerOfTen(largeRange.min)); static_assert(isPowerOfTen(largeRange.min));
static_assert(largeRange.min == 1'000'000'000'000'000'000ULL); static_assert(largeRange.min == 1'000'000'000'000'000'000ULL);
static_assert(largeRange.max == internalrep(9'999'999'999'999'999'999ULL)); static_assert(largeRange.max == internalrep(9'999'999'999'999'999'999ULL));
@@ -759,9 +759,9 @@ to_string(MantissaRange::mantissa_scale const& scale)
{ {
switch (scale) switch (scale)
{ {
case MantissaRange::small: case MantissaRange::mantissa_scale::small:
return "small"; return "small";
case MantissaRange::large: case MantissaRange::mantissa_scale::large:
return "large"; return "large";
default: default:
throw std::runtime_error("Bad scale"); throw std::runtime_error("Bad scale");

View File

@@ -92,7 +92,7 @@ class SlabAllocator
std::uint8_t* ret = nullptr; // NOLINT(misc-const-correctness) std::uint8_t* ret = nullptr; // NOLINT(misc-const-correctness)
{ {
std::lock_guard const l(m_); std::scoped_lock const l(m_);
ret = l_; ret = l_;
@@ -121,7 +121,7 @@ class SlabAllocator
{ {
XRPL_ASSERT(own(ptr), "xrpl::SlabAllocator::SlabBlock::deallocate : own input"); XRPL_ASSERT(own(ptr), "xrpl::SlabAllocator::SlabBlock::deallocate : own input");
std::lock_guard const l(m_); std::scoped_lock const l(m_);
// Use memcpy to avoid unaligned UB // Use memcpy to avoid unaligned UB
// (will optimize to equivalent code) // (will optimize to equivalent code)

View File

@@ -166,7 +166,7 @@ public:
private: private:
SharedPointerType SharedPointerType
initialFetch(key_type const& key, std::lock_guard<mutex_type> const& l); initialFetch(key_type const& key, std::scoped_lock<mutex_type> const& l);
void void
collect_metrics(); collect_metrics();
@@ -266,7 +266,7 @@ private:
typename KeyValueCacheType::map_type& partition, typename KeyValueCacheType::map_type& partition,
SweptPointersVector& stuffToSweep, SweptPointersVector& stuffToSweep,
std::atomic<int>& allRemovals, std::atomic<int>& allRemovals,
std::lock_guard<std::recursive_mutex> const&); std::scoped_lock<std::recursive_mutex> const&);
[[nodiscard]] std::thread [[nodiscard]] std::thread
sweepHelper( sweepHelper(
@@ -275,7 +275,7 @@ private:
typename KeyOnlyCacheType::map_type& partition, typename KeyOnlyCacheType::map_type& partition,
SweptPointersVector&, SweptPointersVector&,
std::atomic<int>& allRemovals, std::atomic<int>& allRemovals,
std::lock_guard<std::recursive_mutex> const&); std::scoped_lock<std::recursive_mutex> const&);
beast::Journal m_journal; beast::Journal m_journal;
clock_type& m_clock; clock_type& m_clock;

View File

@@ -69,7 +69,7 @@ inline std::size_t
TaggedCache<Key, T, IsKeyCache, SharedWeakUnionPointer, SharedPointerType, Hash, KeyEqual, Mutex>:: TaggedCache<Key, T, IsKeyCache, SharedWeakUnionPointer, SharedPointerType, Hash, KeyEqual, Mutex>::
size() const size() const
{ {
std::lock_guard lock(m_mutex); std::scoped_lock lock(m_mutex);
return m_cache.size(); return m_cache.size();
} }
@@ -86,7 +86,7 @@ inline int
TaggedCache<Key, T, IsKeyCache, SharedWeakUnionPointer, SharedPointerType, Hash, KeyEqual, Mutex>:: TaggedCache<Key, T, IsKeyCache, SharedWeakUnionPointer, SharedPointerType, Hash, KeyEqual, Mutex>::
getCacheSize() const getCacheSize() const
{ {
std::lock_guard lock(m_mutex); std::scoped_lock lock(m_mutex);
return m_cache_count; return m_cache_count;
} }
@@ -103,7 +103,7 @@ inline int
TaggedCache<Key, T, IsKeyCache, SharedWeakUnionPointer, SharedPointerType, Hash, KeyEqual, Mutex>:: TaggedCache<Key, T, IsKeyCache, SharedWeakUnionPointer, SharedPointerType, Hash, KeyEqual, Mutex>::
getTrackSize() const getTrackSize() const
{ {
std::lock_guard lock(m_mutex); std::scoped_lock lock(m_mutex);
return m_cache.size(); return m_cache.size();
} }
@@ -120,7 +120,7 @@ inline float
TaggedCache<Key, T, IsKeyCache, SharedWeakUnionPointer, SharedPointerType, Hash, KeyEqual, Mutex>:: TaggedCache<Key, T, IsKeyCache, SharedWeakUnionPointer, SharedPointerType, Hash, KeyEqual, Mutex>::
getHitRate() getHitRate()
{ {
std::lock_guard lock(m_mutex); std::scoped_lock lock(m_mutex);
auto const total = static_cast<float>(m_hits + m_misses); auto const total = static_cast<float>(m_hits + m_misses);
return m_hits * (100.0f / std::max(1.0f, total)); return m_hits * (100.0f / std::max(1.0f, total));
} }
@@ -138,7 +138,7 @@ inline void
TaggedCache<Key, T, IsKeyCache, SharedWeakUnionPointer, SharedPointerType, Hash, KeyEqual, Mutex>:: TaggedCache<Key, T, IsKeyCache, SharedWeakUnionPointer, SharedPointerType, Hash, KeyEqual, Mutex>::
clear() clear()
{ {
std::lock_guard lock(m_mutex); std::scoped_lock lock(m_mutex);
m_cache.clear(); m_cache.clear();
m_cache_count = 0; m_cache_count = 0;
} }
@@ -156,7 +156,7 @@ inline void
TaggedCache<Key, T, IsKeyCache, SharedWeakUnionPointer, SharedPointerType, Hash, KeyEqual, Mutex>:: TaggedCache<Key, T, IsKeyCache, SharedWeakUnionPointer, SharedPointerType, Hash, KeyEqual, Mutex>::
reset() reset()
{ {
std::lock_guard lock(m_mutex); std::scoped_lock lock(m_mutex);
m_cache.clear(); m_cache.clear();
m_cache_count = 0; m_cache_count = 0;
m_hits = 0; m_hits = 0;
@@ -177,7 +177,7 @@ inline bool
TaggedCache<Key, T, IsKeyCache, SharedWeakUnionPointer, SharedPointerType, Hash, KeyEqual, Mutex>:: TaggedCache<Key, T, IsKeyCache, SharedWeakUnionPointer, SharedPointerType, Hash, KeyEqual, Mutex>::
touch_if_exists(KeyComparable const& key) touch_if_exists(KeyComparable const& key)
{ {
std::lock_guard lock(m_mutex); std::scoped_lock lock(m_mutex);
auto const iter(m_cache.find(key)); auto const iter(m_cache.find(key));
if (iter == m_cache.end()) if (iter == m_cache.end())
{ {
@@ -212,7 +212,7 @@ TaggedCache<Key, T, IsKeyCache, SharedWeakUnionPointer, SharedPointerType, Hash,
auto const start = std::chrono::steady_clock::now(); auto const start = std::chrono::steady_clock::now();
{ {
std::lock_guard lock(m_mutex); std::scoped_lock lock(m_mutex);
if (m_target_size == 0 || (static_cast<int>(m_cache.size()) <= m_target_size)) if (m_target_size == 0 || (static_cast<int>(m_cache.size()) <= m_target_size))
{ {
@@ -269,7 +269,7 @@ TaggedCache<Key, T, IsKeyCache, SharedWeakUnionPointer, SharedPointerType, Hash,
{ {
// Remove from cache, if !valid, remove from map too. Returns true if // Remove from cache, if !valid, remove from map too. Returns true if
// removed from cache // removed from cache
std::lock_guard lock(m_mutex); std::scoped_lock lock(m_mutex);
auto cit = m_cache.find(key); auto cit = m_cache.find(key);
@@ -309,7 +309,7 @@ TaggedCache<Key, T, IsKeyCache, SharedWeakUnionPointer, SharedPointerType, Hash,
{ {
// Return canonical value, store if needed, refresh in cache // Return canonical value, store if needed, refresh in cache
// Return values: true=we had the data already // Return values: true=we had the data already
std::lock_guard lock(m_mutex); std::scoped_lock lock(m_mutex);
auto cit = m_cache.find(key); auto cit = m_cache.find(key);
@@ -423,7 +423,7 @@ inline SharedPointerType
TaggedCache<Key, T, IsKeyCache, SharedWeakUnionPointer, SharedPointerType, Hash, KeyEqual, Mutex>:: TaggedCache<Key, T, IsKeyCache, SharedWeakUnionPointer, SharedPointerType, Hash, KeyEqual, Mutex>::
fetch(key_type const& key) fetch(key_type const& key)
{ {
std::lock_guard<mutex_type> l(m_mutex); std::scoped_lock<mutex_type> l(m_mutex);
auto ret = initialFetch(key, l); auto ret = initialFetch(key, l);
if (!ret) if (!ret)
++m_misses; ++m_misses;
@@ -474,7 +474,7 @@ inline auto
TaggedCache<Key, T, IsKeyCache, SharedWeakUnionPointer, SharedPointerType, Hash, KeyEqual, Mutex>:: TaggedCache<Key, T, IsKeyCache, SharedWeakUnionPointer, SharedPointerType, Hash, KeyEqual, Mutex>::
insert(key_type const& key) -> std::enable_if_t<IsKeyCache, ReturnType> insert(key_type const& key) -> std::enable_if_t<IsKeyCache, ReturnType>
{ {
std::lock_guard lock(m_mutex); std::scoped_lock lock(m_mutex);
clock_type::time_point const now(m_clock.now()); clock_type::time_point const now(m_clock.now());
auto [it, inserted] = m_cache.emplace( auto [it, inserted] = m_cache.emplace(
std::piecewise_construct, std::forward_as_tuple(key), std::forward_as_tuple(now)); std::piecewise_construct, std::forward_as_tuple(key), std::forward_as_tuple(now));
@@ -538,7 +538,7 @@ TaggedCache<Key, T, IsKeyCache, SharedWeakUnionPointer, SharedPointerType, Hash,
std::vector<key_type> v; std::vector<key_type> v;
{ {
std::lock_guard lock(m_mutex); std::scoped_lock lock(m_mutex);
v.reserve(m_cache.size()); v.reserve(m_cache.size());
for (auto const& _ : m_cache) for (auto const& _ : m_cache)
v.push_back(_.first); v.push_back(_.first);
@@ -560,7 +560,7 @@ inline double
TaggedCache<Key, T, IsKeyCache, SharedWeakUnionPointer, SharedPointerType, Hash, KeyEqual, Mutex>:: TaggedCache<Key, T, IsKeyCache, SharedWeakUnionPointer, SharedPointerType, Hash, KeyEqual, Mutex>::
rate() const rate() const
{ {
std::lock_guard lock(m_mutex); std::scoped_lock lock(m_mutex);
auto const tot = m_hits + m_misses; auto const tot = m_hits + m_misses;
if (tot == 0) if (tot == 0)
return 0; return 0;
@@ -582,7 +582,7 @@ TaggedCache<Key, T, IsKeyCache, SharedWeakUnionPointer, SharedPointerType, Hash,
fetch(key_type const& digest, Handler const& h) fetch(key_type const& digest, Handler const& h)
{ {
{ {
std::lock_guard l(m_mutex); std::scoped_lock l(m_mutex);
if (auto ret = initialFetch(digest, l)) if (auto ret = initialFetch(digest, l))
return ret; return ret;
} }
@@ -591,7 +591,7 @@ TaggedCache<Key, T, IsKeyCache, SharedWeakUnionPointer, SharedPointerType, Hash,
if (!sle) if (!sle)
return {}; return {};
std::lock_guard l(m_mutex); std::scoped_lock l(m_mutex);
++m_misses; ++m_misses;
auto const [it, inserted] = m_cache.emplace(digest, Entry(m_clock.now(), std::move(sle))); auto const [it, inserted] = m_cache.emplace(digest, Entry(m_clock.now(), std::move(sle)));
if (!inserted) if (!inserted)
@@ -611,7 +611,7 @@ template <
class Mutex> class Mutex>
inline SharedPointerType inline SharedPointerType
TaggedCache<Key, T, IsKeyCache, SharedWeakUnionPointer, SharedPointerType, Hash, KeyEqual, Mutex>:: TaggedCache<Key, T, IsKeyCache, SharedWeakUnionPointer, SharedPointerType, Hash, KeyEqual, Mutex>::
initialFetch(key_type const& key, std::lock_guard<mutex_type> const& l) initialFetch(key_type const& key, std::scoped_lock<mutex_type> const& l)
{ {
auto cit = m_cache.find(key); auto cit = m_cache.find(key);
if (cit == m_cache.end()) if (cit == m_cache.end())
@@ -655,7 +655,7 @@ TaggedCache<Key, T, IsKeyCache, SharedWeakUnionPointer, SharedPointerType, Hash,
{ {
beast::insight::Gauge::value_type hit_rate(0); beast::insight::Gauge::value_type hit_rate(0);
{ {
std::lock_guard lock(m_mutex); std::scoped_lock lock(m_mutex);
auto const total(m_hits + m_misses); auto const total(m_hits + m_misses);
if (total != 0) if (total != 0)
hit_rate = (m_hits * 100) / total; hit_rate = (m_hits * 100) / total;
@@ -681,7 +681,7 @@ TaggedCache<Key, T, IsKeyCache, SharedWeakUnionPointer, SharedPointerType, Hash,
typename KeyValueCacheType::map_type& partition, typename KeyValueCacheType::map_type& partition,
SweptPointersVector& stuffToSweep, SweptPointersVector& stuffToSweep,
std::atomic<int>& allRemovals, std::atomic<int>& allRemovals,
std::lock_guard<std::recursive_mutex> const&) std::scoped_lock<std::recursive_mutex> const&)
{ {
return std::thread([&, this]() { return std::thread([&, this]() {
int cacheRemovals = 0; int cacheRemovals = 0;
@@ -761,7 +761,7 @@ TaggedCache<Key, T, IsKeyCache, SharedWeakUnionPointer, SharedPointerType, Hash,
typename KeyOnlyCacheType::map_type& partition, typename KeyOnlyCacheType::map_type& partition,
SweptPointersVector&, SweptPointersVector&,
std::atomic<int>& allRemovals, std::atomic<int>& allRemovals,
std::lock_guard<std::recursive_mutex> const&) std::scoped_lock<std::recursive_mutex> const&)
{ {
return std::thread([&, this]() { return std::thread([&, this]() {
int cacheRemovals = 0; int cacheRemovals = 0;

View File

@@ -32,7 +32,7 @@ make_seed_pair() noexcept
// state_t& operator=(state_t const&) = delete; // state_t& operator=(state_t const&) = delete;
}; };
static state_t state; static state_t state;
std::lock_guard const lock(state.mutex); std::scoped_lock const lock(state.mutex);
return {state.dist(state.gen), state.dist(state.gen)}; return {state.dist(state.gen), state.dist(state.gen)};
} }

View File

@@ -60,7 +60,7 @@ default_prng()
thread_local beast::xor_shift_engine engine = [] { thread_local beast::xor_shift_engine engine = [] {
std::uint64_t seed = 0; std::uint64_t seed = 0;
{ {
std::lock_guard const lk(m); std::scoped_lock const lk(m);
std::uniform_int_distribution<std::uint64_t> distribution{1}; std::uniform_int_distribution<std::uint64_t> distribution{1};
seed = distribution(seeder); seed = distribution(seeder);
} }

View File

@@ -83,7 +83,7 @@ public:
void void
sample_one(Handler&& handler) sample_one(Handler&& handler)
{ {
std::lock_guard const lock(m_mutex); std::scoped_lock const lock(m_mutex);
if (m_cancel) if (m_cancel)
throw std::logic_error("io_latency_probe is canceled"); throw std::logic_error("io_latency_probe is canceled");
boost::asio::post( boost::asio::post(
@@ -98,7 +98,7 @@ public:
void void
sample(Handler&& handler) sample(Handler&& handler)
{ {
std::lock_guard const lock(m_mutex); std::scoped_lock const lock(m_mutex);
if (m_cancel) if (m_cancel)
throw std::logic_error("io_latency_probe is canceled"); throw std::logic_error("io_latency_probe is canceled");
boost::asio::post( boost::asio::post(
@@ -122,14 +122,14 @@ private:
void void
addref() addref()
{ {
std::lock_guard const lock(m_mutex); std::scoped_lock const lock(m_mutex);
++m_count; ++m_count;
} }
void void
release() release()
{ {
std::lock_guard const lock(m_mutex); std::scoped_lock const lock(m_mutex);
if (--m_count == 0) if (--m_count == 0)
m_cond.notify_all(); m_cond.notify_all();
} }
@@ -192,7 +192,7 @@ private:
m_handler(elapsed); m_handler(elapsed);
{ {
std::lock_guard const lock(m_probe->m_mutex); std::scoped_lock const lock(m_probe->m_mutex);
if (m_probe->m_cancel) if (m_probe->m_cancel)
return; return;
} }

View File

@@ -115,7 +115,7 @@ enable_yield_to::spawn(F0&& f, FN&&... fn)
boost::context::fixedsize_stack(2 * 1024 * 1024), boost::context::fixedsize_stack(2 * 1024 * 1024),
[&](yield_context yield) { [&](yield_context yield) {
f(yield); f(yield);
std::lock_guard const lock{m_}; std::scoped_lock const lock{m_};
if (--running_ == 0) if (--running_ == 0)
cv_.notify_all(); cv_.notify_all();
}, },

View File

@@ -14,7 +14,7 @@ namespace beast::unit_test {
class selector class selector
{ {
public: public:
enum mode_t { enum class mode_t {
// Run all tests except manual ones // Run all tests except manual ones
all, all,
@@ -53,8 +53,8 @@ public:
template <class> template <class>
selector::selector(mode_t mode, std::string const& pattern) : mode_(mode), pat_(pattern) selector::selector(mode_t mode, std::string const& pattern) : mode_(mode), pat_(pattern)
{ {
if (mode_ == automatch && pattern.empty()) if (mode_ == mode_t::automatch && pattern.empty())
mode_ = all; mode_ = mode_t::all;
} }
template <class> template <class>
@@ -63,18 +63,18 @@ selector::operator()(suite_info const& s)
{ {
switch (mode_) switch (mode_)
{ {
case automatch: case mode_t::automatch:
// suite or full name // suite or full name
if (s.name() == pat_ || s.full_name() == pat_) if (s.name() == pat_ || s.full_name() == pat_)
{ {
mode_ = none; mode_ = mode_t::none;
return true; return true;
} }
// check module // check module
if (pat_ == s.module()) if (pat_ == s.module())
{ {
mode_ = module; mode_ = mode_t::module;
library_ = s.library(); library_ = s.library();
return !s.manual(); return !s.manual();
} }
@@ -82,7 +82,7 @@ selector::operator()(suite_info const& s)
// check library // check library
if (pat_ == s.library()) if (pat_ == s.library())
{ {
mode_ = library; mode_ = mode_t::library;
return !s.manual(); return !s.manual();
} }
@@ -96,19 +96,19 @@ selector::operator()(suite_info const& s)
return false; return false;
case suite: case mode_t::suite:
return pat_ == s.name(); return pat_ == s.name();
case module: case mode_t::module:
return pat_ == s.module() && !s.manual(); return pat_ == s.module() && !s.manual();
case library: case mode_t::library:
return pat_ == s.library() && !s.manual(); return pat_ == s.library() && !s.manual();
case none: case mode_t::none:
return false; return false;
case all: case mode_t::all:
default: default:
break; break;
}; };
@@ -138,28 +138,28 @@ selector::operator()(suite_info const& s)
inline selector inline selector
match_auto(std::string const& name) match_auto(std::string const& name)
{ {
return selector(selector::automatch, name); return selector(selector::mode_t::automatch, name);
} }
/** Return a predicate that matches all suites not marked manual. */ /** Return a predicate that matches all suites not marked manual. */
inline selector inline selector
match_all() match_all()
{ {
return selector(selector::all); return selector(selector::mode_t::all);
} }
/** Returns a predicate that matches a specific suite. */ /** Returns a predicate that matches a specific suite. */
inline selector inline selector
match_suite(std::string const& name) match_suite(std::string const& name)
{ {
return selector(selector::suite, name); return selector(selector::mode_t::suite, name);
} }
/** Returns a predicate that matches all suites in a library. */ /** Returns a predicate that matches all suites in a library. */
inline selector inline selector
match_library(std::string const& name) match_library(std::string const& name)
{ {
return selector(selector::library, name); return selector(selector::mode_t::library, name);
} }
} // namespace beast::unit_test } // namespace beast::unit_test

View File

@@ -62,6 +62,8 @@ private:
{ {
using run_time = std::pair<std::string, typename clock_type::duration>; using run_time = std::pair<std::string, typename clock_type::duration>;
// Need to be named before converting
// NOLINTNEXTLINE(cppcoreguidelines-use-enum-class)
enum { max_top = 10 }; enum { max_top = 10 };
std::size_t suites = 0; std::size_t suites = 0;

View File

@@ -231,7 +231,7 @@ template <class>
void void
runner::testcase(std::string const& name) runner::testcase(std::string const& name)
{ {
std::lock_guard const lock(mutex_); std::scoped_lock const lock(mutex_);
// Name may not be empty // Name may not be empty
BOOST_ASSERT(default_ || !name.empty()); BOOST_ASSERT(default_ || !name.empty());
// Forgot to call pass or fail // Forgot to call pass or fail
@@ -247,7 +247,7 @@ template <class>
void void
runner::pass() runner::pass()
{ {
std::lock_guard const lock(mutex_); std::scoped_lock const lock(mutex_);
if (default_) if (default_)
testcase(""); testcase("");
on_pass(); on_pass();
@@ -258,7 +258,7 @@ template <class>
void void
runner::fail(std::string const& reason) runner::fail(std::string const& reason)
{ {
std::lock_guard const lock(mutex_); std::scoped_lock const lock(mutex_);
if (default_) if (default_)
testcase(""); testcase("");
on_fail(reason); on_fail(reason);
@@ -270,7 +270,7 @@ template <class>
void void
runner::log(std::string const& s) runner::log(std::string const& s)
{ {
std::lock_guard const lock(mutex_); std::scoped_lock const lock(mutex_);
if (default_) if (default_)
testcase(""); testcase("");
on_log(s); on_log(s);

View File

@@ -37,7 +37,7 @@ make_reason(String const& reason, char const* file, int line)
class Thread; class Thread;
enum abort_t { no_abort_on_fail, abort_on_fail }; enum class abort_t { no_abort_on_fail, abort_on_fail };
/** A testsuite class. /** A testsuite class.
@@ -127,7 +127,7 @@ private:
@param abort Determines if suite continues running after a failure. @param abort Determines if suite continues running after a failure.
*/ */
void void
operator()(std::string const& name, abort_t abort = no_abort_on_fail); operator()(std::string const& name, abort_t abort = abort_t::no_abort_on_fail);
scoped_testcase scoped_testcase
operator()(abort_t abort); operator()(abort_t abort);
@@ -363,14 +363,14 @@ public:
inline void inline void
suite::testcase_t::operator()(std::string const& name, abort_t abort) suite::testcase_t::operator()(std::string const& name, abort_t abort)
{ {
suite_.abort_ = abort == abort_on_fail; suite_.abort_ = abort == abort_t::abort_on_fail;
suite_.runner_->testcase(name); suite_.runner_->testcase(name);
} }
inline suite::scoped_testcase inline suite::scoped_testcase
suite::testcase_t::operator()(abort_t abort) suite::testcase_t::operator()(abort_t abort)
{ {
suite_.abort_ = abort == abort_on_fail; suite_.abort_ = abort == abort_t::abort_on_fail;
return {suite_, ss_}; return {suite_, ss_};
} }

View File

@@ -9,6 +9,8 @@ namespace beast {
/** A namespace for easy access to logging severity values. */ /** A namespace for easy access to logging severity values. */
namespace severities { namespace severities {
/** Severity level / threshold of a Journal message. */ /** Severity level / threshold of a Journal message. */
// Hundreds of usages via logging macros
// NOLINTNEXTLINE(cppcoreguidelines-use-enum-class)
enum Severity { enum Severity {
kAll = 0, kAll = 0,

View File

@@ -56,7 +56,7 @@ private:
// a lock. This removes a small timing window that occurs if the // a lock. This removes a small timing window that occurs if the
// waiting thread is handling a spurious wakeup when closureCount_ // waiting thread is handling a spurious wakeup when closureCount_
// drops to zero. // drops to zero.
std::lock_guard const lock{mutex_}; std::scoped_lock const lock{mutex_};
// Update closureCount_. Notify if stopping and closureCount_ == 0. // Update closureCount_. Notify if stopping and closureCount_ == 0.
if ((--closureCount_ == 0) && waitForClosures_) if ((--closureCount_ == 0) && waitForClosures_)
@@ -170,7 +170,7 @@ public:
{ {
std::optional<Substitute<Closure>> ret; std::optional<Substitute<Closure>> ret;
std::lock_guard const lock{mutex_}; std::scoped_lock const lock{mutex_};
if (!waitForClosures_) if (!waitForClosures_)
ret.emplace(*this, std::forward<Closure>(closure)); ret.emplace(*this, std::forward<Closure>(closure));
@@ -193,7 +193,7 @@ public:
bool bool
joined() const joined() const
{ {
std::lock_guard const lock{mutex_}; std::scoped_lock const lock{mutex_};
return waitForClosures_; return waitForClosures_;
} }
}; };

View File

@@ -34,7 +34,7 @@ inline void
JobQueue::Coro::yield() const JobQueue::Coro::yield() const
{ {
{ {
std::lock_guard lock(jq_.m_mutex); std::scoped_lock lock(jq_.m_mutex);
++jq_.nSuspend_; ++jq_.nSuspend_;
} }
(*yield_)(); (*yield_)();
@@ -44,7 +44,7 @@ inline bool
JobQueue::Coro::post() JobQueue::Coro::post()
{ {
{ {
std::lock_guard lk(mutex_run_); std::scoped_lock lk(mutex_run_);
running_ = true; running_ = true;
} }
@@ -55,7 +55,7 @@ JobQueue::Coro::post()
} }
// The coroutine will not run. Clean up running_. // The coroutine will not run. Clean up running_.
std::lock_guard lk(mutex_run_); std::scoped_lock lk(mutex_run_);
running_ = false; running_ = false;
cv_.notify_all(); cv_.notify_all();
return false; return false;
@@ -65,16 +65,16 @@ inline void
JobQueue::Coro::resume() JobQueue::Coro::resume()
{ {
{ {
std::lock_guard lk(mutex_run_); std::scoped_lock lk(mutex_run_);
running_ = true; running_ = true;
} }
{ {
std::lock_guard lk(jq_.m_mutex); std::scoped_lock lk(jq_.m_mutex);
--jq_.nSuspend_; --jq_.nSuspend_;
} }
auto saved = detail::getLocalValues().release(); auto saved = detail::getLocalValues().release();
detail::getLocalValues().reset(&lvs_); detail::getLocalValues().reset(&lvs_);
std::lock_guard lock(mutex_); std::scoped_lock lock(mutex_);
// A late resume() can arrive after the coroutine has already completed. // A late resume() can arrive after the coroutine has already completed.
// This is an expected (if rare) outcome of the race condition documented // This is an expected (if rare) outcome of the race condition documented
// in JobQueue.h:354-377 where post() schedules a resume job before the // in JobQueue.h:354-377 where post() schedules a resume job before the
@@ -89,7 +89,7 @@ JobQueue::Coro::resume()
} }
detail::getLocalValues().release(); detail::getLocalValues().release();
detail::getLocalValues().reset(saved); detail::getLocalValues().reset(saved);
std::lock_guard lk(mutex_run_); std::scoped_lock lk(mutex_run_);
running_ = false; running_ = false;
cv_.notify_all(); cv_.notify_all();
} }
@@ -113,7 +113,7 @@ JobQueue::Coro::expectEarlyExit()
// //
// That said, since we're outside the Coro's stack, we need to // That said, since we're outside the Coro's stack, we need to
// decrement the nSuspend that the Coro's call to yield caused. // decrement the nSuspend that the Coro's call to yield caused.
std::lock_guard lock(jq_.m_mutex); std::scoped_lock lock(jq_.m_mutex);
--jq_.nSuspend_; --jq_.nSuspend_;
#ifndef NDEBUG #ifndef NDEBUG
finished_ = true; finished_ = true;

View File

@@ -11,6 +11,8 @@ namespace xrpl {
// Note that this queue should only be used for CPU-bound jobs // Note that this queue should only be used for CPU-bound jobs
// It is primarily intended for signature checking // It is primarily intended for signature checking
// Protocol-wide
// NOLINTNEXTLINE(cppcoreguidelines-use-enum-class)
enum JobType { enum JobType {
// Special type indicating an invalid job - will go away soon. // Special type indicating an invalid job - will go away soon.
jtINVALID = -1, jtINVALID = -1,

View File

@@ -67,7 +67,7 @@ public:
bool bool
contains(PublicKey const& nodeId) contains(PublicKey const& nodeId)
{ {
std::lock_guard const lock(this->mutex_); std::scoped_lock const lock(this->mutex_);
return table_.contains({.nodeId = nodeId, .description = {}}); return table_.contains({.nodeId = nodeId, .description = {}});
} }

View File

@@ -55,7 +55,7 @@ public:
void void
notify() notify()
{ {
std::lock_guard const lock{m_mutex}; std::scoped_lock const lock{m_mutex};
++m_count; ++m_count;
m_cond.notify_one(); m_cond.notify_one();
} }
@@ -76,7 +76,7 @@ public:
bool bool
try_wait() try_wait()
{ {
std::lock_guard lock{m_mutex}; std::scoped_lock lock{m_mutex};
if (m_count == 0) if (m_count == 0)
return false; return false;
--m_count; --m_count;

View File

@@ -107,7 +107,7 @@ namespace Json {
class Writer class Writer
{ {
public: public:
enum CollectionType { array, object }; enum class CollectionType { array, object };
explicit Writer(Output const& output); explicit Writer(Output const& output);
Writer(Writer&&) noexcept; Writer(Writer&&) noexcept;

View File

@@ -70,6 +70,8 @@ public:
static constexpr unsigned nest_limit{25}; static constexpr unsigned nest_limit{25};
private: private:
// 53 files, protocol-wide
// NOLINTNEXTLINE(cppcoreguidelines-use-enum-class)
enum TokenType { enum TokenType {
tokenEndOfStream = 0, tokenEndOfStream = 0,
tokenObjectBegin, tokenObjectBegin,

View File

@@ -15,6 +15,8 @@ namespace Json {
/** \brief Type of the value held by a Value object. /** \brief Type of the value held by a Value object.
*/ */
// Used throughout JSON layer
// NOLINTNEXTLINE(cppcoreguidelines-use-enum-class)
enum ValueType { enum ValueType {
nullValue = 0, ///< 'null' value nullValue = 0, ///< 'null' value
intValue, ///< signed integer value intValue, ///< signed integer value
@@ -147,6 +149,8 @@ private:
class CZString class CZString
{ {
public: public:
// Stored as int field, implicit conversion
// NOLINTNEXTLINE(cppcoreguidelines-use-enum-class)
enum DuplicationPolicy { noDuplication = 0, duplicate, duplicateOnCopy }; enum DuplicationPolicy { noDuplication = 0, duplicate, duplicateOnCopy };
CZString(int index); CZString(int index);
CZString(char const* cstr, DuplicationPolicy allocate); CZString(char const* cstr, DuplicationPolicy allocate);
@@ -471,6 +475,8 @@ operator>=(Value const& x, Value const& y)
class ValueAllocator class ValueAllocator
{ {
public: public:
// Need to be named before converting
// NOLINTNEXTLINE(cppcoreguidelines-use-enum-class)
enum { unknown = (unsigned)-1 }; enum { unknown = (unsigned)-1 };
virtual ~ValueAllocator() = default; virtual ~ValueAllocator() = default;

View File

@@ -7,6 +7,8 @@
namespace xrpl { namespace xrpl {
// Bitwise flag enum with existing operator overloads
// NOLINTNEXTLINE(cppcoreguidelines-use-enum-class)
enum ApplyFlags : std::uint32_t { enum ApplyFlags : std::uint32_t {
tapNONE = 0x00, tapNONE = 0x00,

View File

@@ -31,7 +31,7 @@ public:
bool bool
startWork(LedgerIndex seq) startWork(LedgerIndex seq)
{ {
std::lock_guard const lock(mutex_); std::scoped_lock const lock(mutex_);
auto it = map_.find(seq); auto it = map_.find(seq);
@@ -54,7 +54,7 @@ public:
void void
finishWork(LedgerIndex seq) finishWork(LedgerIndex seq)
{ {
std::lock_guard const lock(mutex_); std::scoped_lock const lock(mutex_);
map_.erase(seq); map_.erase(seq);
await_.notify_all(); await_.notify_all();
@@ -64,7 +64,7 @@ public:
bool bool
pending(LedgerIndex seq) pending(LedgerIndex seq)
{ {
std::lock_guard const lock(mutex_); std::scoped_lock const lock(mutex_);
return map_.contains(seq); return map_.contains(seq);
} }
@@ -117,7 +117,7 @@ public:
std::map<LedgerIndex, bool> std::map<LedgerIndex, bool>
getSnapshot() const getSnapshot() const
{ {
std::lock_guard const lock(mutex_); std::scoped_lock const lock(mutex_);
return map_; return map_;
} }

View File

@@ -28,7 +28,7 @@ reduceOffer(auto const& amount)
static Number const reducedOfferPct(9999, -4); static Number const reducedOfferPct(9999, -4);
// Make sure the result is always less than amount or zero. // Make sure the result is always less than amount or zero.
NumberRoundModeGuard const mg(Number::towards_zero); NumberRoundModeGuard const mg(Number::rounding_mode::towards_zero);
return amount * reducedOfferPct; return amount * reducedOfferPct;
} }
@@ -180,7 +180,7 @@ getAMMOfferStartWithTakerGets(
if (targetQuality.rate() == beast::zero) if (targetQuality.rate() == beast::zero)
return std::nullopt; return std::nullopt;
NumberRoundModeGuard const mg(Number::to_nearest); NumberRoundModeGuard const mg(Number::rounding_mode::to_nearest);
auto const f = feeMult(tfee); auto const f = feeMult(tfee);
auto const a = 1; auto const a = 1;
auto const b = pool.in * (1 - 1 / f) / targetQuality.rate() - 2 * pool.out; auto const b = pool.in * (1 - 1 / f) / targetQuality.rate() - 2 * pool.out;
@@ -202,7 +202,7 @@ getAMMOfferStartWithTakerGets(
// Round downward to minimize the offer and to maximize the quality. // Round downward to minimize the offer and to maximize the quality.
// This has the most impact when takerGets is XRP. // This has the most impact when takerGets is XRP.
auto const takerGets = auto const takerGets =
toAmount<TOut>(getAsset(pool.out), nTakerGetsProposed, Number::downward); toAmount<TOut>(getAsset(pool.out), nTakerGetsProposed, Number::rounding_mode::downward);
return TAmounts<TIn, TOut>{swapAssetOut(pool, takerGets, tfee), takerGets}; return TAmounts<TIn, TOut>{swapAssetOut(pool, takerGets, tfee), takerGets};
}; };
@@ -247,7 +247,7 @@ getAMMOfferStartWithTakerPays(
if (targetQuality.rate() == beast::zero) if (targetQuality.rate() == beast::zero)
return std::nullopt; return std::nullopt;
NumberRoundModeGuard const mg(Number::to_nearest); NumberRoundModeGuard const mg(Number::rounding_mode::to_nearest);
auto const f = feeMult(tfee); auto const f = feeMult(tfee);
auto const& a = f; auto const& a = f;
auto const b = pool.in * (1 + f); auto const b = pool.in * (1 + f);
@@ -269,7 +269,7 @@ getAMMOfferStartWithTakerPays(
// Round downward to minimize the offer and to maximize the quality. // Round downward to minimize the offer and to maximize the quality.
// This has the most impact when takerPays is XRP. // This has the most impact when takerPays is XRP.
auto const takerPays = auto const takerPays =
toAmount<TIn>(getAsset(pool.in), nTakerPaysProposed, Number::downward); toAmount<TIn>(getAsset(pool.in), nTakerPaysProposed, Number::rounding_mode::downward);
return TAmounts<TIn, TOut>{takerPays, swapAssetIn(pool, takerPays, tfee)}; return TAmounts<TIn, TOut>{takerPays, swapAssetIn(pool, takerPays, tfee)};
}; };
@@ -341,7 +341,8 @@ changeSpotPriceQuality(
<< " " << to_string(pool.out) << " " << quality << " " << tfee; << " " << to_string(pool.out) << " " << quality << " " << tfee;
return std::nullopt; return std::nullopt;
} }
auto const takerPays = toAmount<TIn>(getAsset(pool.in), nTakerPays, Number::upward); auto const takerPays =
toAmount<TIn>(getAsset(pool.in), nTakerPays, Number::rounding_mode::upward);
// should not fail // should not fail
if (auto amounts = TAmounts<TIn, TOut>{takerPays, swapAssetIn(pool, takerPays, tfee)}; if (auto amounts = TAmounts<TIn, TOut>{takerPays, swapAssetIn(pool, takerPays, tfee)};
Quality{amounts} < quality && Quality{amounts} < quality &&
@@ -447,32 +448,32 @@ swapAssetIn(TAmounts<TIn, TOut> const& pool, TIn const& assetIn, std::uint16_t t
// fee // fee
saveNumberRoundMode const _{Number::getround()}; saveNumberRoundMode const _{Number::getround()};
Number::setround(Number::upward); Number::setround(Number::rounding_mode::upward);
auto const numerator = pool.in * pool.out; auto const numerator = pool.in * pool.out;
auto const fee = getFee(tfee); auto const fee = getFee(tfee);
Number::setround(Number::downward); Number::setround(Number::rounding_mode::downward);
auto const denom = pool.in + assetIn * (1 - fee); auto const denom = pool.in + assetIn * (1 - fee);
if (denom.signum() <= 0) if (denom.signum() <= 0)
return toAmount<TOut>(getAsset(pool.out), 0); return toAmount<TOut>(getAsset(pool.out), 0);
Number::setround(Number::upward); Number::setround(Number::rounding_mode::upward);
auto const ratio = numerator / denom; auto const ratio = numerator / denom;
Number::setround(Number::downward); Number::setround(Number::rounding_mode::downward);
auto const swapOut = pool.out - ratio; auto const swapOut = pool.out - ratio;
if (swapOut.signum() < 0) if (swapOut.signum() < 0)
return toAmount<TOut>(getAsset(pool.out), 0); return toAmount<TOut>(getAsset(pool.out), 0);
return toAmount<TOut>(getAsset(pool.out), swapOut, Number::downward); return toAmount<TOut>(getAsset(pool.out), swapOut, Number::rounding_mode::downward);
} }
return toAmount<TOut>( return toAmount<TOut>(
getAsset(pool.out), getAsset(pool.out),
pool.out - (pool.in * pool.out) / (pool.in + assetIn * feeMult(tfee)), pool.out - (pool.in * pool.out) / (pool.in + assetIn * feeMult(tfee)),
Number::downward); Number::rounding_mode::downward);
} }
/** Swap assetOut out of the pool and swap in a proportional amount /** Swap assetOut out of the pool and swap in a proportional amount
@@ -509,36 +510,36 @@ swapAssetOut(TAmounts<TIn, TOut> const& pool, TOut const& assetOut, std::uint16_
saveNumberRoundMode const _{Number::getround()}; saveNumberRoundMode const _{Number::getround()};
Number::setround(Number::upward); Number::setround(Number::rounding_mode::upward);
auto const numerator = pool.in * pool.out; auto const numerator = pool.in * pool.out;
Number::setround(Number::downward); Number::setround(Number::rounding_mode::downward);
auto const denom = pool.out - assetOut; auto const denom = pool.out - assetOut;
if (denom.signum() <= 0) if (denom.signum() <= 0)
{ {
return toMaxAmount<TIn>(getAsset(pool.in)); return toMaxAmount<TIn>(getAsset(pool.in));
} }
Number::setround(Number::upward); Number::setround(Number::rounding_mode::upward);
auto const ratio = numerator / denom; auto const ratio = numerator / denom;
auto const numerator2 = ratio - pool.in; auto const numerator2 = ratio - pool.in;
auto const fee = getFee(tfee); auto const fee = getFee(tfee);
Number::setround(Number::downward); Number::setround(Number::rounding_mode::downward);
auto const feeMult = 1 - fee; auto const feeMult = 1 - fee;
Number::setround(Number::upward); Number::setround(Number::rounding_mode::upward);
auto const swapIn = numerator2 / feeMult; auto const swapIn = numerator2 / feeMult;
if (swapIn.signum() < 0) if (swapIn.signum() < 0)
return toAmount<TIn>(getAsset(pool.in), 0); return toAmount<TIn>(getAsset(pool.in), 0);
return toAmount<TIn>(getAsset(pool.in), swapIn, Number::upward); return toAmount<TIn>(getAsset(pool.in), swapIn, Number::rounding_mode::upward);
} }
return toAmount<TIn>( return toAmount<TIn>(
getAsset(pool.in), getAsset(pool.in),
((pool.in * pool.out) / (pool.out - assetOut) - pool.in) / feeMult(tfee), ((pool.in * pool.out) / (pool.out - assetOut) - pool.in) / feeMult(tfee),
Number::upward); Number::rounding_mode::upward);
} }
/** Return square of n. /** Return square of n.
@@ -597,7 +598,8 @@ getLPTokenRounding(IsDeposit isDeposit)
{ {
// Minimize on deposit, maximize on withdraw to ensure // Minimize on deposit, maximize on withdraw to ensure
// AMM invariant sqrt(poolAsset1 * poolAsset2) >= LPTokensBalance // AMM invariant sqrt(poolAsset1 * poolAsset2) >= LPTokensBalance
return isDeposit == IsDeposit::Yes ? Number::downward : Number::upward; return isDeposit == IsDeposit::Yes ? Number::rounding_mode::downward
: Number::rounding_mode::upward;
} }
inline Number::rounding_mode inline Number::rounding_mode
@@ -605,7 +607,8 @@ getAssetRounding(IsDeposit isDeposit)
{ {
// Maximize on deposit, minimize on withdraw to ensure // Maximize on deposit, minimize on withdraw to ensure
// AMM invariant sqrt(poolAsset1 * poolAsset2) >= LPTokensBalance // AMM invariant sqrt(poolAsset1 * poolAsset2) >= LPTokensBalance
return isDeposit == IsDeposit::Yes ? Number::upward : Number::downward; return isDeposit == IsDeposit::Yes ? Number::rounding_mode::upward
: Number::rounding_mode::downward;
} }
} // namespace detail } // namespace detail

View File

@@ -19,7 +19,7 @@ loanPeriodicRate(TenthBips32 interestRate, std::uint32_t paymentInterval);
inline Number inline Number
roundPeriodicPayment(Asset const& asset, Number const& periodicPayment, std::int32_t scale) roundPeriodicPayment(Asset const& asset, Number const& periodicPayment, std::int32_t scale)
{ {
return roundToAsset(asset, periodicPayment, scale, Number::upward); return roundToAsset(asset, periodicPayment, scale, Number::rounding_mode::upward);
} }
/* Represents the breakdown of amounts to be paid and changes applied to the /* Represents the breakdown of amounts to be paid and changes applied to the

View File

@@ -21,13 +21,13 @@ namespace xrpl {
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
/** Controls the treatment of frozen account balances */ /** Controls the treatment of frozen account balances */
enum FreezeHandling { fhIGNORE_FREEZE, fhZERO_IF_FROZEN }; enum class FreezeHandling { fhIGNORE_FREEZE, fhZERO_IF_FROZEN };
/** Controls the treatment of unauthorized MPT balances */ /** Controls the treatment of unauthorized MPT balances */
enum AuthHandling { ahIGNORE_AUTH, ahZERO_IF_UNAUTHORIZED }; enum class AuthHandling { ahIGNORE_AUTH, ahZERO_IF_UNAUTHORIZED };
/** Controls whether to include the account's full spendable balance */ /** Controls whether to include the account's full spendable balance */
enum SpendableHandling { shSIMPLE_BALANCE, shFULL_BALANCE }; enum class SpendableHandling { shSIMPLE_BALANCE, shFULL_BALANCE };
enum class WaiveTransferFee : bool { No = false, Yes }; enum class WaiveTransferFee : bool { No = false, Yes };
@@ -135,7 +135,7 @@ accountHolds(
AccountID const& issuer, AccountID const& issuer,
FreezeHandling zeroIfFrozen, FreezeHandling zeroIfFrozen,
beast::Journal j, beast::Journal j,
SpendableHandling includeFullBalance = shSIMPLE_BALANCE); SpendableHandling includeFullBalance = SpendableHandling::shSIMPLE_BALANCE);
[[nodiscard]] STAmount [[nodiscard]] STAmount
accountHolds( accountHolds(
@@ -144,7 +144,7 @@ accountHolds(
Issue const& issue, Issue const& issue,
FreezeHandling zeroIfFrozen, FreezeHandling zeroIfFrozen,
beast::Journal j, beast::Journal j,
SpendableHandling includeFullBalance = shSIMPLE_BALANCE); SpendableHandling includeFullBalance = SpendableHandling::shSIMPLE_BALANCE);
[[nodiscard]] STAmount [[nodiscard]] STAmount
accountHolds( accountHolds(
@@ -154,7 +154,7 @@ accountHolds(
FreezeHandling zeroIfFrozen, FreezeHandling zeroIfFrozen,
AuthHandling zeroIfUnauthorized, AuthHandling zeroIfUnauthorized,
beast::Journal j, beast::Journal j,
SpendableHandling includeFullBalance = shSIMPLE_BALANCE); SpendableHandling includeFullBalance = SpendableHandling::shSIMPLE_BALANCE);
[[nodiscard]] STAmount [[nodiscard]] STAmount
accountHolds( accountHolds(
@@ -164,7 +164,7 @@ accountHolds(
FreezeHandling zeroIfFrozen, FreezeHandling zeroIfFrozen,
AuthHandling zeroIfUnauthorized, AuthHandling zeroIfUnauthorized,
beast::Journal j, beast::Journal j,
SpendableHandling includeFullBalance = shSIMPLE_BALANCE); SpendableHandling includeFullBalance = SpendableHandling::shSIMPLE_BALANCE);
// Returns the amount an account can spend of the currency type saDefault, or // Returns the amount an account can spend of the currency type saDefault, or
// returns saDefault if this account is the issuer of the currency in // returns saDefault if this account is the issuer of the currency in

View File

@@ -76,16 +76,16 @@ public:
If the object is not found or an error is encountered, the If the object is not found or an error is encountered, the
result will indicate the condition. result will indicate the condition.
@note This will be called concurrently. @note This will be called concurrently.
@param key A pointer to the key data. @param hash The hash of the object.
@param pObject [out] The created object if successful. @param pObject [out] The created object if successful.
@return The result of the operation. @return The result of the operation.
*/ */
virtual Status virtual Status
fetch(void const* key, std::shared_ptr<NodeObject>* pObject) = 0; fetch(uint256 const& hash, std::shared_ptr<NodeObject>* pObject) = 0;
/** Fetch a batch synchronously. */ /** Fetch a batch synchronously. */
virtual std::pair<std::vector<std::shared_ptr<NodeObject>>, Status> virtual std::pair<std::vector<std::shared_ptr<NodeObject>>, Status>
fetchBatch(std::vector<uint256 const*> const& hashes) = 0; fetchBatch(std::vector<uint256> const& hashes) = 0;
/** Store a single object. /** Store a single object.
Depending on the implementation this may happen immediately Depending on the implementation this may happen immediately

View File

@@ -9,7 +9,7 @@
namespace xrpl { namespace xrpl {
/** The types of node objects. */ /** The types of node objects. */
enum NodeObjectType : std::uint32_t { enum class NodeObjectType : std::uint32_t {
hotUNKNOWN = 0, hotUNKNOWN = 0,
hotLEDGER = 1, hotLEDGER = 1,
hotACCOUNT_NODE = 3, hotACCOUNT_NODE = 3,

View File

@@ -6,6 +6,8 @@
namespace xrpl::NodeStore { namespace xrpl::NodeStore {
// Need to be named before converting
// NOLINTNEXTLINE(cppcoreguidelines-use-enum-class)
enum { enum {
// This is only used to pre-allocate the array for // This is only used to pre-allocate the array for
// batch objects and does not affect the amount written. // batch objects and does not affect the amount written.
@@ -20,7 +22,7 @@ enum {
}; };
/** Return codes from Backend operations. */ /** Return codes from Backend operations. */
enum Status { enum class Status {
ok = 0, ok = 0,
notFound = 1, notFound = 1,
dataCorrupt = 2, dataCorrupt = 2,

View File

@@ -127,7 +127,7 @@ nodeobject_decompress(void const* in, std::size_t in_size, BufferFactory&& bf)
ostream os(out, result.second); ostream os(out, result.second);
write<std::uint32_t>(os, 0); write<std::uint32_t>(os, 0);
write<std::uint32_t>(os, 0); write<std::uint32_t>(os, 0);
write<std::uint8_t>(os, hotUNKNOWN); write<std::uint8_t>(os, static_cast<std::uint8_t>(NodeObjectType::hotUNKNOWN));
write<std::uint32_t>(os, static_cast<std::uint32_t>(HashPrefix::innerNode)); write<std::uint32_t>(os, static_cast<std::uint32_t>(HashPrefix::innerNode));
if (mask == 0) if (mask == 0)
Throw<std::runtime_error>("nodeobject codec v1: empty inner node"); Throw<std::runtime_error>("nodeobject codec v1: empty inner node");
@@ -173,7 +173,7 @@ nodeobject_decompress(void const* in, std::size_t in_size, BufferFactory&& bf)
ostream os(out, result.second); ostream os(out, result.second);
write<std::uint32_t>(os, 0); write<std::uint32_t>(os, 0);
write<std::uint32_t>(os, 0); write<std::uint32_t>(os, 0);
write<std::uint8_t>(os, hotUNKNOWN); write<std::uint8_t>(os, static_cast<std::uint8_t>(NodeObjectType::hotUNKNOWN));
write<std::uint32_t>(os, static_cast<std::uint32_t>(HashPrefix::innerNode)); write<std::uint32_t>(os, static_cast<std::uint32_t>(HashPrefix::innerNode));
write(os, is(512), 512); write(os, is(512), 512);
break; break;
@@ -307,7 +307,7 @@ filter_inner(void* in, std::size_t in_size)
ostream os(in, 9); ostream os(in, 9);
write<std::uint32_t>(os, 0); write<std::uint32_t>(os, 0);
write<std::uint32_t>(os, 0); write<std::uint32_t>(os, 0);
write<std::uint8_t>(os, hotUNKNOWN); write<std::uint8_t>(os, static_cast<std::uint8_t>(NodeObjectType::hotUNKNOWN));
} }
} }
} }

View File

@@ -17,6 +17,8 @@ namespace xrpl {
// //
// Please only append to this table. Do not "fill-in" gaps and do not re-use // Please only append to this table. Do not "fill-in" gaps and do not re-use
// or repurpose error code values. // or repurpose error code values.
// Protocol-wide, 50+ files
// NOLINTNEXTLINE(cppcoreguidelines-use-enum-class)
enum error_code_i { enum error_code_i {
// -1 represents codes not listed in this enumeration // -1 represents codes not listed in this enumeration
rpcUNKNOWN = -1, rpcUNKNOWN = -1,
@@ -148,6 +150,8 @@ enum error_code_i {
These values need to remain stable. These values need to remain stable.
*/ */
// Protocol-wide, 50+ files
// NOLINTNEXTLINE(cppcoreguidelines-use-enum-class)
enum warning_code_i { enum warning_code_i {
warnRPC_UNSUPPORTED_MAJORITY = 1001, warnRPC_UNSUPPORTED_MAJORITY = 1001,
warnRPC_AMENDMENT_BLOCKED = 1002, warnRPC_AMENDMENT_BLOCKED = 1002,

View File

@@ -29,6 +29,8 @@ namespace xrpl {
@ingroup protocol @ingroup protocol
*/ */
// Protocol-critical, hundreds of usages
// NOLINTNEXTLINE(cppcoreguidelines-use-enum-class)
enum LedgerEntryType : std::uint16_t { enum LedgerEntryType : std::uint16_t {
#pragma push_macro("LEDGER_ENTRY") #pragma push_macro("LEDGER_ENTRY")
@@ -214,6 +216,8 @@ enum LedgerEntryType : std::uint16_t {
#define TO_VALUE(name, value) name = (value), #define TO_VALUE(name, value) name = (value),
#define NULL_NAME(name, values) values #define NULL_NAME(name, values) values
#define NULL_OUTPUT(name, value) #define NULL_OUTPUT(name, value)
// Bitwise flag enum
// NOLINTNEXTLINE(cppcoreguidelines-use-enum-class)
enum LedgerSpecificFlags : std::uint32_t { XMACRO(NULL_NAME, TO_VALUE, NULL_OUTPUT) }; enum LedgerSpecificFlags : std::uint32_t { XMACRO(NULL_NAME, TO_VALUE, NULL_OUTPUT) };
// Create getter functions for each set of flags using Meyer's singleton pattern. // Create getter functions for each set of flags using Meyer's singleton pattern.

View File

@@ -66,8 +66,7 @@ struct MultiApiJson
a[key] = v; a[key] = v;
} }
// Intentionally not using class enum here, MultivarJson is scope enough enum class IsMemberResult : int { none = 0, some, all };
enum IsMemberResult : int { none = 0, some, all };
[[nodiscard]] IsMemberResult [[nodiscard]] IsMemberResult
isMember(char const* key) const isMember(char const* key) const
@@ -80,8 +79,8 @@ struct MultiApiJson
} }
if (count == 0) if (count == 0)
return none; return IsMemberResult::none;
return count < size ? some : all; return count < size ? IsMemberResult::some : IsMemberResult::all;
} }
static constexpr struct visitor_t final static constexpr struct visitor_t final

View File

@@ -16,6 +16,8 @@ namespace xrpl {
* conflicts with TxType, the GranularPermissionType is always set to a value * conflicts with TxType, the GranularPermissionType is always set to a value
* greater than the maximum value of uint16. * greater than the maximum value of uint16.
*/ */
// Macro-generated, complex
// NOLINTNEXTLINE(cppcoreguidelines-use-enum-class)
enum GranularPermissionType : std::uint32_t { enum GranularPermissionType : std::uint32_t {
#pragma push_macro("PERMISSION") #pragma push_macro("PERMISSION")
#undef PERMISSION #undef PERMISSION
@@ -28,6 +30,9 @@ enum GranularPermissionType : std::uint32_t {
#pragma pop_macro("PERMISSION") #pragma pop_macro("PERMISSION")
}; };
// Injected bare enumerators (xrpl::delegable / xrpl::notDelegable) are required by preprocessor
// tricks in tests and macro-generated code; enum class would break that.
// NOLINTNEXTLINE(cppcoreguidelines-use-enum-class)
enum Delegation { delegable, notDelegable }; enum Delegation { delegable, notDelegable };
class Permission class Permission

View File

@@ -33,7 +33,7 @@ or may not hold a value. For things not guaranteed to exist,
you use `x[~sfFoo]` because you want such a container. It you use `x[~sfFoo]` because you want such a container. It
avoids having to look something up twice, once just to see if avoids having to look something up twice, once just to see if
it exists and a second time to get/set its value. it exists and a second time to get/set its value.
([Real example](https://github.com/XRPLF/rippled/blob/35f4698aed5dce02f771b34cfbb690495cb5efcc/src/ripple/app/tx/impl/PayChan.cpp#L229-L236)) ([Real example](https://github.com/XRPLF/rippled/blob/35f4698aed5dce02f771b34cfbb690495cb5efcc/src/xrpld/app/tx/impl/PayChan.cpp#L229-L236))
The source of this "type magic" is in The source of this "type magic" is in
[SField.h](./SField.h#L296-L302). [SField.h](./SField.h#L296-L302).

View File

@@ -87,6 +87,8 @@ class STCurrency;
#define TO_ENUM(name, value) name = (value), #define TO_ENUM(name, value) name = (value),
#define TO_MAP(name, value) {#name, value}, #define TO_MAP(name, value) {#name, value},
// Protocol infrastructure, 39+ files
// NOLINTNEXTLINE(cppcoreguidelines-use-enum-class)
enum SerializedTypeID { XMACRO(TO_ENUM) }; enum SerializedTypeID { XMACRO(TO_ENUM) };
static std::map<std::string, int> const sTypeMap = {XMACRO(TO_MAP)}; static std::map<std::string, int> const sTypeMap = {XMACRO(TO_MAP)};
@@ -125,6 +127,8 @@ field_code(int id, int index)
class SField class SField
{ {
public: public:
// Need to be named before converting
// NOLINTNEXTLINE(cppcoreguidelines-use-enum-class)
enum { enum {
sMD_Never = 0x00, sMD_Never = 0x00,
sMD_ChangeOrig = 0x01, // original value when it changes sMD_ChangeOrig = 0x01, // original value when it changes

View File

@@ -11,6 +11,8 @@
namespace xrpl { namespace xrpl {
/** Kind of element in each entry of an SOTemplate. */ /** Kind of element in each entry of an SOTemplate. */
// 2026 usages, 129 files
// NOLINTNEXTLINE(cppcoreguidelines-use-enum-class)
enum SOEStyle { enum SOEStyle {
soeINVALID = -1, soeINVALID = -1,
soeREQUIRED = 0, // required soeREQUIRED = 0, // required
@@ -20,7 +22,8 @@ enum SOEStyle {
// constructed with STObject::makeInnerObject() // constructed with STObject::makeInnerObject()
}; };
/** Amount fields that can support MPT */ // Part of a Python-parsed DSL (transactions.macro); bare enumerator names required by the parser
// NOLINTNEXTLINE(cppcoreguidelines-use-enum-class)
enum SOETxMPTIssue { soeMPTNone, soeMPTSupported, soeMPTNotSupported }; enum SOETxMPTIssue { soeMPTNone, soeMPTSupported, soeMPTNotSupported };
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------

View File

@@ -319,7 +319,7 @@ STAmount::STAmount(
: STBase(name), mAsset(asset), mValue(mantissa), mOffset(exponent), mIsNegative(negative) : STBase(name), mAsset(asset), mValue(mantissa), mOffset(exponent), mIsNegative(negative)
{ {
// mValue is uint64, but needs to fit in the range of int64 // mValue is uint64, but needs to fit in the range of int64
if (Number::getMantissaScale() == MantissaRange::small) if (Number::getMantissaScale() == MantissaRange::mantissa_scale::small)
{ {
XRPL_ASSERT( XRPL_ASSERT(
mValue <= std::numeric_limits<std::int64_t>::max(), mValue <= std::numeric_limits<std::int64_t>::max(),

View File

@@ -18,6 +18,8 @@ struct JsonOptions
using underlying_t = unsigned int; using underlying_t = unsigned int;
underlying_t value; underlying_t value;
// Bitwise flags with operator~
// NOLINTNEXTLINE(cppcoreguidelines-use-enum-class)
enum values : underlying_t { enum values : underlying_t {
// clang-format off // clang-format off
none = 0b0000'0000, none = 0b0000'0000,

View File

@@ -413,9 +413,9 @@ public:
class FieldErr; class FieldErr;
private: private:
enum WhichFields : bool { enum class WhichFields : bool {
// These values are carefully chosen to do the right thing if passed // These values are carefully chosen to do the right thing if passed
// to SField::shouldInclude (bool) // to SField::shouldInclude (bool) via static_cast<bool>
omitSigningFields = false, omitSigningFields = false,
withAllFields = true withAllFields = true
}; };
@@ -987,7 +987,7 @@ STObject::isFree() const
inline void inline void
STObject::addWithoutSigningFields(Serializer& s) const STObject::addWithoutSigningFields(Serializer& s) const
{ {
add(s, omitSigningFields); add(s, WhichFields::omitSigningFields);
} }
// VFALCO NOTE does this return an expensive copy of an object with a // VFALCO NOTE does this return an expensive copy of an object with a
@@ -997,7 +997,7 @@ inline Serializer
STObject::getSerializer() const STObject::getSerializer() const
{ {
Serializer s; Serializer s;
add(s, withAllFields); add(s, WhichFields::withAllFields);
return s; return s;
} }

View File

@@ -25,6 +25,8 @@ class STPathElement final : public CountedObject<STPathElement>
std::size_t hash_value_; std::size_t hash_value_;
public: public:
// Bitwise values (typeCurrency | typeMPT)
// NOLINTNEXTLINE(cppcoreguidelines-use-enum-class)
enum Type { enum Type {
typeNone = 0x00, typeNone = 0x00,
typeAccount = 0x01, // Rippling through an account (vs taking an offer). typeAccount = 0x01, // Rippling through an account (vs taking an offer).

View File

@@ -35,7 +35,7 @@ namespace xrpl {
class SeqProxy class SeqProxy
{ {
public: public:
enum Type : std::uint8_t { seq = 0, ticket }; enum class Type : std::uint8_t { seq = 0, ticket };
private: private:
std::uint32_t value_; std::uint32_t value_;
@@ -67,13 +67,13 @@ public:
[[nodiscard]] constexpr bool [[nodiscard]] constexpr bool
isSeq() const isSeq() const
{ {
return type_ == seq; return type_ == Type::seq;
} }
[[nodiscard]] constexpr bool [[nodiscard]] constexpr bool
isTicket() const isTicket() const
{ {
return type_ == ticket; return type_ == Type::ticket;
} }
// Occasionally it is convenient to be able to increase the value_ // Occasionally it is convenient to be able to increase the value_

View File

@@ -19,6 +19,8 @@ using TERUnderlyingType = int;
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
// Protocol-critical, mixed with custom TER wrapper type, hundreds of usages
// NOLINTNEXTLINE(cppcoreguidelines-use-enum-class)
enum TELcodes : TERUnderlyingType { enum TELcodes : TERUnderlyingType {
// Note: Range is stable. // Note: Range is stable.
// Exact numbers are used in ripple-binary-codec: // Exact numbers are used in ripple-binary-codec:
@@ -50,6 +52,8 @@ enum TELcodes : TERUnderlyingType {
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
// Protocol-critical, mixed with custom TER wrapper type, hundreds of usages
// NOLINTNEXTLINE(cppcoreguidelines-use-enum-class)
enum TEMcodes : TERUnderlyingType { enum TEMcodes : TERUnderlyingType {
// Note: Range is stable. // Note: Range is stable.
// Exact numbers are used in ripple-binary-codec: // Exact numbers are used in ripple-binary-codec:
@@ -126,6 +130,8 @@ enum TEMcodes : TERUnderlyingType {
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
// Protocol-critical, mixed with custom TER wrapper type, hundreds of usages
// NOLINTNEXTLINE(cppcoreguidelines-use-enum-class)
enum TEFcodes : TERUnderlyingType { enum TEFcodes : TERUnderlyingType {
// Note: Range is stable. // Note: Range is stable.
// Exact numbers are used in ripple-binary-codec: // Exact numbers are used in ripple-binary-codec:
@@ -170,6 +176,8 @@ enum TEFcodes : TERUnderlyingType {
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
// Protocol-critical, mixed with custom TER wrapper type, hundreds of usages
// NOLINTNEXTLINE(cppcoreguidelines-use-enum-class)
enum TERcodes : TERUnderlyingType { enum TERcodes : TERUnderlyingType {
// Note: Range is stable. // Note: Range is stable.
// Exact numbers are used in ripple-binary-codec: // Exact numbers are used in ripple-binary-codec:
@@ -214,6 +222,8 @@ enum TERcodes : TERUnderlyingType {
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
// Protocol-critical, mixed with custom TER wrapper type, hundreds of usages
// NOLINTNEXTLINE(cppcoreguidelines-use-enum-class)
enum TEScodes : TERUnderlyingType { enum TEScodes : TERUnderlyingType {
// Note: Exact number must stay stable. This code is stored by value // Note: Exact number must stay stable. This code is stored by value
// in metadata for historic transactions. // in metadata for historic transactions.
@@ -229,6 +239,8 @@ enum TEScodes : TERUnderlyingType {
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
// Protocol-critical, mixed with custom TER wrapper type, hundreds of usages
// NOLINTNEXTLINE(cppcoreguidelines-use-enum-class)
enum TECcodes : TERUnderlyingType { enum TECcodes : TERUnderlyingType {
// Note: Exact numbers must stay stable. These codes are stored by // Note: Exact numbers must stay stable. These codes are stored by
// value in metadata for historic transactions. // value in metadata for historic transactions.

View File

@@ -35,6 +35,8 @@ namespace xrpl {
@ingroup protocol @ingroup protocol
*/ */
// clang-format off // clang-format off
// Protocol-critical, hundreds of usages
// NOLINTNEXTLINE(cppcoreguidelines-use-enum-class)
enum TxType : std::uint16_t enum TxType : std::uint16_t
{ {

View File

@@ -130,6 +130,19 @@ public:
return sle_->at(sfFlags); return sle_->at(sfFlags);
} }
/**
* @brief Check if a specific flag is set.
*
* @param f The flag bitmask to check
* @return true if all bits in f are set in the flags field
*/
[[nodiscard]]
bool
isFlag(std::uint32_t f) const
{
return sle_->isFlag(f);
}
/** /**
* @brief Get the underlying SLE object. * @brief Get the underlying SLE object.
* *

View File

@@ -3,7 +3,7 @@
namespace xrpl::Resource { namespace xrpl::Resource {
/** The disposition of a consumer after applying a load charge. */ /** The disposition of a consumer after applying a load charge. */
enum Disposition { enum class Disposition {
/** No action required. */ /** No action required. */
ok ok

View File

@@ -39,7 +39,7 @@ struct Entry : public beast::List<Entry>::Node
[[nodiscard]] bool [[nodiscard]] bool
isUnlimited() const isUnlimited() const
{ {
return key->kind == kindUnlimited; return key->kind == Kind::kindUnlimited;
} }
// Balance including remote contributions // Balance including remote contributions

View File

@@ -10,6 +10,6 @@ namespace xrpl::Resource {
* subjected to administrative restrictions, such as * subjected to administrative restrictions, such as
* use of some RPC commands like "stop". * use of some RPC commands like "stop".
*/ */
enum Kind { kindInbound, kindOutbound, kindUnlimited }; enum class Kind { kindInbound, kindOutbound, kindUnlimited };
} // namespace xrpl::Resource } // namespace xrpl::Resource

View File

@@ -92,11 +92,11 @@ public:
Entry* entry(nullptr); Entry* entry(nullptr);
{ {
std::lock_guard const _(lock_); std::scoped_lock const _(lock_);
auto [resultIt, resultInserted] = table_.emplace( auto [resultIt, resultInserted] = table_.emplace(
std::piecewise_construct, std::piecewise_construct,
std::make_tuple(kindInbound, address.at_port(0)), // Key std::make_tuple(Kind::kindInbound, address.at_port(0)), // Key
std::make_tuple(m_clock.now())); // Entry std::make_tuple(m_clock.now())); // Entry
entry = &resultIt->second; entry = &resultIt->second;
entry->key = &resultIt->first; entry->key = &resultIt->first;
@@ -122,11 +122,11 @@ public:
Entry* entry(nullptr); Entry* entry(nullptr);
{ {
std::lock_guard const _(lock_); std::scoped_lock const _(lock_);
auto [resultIt, resultInserted] = table_.emplace( auto [resultIt, resultInserted] = table_.emplace(
std::piecewise_construct, std::piecewise_construct,
std::make_tuple(kindOutbound, address), // Key std::make_tuple(Kind::kindOutbound, address), // Key
std::make_tuple(m_clock.now())); // Entry std::make_tuple(m_clock.now())); // Entry
entry = &resultIt->second; entry = &resultIt->second;
entry->key = &resultIt->first; entry->key = &resultIt->first;
@@ -155,11 +155,11 @@ public:
Entry* entry(nullptr); Entry* entry(nullptr);
{ {
std::lock_guard const _(lock_); std::scoped_lock const _(lock_);
auto [resultIt, resultInserted] = table_.emplace( auto [resultIt, resultInserted] = table_.emplace(
std::piecewise_construct, std::piecewise_construct,
std::make_tuple(kindUnlimited, address.at_port(1)), // Key std::make_tuple(Kind::kindUnlimited, address.at_port(1)), // Key
std::make_tuple(m_clock.now())); // Entry std::make_tuple(m_clock.now())); // Entry
entry = &resultIt->second; entry = &resultIt->second;
entry->key = &resultIt->first; entry->key = &resultIt->first;
@@ -190,7 +190,7 @@ public:
clock_type::time_point const now(m_clock.now()); clock_type::time_point const now(m_clock.now());
Json::Value ret(Json::objectValue); Json::Value ret(Json::objectValue);
std::lock_guard const _(lock_); std::scoped_lock const _(lock_);
for (auto& inboundEntry : inbound_) for (auto& inboundEntry : inbound_)
{ {
@@ -235,7 +235,7 @@ public:
clock_type::time_point const now(m_clock.now()); clock_type::time_point const now(m_clock.now());
Gossip gossip; Gossip gossip;
std::lock_guard const _(lock_); std::scoped_lock const _(lock_);
gossip.items.reserve(inbound_.size()); gossip.items.reserve(inbound_.size());
@@ -260,7 +260,7 @@ public:
{ {
auto const elapsed = m_clock.now(); auto const elapsed = m_clock.now();
{ {
std::lock_guard const _(lock_); std::scoped_lock const _(lock_);
auto [resultIt, resultInserted] = importTable_.emplace( auto [resultIt, resultInserted] = importTable_.emplace(
std::piecewise_construct, std::piecewise_construct,
std::make_tuple(origin), // Key std::make_tuple(origin), // Key
@@ -317,7 +317,7 @@ public:
void void
periodicActivity() periodicActivity()
{ {
std::lock_guard const _(lock_); std::scoped_lock const _(lock_);
auto const elapsed = m_clock.now(); auto const elapsed = m_clock.now();
@@ -375,7 +375,7 @@ public:
void void
erase(Table::iterator iter) erase(Table::iterator iter)
{ {
std::lock_guard const _(lock_); std::scoped_lock const _(lock_);
Entry& entry(iter->second); Entry& entry(iter->second);
XRPL_ASSERT(entry.refcount == 0, "xrpl::Resource::Logic::erase : entry not used"); XRPL_ASSERT(entry.refcount == 0, "xrpl::Resource::Logic::erase : entry not used");
inactive_.erase(inactive_.iterator_to(entry)); inactive_.erase(inactive_.iterator_to(entry));
@@ -385,27 +385,27 @@ public:
void void
acquire(Entry& entry) acquire(Entry& entry)
{ {
std::lock_guard const _(lock_); std::scoped_lock const _(lock_);
++entry.refcount; ++entry.refcount;
} }
void void
release(Entry& entry) release(Entry& entry)
{ {
std::lock_guard const _(lock_); std::scoped_lock const _(lock_);
if (--entry.refcount == 0) if (--entry.refcount == 0)
{ {
JLOG(m_journal.debug()) << "Inactive " << entry; JLOG(m_journal.debug()) << "Inactive " << entry;
switch (entry.key->kind) switch (entry.key->kind)
{ {
case kindInbound: case Kind::kindInbound:
inbound_.erase(inbound_.iterator_to(entry)); inbound_.erase(inbound_.iterator_to(entry));
break; break;
case kindOutbound: case Kind::kindOutbound:
outbound_.erase(outbound_.iterator_to(entry)); outbound_.erase(outbound_.iterator_to(entry));
break; break;
case kindUnlimited: case Kind::kindUnlimited:
admin_.erase(admin_.iterator_to(entry)); admin_.erase(admin_.iterator_to(entry));
break; break;
default: default:
@@ -443,7 +443,7 @@ public:
if (!context.empty()) if (!context.empty())
context = " (" + context + ")"; context = " (" + context + ")";
std::lock_guard const _(lock_); std::scoped_lock const _(lock_);
clock_type::time_point const now(m_clock.now()); clock_type::time_point const now(m_clock.now());
int const balance(entry.add(fee.cost(), now)); int const balance(entry.add(fee.cost(), now));
JLOG(getStream(fee.cost(), m_journal)) << "Charging " << entry << " for " << fee << context; JLOG(getStream(fee.cost(), m_journal)) << "Charging " << entry << " for " << fee << context;
@@ -456,7 +456,7 @@ public:
if (entry.isUnlimited()) if (entry.isUnlimited())
return false; return false;
std::lock_guard const _(lock_); std::scoped_lock const _(lock_);
bool notify(false); bool notify(false);
auto const elapsed = m_clock.now(); auto const elapsed = m_clock.now();
if (entry.balance(m_clock.now()) >= warningThreshold && elapsed != entry.lastWarningTime) if (entry.balance(m_clock.now()) >= warningThreshold && elapsed != entry.lastWarningTime)
@@ -479,7 +479,7 @@ public:
if (entry.isUnlimited()) if (entry.isUnlimited())
return false; return false;
std::lock_guard const _(lock_); std::scoped_lock const _(lock_);
bool drop(false); bool drop(false);
clock_type::time_point const now(m_clock.now()); clock_type::time_point const now(m_clock.now());
int const balance(entry.balance(now)); int const balance(entry.balance(now));
@@ -501,7 +501,7 @@ public:
int int
balance(Entry& entry) balance(Entry& entry)
{ {
std::lock_guard const _(lock_); std::scoped_lock const _(lock_);
return entry.balance(m_clock.now()); return entry.balance(m_clock.now());
} }
@@ -530,7 +530,7 @@ public:
{ {
clock_type::time_point const now(m_clock.now()); clock_type::time_point const now(m_clock.now());
std::lock_guard const _(lock_); std::scoped_lock const _(lock_);
{ {
beast::PropertyStream::Set s("inbound", map); beast::PropertyStream::Set s("inbound", map);

View File

@@ -5,6 +5,8 @@
namespace xrpl::Resource { namespace xrpl::Resource {
/** Tunable constants. */ /** Tunable constants. */
// Need to be named before converting
// NOLINTNEXTLINE(cppcoreguidelines-use-enum-class)
enum { enum {
// Balance at which a warning is issued // Balance at which a warning is issued
warningThreshold = 5000 warningThreshold = 5000

View File

@@ -35,28 +35,28 @@ public:
setRemoteFee(std::uint32_t f) setRemoteFee(std::uint32_t f)
{ {
JLOG(j_.trace()) << "setRemoteFee: " << f; JLOG(j_.trace()) << "setRemoteFee: " << f;
std::lock_guard const sl(lock_); std::scoped_lock const sl(lock_);
remoteTxnLoadFee_ = f; remoteTxnLoadFee_ = f;
} }
std::uint32_t std::uint32_t
getRemoteFee() const getRemoteFee() const
{ {
std::lock_guard const sl(lock_); std::scoped_lock const sl(lock_);
return remoteTxnLoadFee_; return remoteTxnLoadFee_;
} }
std::uint32_t std::uint32_t
getLocalFee() const getLocalFee() const
{ {
std::lock_guard const sl(lock_); std::scoped_lock const sl(lock_);
return localTxnLoadFee_; return localTxnLoadFee_;
} }
std::uint32_t std::uint32_t
getClusterFee() const getClusterFee() const
{ {
std::lock_guard const sl(lock_); std::scoped_lock const sl(lock_);
return clusterTxnLoadFee_; return clusterTxnLoadFee_;
} }
@@ -69,14 +69,14 @@ public:
std::uint32_t std::uint32_t
getLoadFactor() const getLoadFactor() const
{ {
std::lock_guard const sl(lock_); std::scoped_lock const sl(lock_);
return std::max({clusterTxnLoadFee_, localTxnLoadFee_, remoteTxnLoadFee_}); return std::max({clusterTxnLoadFee_, localTxnLoadFee_, remoteTxnLoadFee_});
} }
std::pair<std::uint32_t, std::uint32_t> std::pair<std::uint32_t, std::uint32_t>
getScalingFactors() const getScalingFactors() const
{ {
std::lock_guard const sl(lock_); std::scoped_lock const sl(lock_);
return std::make_pair( return std::make_pair(
std::max(localTxnLoadFee_, remoteTxnLoadFee_), std::max(localTxnLoadFee_, remoteTxnLoadFee_),
@@ -87,7 +87,7 @@ public:
setClusterFee(std::uint32_t fee) setClusterFee(std::uint32_t fee)
{ {
JLOG(j_.trace()) << "setClusterFee: " << fee; JLOG(j_.trace()) << "setClusterFee: " << fee;
std::lock_guard const sl(lock_); std::scoped_lock const sl(lock_);
clusterTxnLoadFee_ = fee; clusterTxnLoadFee_ = fee;
} }
@@ -99,14 +99,14 @@ public:
bool bool
isLoadedLocal() const isLoadedLocal() const
{ {
std::lock_guard const sl(lock_); std::scoped_lock const sl(lock_);
return (raiseCount_ != 0) || (localTxnLoadFee_ != lftNormalFee); return (raiseCount_ != 0) || (localTxnLoadFee_ != lftNormalFee);
} }
bool bool
isLoadedCluster() const isLoadedCluster() const
{ {
std::lock_guard const sl(lock_); std::scoped_lock const sl(lock_);
return (raiseCount_ != 0) || (localTxnLoadFee_ != lftNormalFee) || return (raiseCount_ != 0) || (localTxnLoadFee_ != lftNormalFee) ||
(clusterTxnLoadFee_ != lftNormalFee); (clusterTxnLoadFee_ != lftNormalFee);
} }

View File

@@ -38,6 +38,8 @@ protected:
using endpoint_type = boost::asio::ip::tcp::endpoint; using endpoint_type = boost::asio::ip::tcp::endpoint;
using yield_context = boost::asio::yield_context; using yield_context = boost::asio::yield_context;
// Need to be named before converting
// NOLINTNEXTLINE(cppcoreguidelines-use-enum-class)
enum { enum {
// Size of our read/write buffer // Size of our read/write buffer
bufferSize = 4 * 1024, bufferSize = 4 * 1024,
@@ -303,7 +305,7 @@ BaseHTTPPeer<Handler, Impl>::on_write(error_code const& ec, std::size_t bytes_tr
return fail(ec, "write"); return fail(ec, "write");
bytes_out_ += bytes_transferred; bytes_out_ += bytes_transferred;
{ {
std::lock_guard const lock(mutex_); std::scoped_lock const lock(mutex_);
wq2_.clear(); wq2_.clear();
wq2_.reserve(wq_.size()); wq2_.reserve(wq_.size());
std::swap(wq2_, wq_); std::swap(wq2_, wq_);
@@ -395,7 +397,7 @@ BaseHTTPPeer<Handler, Impl>::write(void const* buf, std::size_t bytes)
if (bytes == 0) if (bytes == 0)
return; return;
if ([&] { if ([&] {
std::lock_guard const lock(mutex_); std::scoped_lock const lock(mutex_);
wq_.emplace_back(buf, bytes); wq_.emplace_back(buf, bytes);
return wq_.size() == 1 && wq2_.size() == 0; return wq_.size() == 1 && wq2_.size() == 0;
}()) }())
@@ -449,7 +451,7 @@ BaseHTTPPeer<Handler, Impl>::complete()
complete_ = true; complete_ = true;
{ {
std::lock_guard const lock(mutex_); std::scoped_lock const lock(mutex_);
if (!wq_.empty() && !wq2_.empty()) if (!wq_.empty() && !wq2_.empty())
return; return;
} }
@@ -484,7 +486,7 @@ BaseHTTPPeer<Handler, Impl>::close(bool graceful)
{ {
graceful_ = true; graceful_ = true;
{ {
std::lock_guard const lock(mutex_); std::scoped_lock const lock(mutex_);
if (!wq_.empty() || !wq2_.empty()) if (!wq_.empty() || !wq2_.empty())
return; return;
} }

View File

@@ -62,6 +62,8 @@ class ServerImpl : public Server
private: private:
using clock_type = std::chrono::system_clock; using clock_type = std::chrono::system_clock;
// Need to be named before converting
// NOLINTNEXTLINE(cppcoreguidelines-use-enum-class)
enum { historySize = 100 }; enum { historySize = 100 };
Handler& handler_; Handler& handler_;

View File

@@ -165,7 +165,7 @@ io_list::work::destroy()
return; return;
std::function<void(void)> f; std::function<void(void)> f;
{ {
std::lock_guard const lock(ios_->m_); std::scoped_lock const lock(ios_->m_);
ios_->map_.erase(this); ios_->map_.erase(this);
if (--ios_->n_ == 0 && ios_->closed_) if (--ios_->n_ == 0 && ios_->closed_)
{ {
@@ -195,7 +195,7 @@ io_list::emplace(Args&&... args)
auto sp = std::make_shared<T>(std::forward<Args>(args)...); auto sp = std::make_shared<T>(std::forward<Args>(args)...);
decltype(sp) dead; decltype(sp) dead;
std::lock_guard const lock(m_); std::scoped_lock const lock(m_);
if (!closed_) if (!closed_)
{ {
++n_; ++n_;

View File

@@ -22,6 +22,8 @@ private:
using CacheType = KeyCache; using CacheType = KeyCache;
public: public:
// Need to be named before converting
// NOLINTNEXTLINE(cppcoreguidelines-use-enum-class)
enum { defaultCacheTargetSize = 0 }; enum { defaultCacheTargetSize = 0 };
using key_type = uint256; using key_type = uint256;

View File

@@ -123,6 +123,8 @@ public:
Transactor(Transactor const&) = delete; Transactor(Transactor const&) = delete;
Transactor& Transactor&
operator=(Transactor const&) = delete; operator=(Transactor const&) = delete;
// 68 transactor subclass files
// NOLINTNEXTLINE(cppcoreguidelines-use-enum-class)
enum ConsequencesFactoryType { Normal, Blocker, Custom }; enum ConsequencesFactoryType { Normal, Blocker, Custom };
/** Process the transaction. */ /** Process the transaction. */

View File

@@ -39,7 +39,7 @@ class TxConsequences
public: public:
/// Describes how the transaction affects subsequent /// Describes how the transaction affects subsequent
/// transactions /// transactions
enum Category { enum class Category {
/// Moves currency around, creates offers, etc. /// Moves currency around, creates offers, etc.
normal = 0, normal = 0,
/// Affects the ability of subsequent transactions /// Affects the ability of subsequent transactions

View File

@@ -25,6 +25,8 @@ not have the relevant amendments enabled_. It's intentionally a pain in the neck
so that bad code gets caught and fixed as early as possible. so that bad code gets caught and fixed as early as possible.
*/ */
// Bitwise flags, 86 files
// NOLINTNEXTLINE(cppcoreguidelines-use-enum-class)
enum Privilege { enum Privilege {
noPriv = 0x0000, // The transaction can not do any of the enumerated operations noPriv = 0x0000, // The transaction can not do any of the enumerated operations
createAcct = 0x0001, // The transaction can create a new ACCOUNT_ROOT object. createAcct = 0x0001, // The transaction can create a new ACCOUNT_ROOT object.

View File

@@ -35,10 +35,10 @@ public:
*/ */
class ValidMPTPayment class ValidMPTPayment
{ {
enum Order { Before = 0, After = 1 }; enum class Order { Before = 0, After = 1 };
struct MPTData struct MPTData
{ {
std::array<std::int64_t, After + 1> outstanding{}; std::array<std::int64_t, 2> outstanding{};
// sum (MPT after - MPT before) // sum (MPT after - MPT before)
std::int64_t mptAmount{0}; std::int64_t mptAmount{0};
}; };

View File

@@ -21,7 +21,7 @@ class AMMContext;
enum class DebtDirection { issues, redeems }; enum class DebtDirection { issues, redeems };
enum class QualityDirection { in, out }; enum class QualityDirection { in, out };
enum class StrandDirection { forward, reverse }; enum class StrandDirection { forward, reverse };
enum OfferCrossing { no = 0, yes = 1, sell = 2 }; enum class OfferCrossing { no = 0, yes = 1, sell = 2 };
inline bool inline bool
redeems(DebtDirection dir) redeems(DebtDirection dir)

View File

@@ -665,7 +665,7 @@ flow(
// the previous strand execution failed. It has to be reset // the previous strand execution failed. It has to be reset
// since this strand might not have AMM liquidity. // since this strand might not have AMM liquidity.
ammContext.clear(); ammContext.clear();
if (offerCrossing && limitQuality) if (offerCrossing != OfferCrossing::no && limitQuality)
{ {
auto const strandQ = qualityUpperBound(sb, *strand); auto const strandQ = qualityUpperBound(sb, *strand);
if (!strandQ || *strandQ < *limitQuality) if (!strandQ || *strandQ < *limitQuality)
@@ -797,7 +797,8 @@ flow(
// fixFillOrKill amendment: // fixFillOrKill amendment:
// That case is handled here if tfSell is also not set; i.e, // That case is handled here if tfSell is also not set; i.e,
// case 1. // case 1.
if (!offerCrossing || (fillOrKillEnabled && offerCrossing != OfferCrossing::sell)) if (offerCrossing == OfferCrossing::no ||
(fillOrKillEnabled && offerCrossing != OfferCrossing::sell))
return {tecPATH_PARTIAL, actualIn, actualOut, std::move(ofrsToRmOnFail)}; return {tecPATH_PARTIAL, actualIn, actualOut, std::move(ofrsToRmOnFail)};
} }
else if (actualOut == beast::zero) else if (actualOut == beast::zero)
@@ -805,7 +806,7 @@ flow(
return {tecPATH_DRY, std::move(ofrsToRmOnFail)}; return {tecPATH_DRY, std::move(ofrsToRmOnFail)};
} }
} }
if (offerCrossing && if (offerCrossing != OfferCrossing::no &&
(!partialPayment && (!fillOrKillEnabled || offerCrossing == OfferCrossing::sell))) (!partialPayment && (!fillOrKillEnabled || offerCrossing == OfferCrossing::sell)))
{ {
// If we're offer crossing and partialPayment is *not* true, then // If we're offer crossing and partialPayment is *not* true, then

View File

@@ -18,8 +18,8 @@ class SignerListSet : public Transactor
{ {
private: private:
// Values determined during preCompute for use later. // Values determined during preCompute for use later.
enum Operation { unknown, set, destroy }; enum class Operation { unknown, set, destroy };
Operation do_{unknown}; Operation do_{Operation::unknown};
std::uint32_t quorum_{0}; std::uint32_t quorum_{0};
std::vector<SignerEntries::SignerEntry> signers_; std::vector<SignerEntries::SignerEntry> signers_;

View File

@@ -7,7 +7,7 @@ namespace xrpl {
class LedgerStateFix : public Transactor class LedgerStateFix : public Transactor
{ {
public: public:
enum FixType : std::uint16_t { enum class FixType : std::uint16_t {
nfTokenPageLink = 1, nfTokenPageLink = 1,
}; };

View File

@@ -120,7 +120,7 @@ Logs::open(boost::filesystem::path const& pathToLogFile)
beast::Journal::Sink& beast::Journal::Sink&
Logs::get(std::string const& name) Logs::get(std::string const& name)
{ {
std::lock_guard const lock(mutex_); std::scoped_lock const lock(mutex_);
auto const result = sinks_.emplace(name, makeSink(name, thresh_)); auto const result = sinks_.emplace(name, makeSink(name, thresh_));
return *result.first->second; return *result.first->second;
} }
@@ -146,7 +146,7 @@ Logs::threshold() const
void void
Logs::threshold(beast::severities::Severity thresh) Logs::threshold(beast::severities::Severity thresh)
{ {
std::lock_guard const lock(mutex_); std::scoped_lock const lock(mutex_);
thresh_ = thresh; thresh_ = thresh;
for (auto& sink : sinks_) for (auto& sink : sinks_)
sink.second->threshold(thresh); sink.second->threshold(thresh);
@@ -156,7 +156,7 @@ std::vector<std::pair<std::string, std::string>>
Logs::partition_severities() const Logs::partition_severities() const
{ {
std::vector<std::pair<std::string, std::string>> list; std::vector<std::pair<std::string, std::string>> list;
std::lock_guard const lock(mutex_); std::scoped_lock const lock(mutex_);
list.reserve(sinks_.size()); list.reserve(sinks_.size());
for (auto const& [name, sink] : sinks_) for (auto const& [name, sink] : sinks_)
list.emplace_back(name, toString(fromSeverity(sink->threshold()))); list.emplace_back(name, toString(fromSeverity(sink->threshold())));
@@ -172,7 +172,7 @@ Logs::write(
{ {
std::string s; std::string s;
format(s, text, level, partition); format(s, text, level, partition);
std::lock_guard const lock(mutex_); std::scoped_lock const lock(mutex_);
file_.writeln(s); file_.writeln(s);
if (!silent_) if (!silent_)
std::cerr << s << '\n'; std::cerr << s << '\n';
@@ -184,7 +184,7 @@ Logs::write(
std::string std::string
Logs::rotate() Logs::rotate()
{ {
std::lock_guard const lock(mutex_); std::scoped_lock const lock(mutex_);
bool const wasOpened = file_.closeAndReopen(); bool const wasOpened = file_.closeAndReopen();
if (wasOpened) if (wasOpened)
return "The log file was closed and reopened."; return "The log file was closed and reopened.";
@@ -412,7 +412,7 @@ public:
std::unique_ptr<beast::Journal::Sink> std::unique_ptr<beast::Journal::Sink>
set(std::unique_ptr<beast::Journal::Sink> sink) set(std::unique_ptr<beast::Journal::Sink> sink)
{ {
std::lock_guard const _(m_); std::scoped_lock const _(m_);
using std::swap; using std::swap;
swap(holder_, sink); swap(holder_, sink);
@@ -432,7 +432,7 @@ public:
beast::Journal::Sink& beast::Journal::Sink&
get() get()
{ {
std::lock_guard const _(m_); std::scoped_lock const _(m_);
return sink_.get(); return sink_.get();
} }
}; };

View File

@@ -27,7 +27,7 @@ using int128_t = __int128_t;
namespace xrpl { namespace xrpl {
thread_local Number::rounding_mode Number::mode_ = Number::to_nearest; thread_local Number::rounding_mode Number::mode_ = Number::rounding_mode::to_nearest;
thread_local std::reference_wrapper<MantissaRange const> Number::range_ = largeRange; thread_local std::reference_wrapper<MantissaRange const> Number::range_ = largeRange;
Number::rounding_mode Number::rounding_mode
@@ -51,9 +51,10 @@ Number::getMantissaScale()
void void
Number::setMantissaScale(MantissaRange::mantissa_scale scale) Number::setMantissaScale(MantissaRange::mantissa_scale scale)
{ {
if (scale != MantissaRange::small && scale != MantissaRange::large) if (scale != MantissaRange::mantissa_scale::small &&
scale != MantissaRange::mantissa_scale::large)
LogicError("Unknown mantissa scale"); LogicError("Unknown mantissa scale");
range_ = scale == MantissaRange::small ? smallRange : largeRange; range_ = scale == MantissaRange::mantissa_scale::small ? smallRange : largeRange;
} }
// Guard // Guard
@@ -176,10 +177,10 @@ Number::Guard::round() const noexcept
{ {
auto mode = Number::getround(); auto mode = Number::getround();
if (mode == towards_zero) if (mode == rounding_mode::towards_zero)
return -1; return -1;
if (mode == downward) if (mode == rounding_mode::downward)
{ {
if (sbit_) if (sbit_)
{ {
@@ -189,7 +190,7 @@ Number::Guard::round() const noexcept
return -1; return -1;
} }
if (mode == upward) if (mode == rounding_mode::upward)
{ {
if (sbit_) if (sbit_)
return -1; return -1;
@@ -729,7 +730,7 @@ Number::operator/=(Number const& y)
// f can be up to 10^(38-19) = 10^19 safely // f can be up to 10^(38-19) = 10^19 safely
static_assert(smallRange.log == 15); static_assert(smallRange.log == 15);
static_assert(largeRange.log == 18); static_assert(largeRange.log == 18);
bool const small = Number::getMantissaScale() == MantissaRange::small; bool const small = Number::getMantissaScale() == MantissaRange::mantissa_scale::small;
uint128_t const f = small ? 100'000'000'000'000'000 : 10'000'000'000'000'000'000ULL; uint128_t const f = small ? 100'000'000'000'000'000 : 10'000'000'000'000'000'000ULL;
XRPL_ASSERT_PARTS(f >= minMantissa * 10, "Number::operator/=", "factor expected size"); XRPL_ASSERT_PARTS(f >= minMantissa * 10, "Number::operator/=", "factor expected size");

View File

@@ -177,7 +177,7 @@ public:
if (m_stopped.exchange(false)) if (m_stopped.exchange(false))
{ {
{ {
std::lock_guard const lk{m_mut}; std::scoped_lock const lk{m_mut};
m_asyncHandlersCompleted = false; m_asyncHandlersCompleted = false;
} }
addReference(); addReference();

View File

@@ -42,7 +42,7 @@ seconds_clock_thread::~seconds_clock_thread()
XRPL_ASSERT( XRPL_ASSERT(
thread_.joinable(), "beast::seconds_clock_thread::~seconds_clock_thread : thread joinable"); thread_.joinable(), "beast::seconds_clock_thread::~seconds_clock_thread : thread joinable");
{ {
std::lock_guard const lock(mut_); std::scoped_lock const lock(mut_);
stop_ = true; stop_ = true;
} // publish stop_ asap so if waiting thread times-out, it will see it } // publish stop_ asap so if waiting thread times-out, it will see it
cv_.notify_one(); cv_.notify_one();

View File

@@ -204,6 +204,8 @@ class StatsDCollectorImp : public StatsDCollector,
public std::enable_shared_from_this<StatsDCollectorImp> public std::enable_shared_from_this<StatsDCollectorImp>
{ {
private: private:
// Need to be named before converting
// NOLINTNEXTLINE(cppcoreguidelines-use-enum-class)
enum { enum {
// max_packet_size = 484 // max_packet_size = 484
max_packet_size = 1472 max_packet_size = 1472
@@ -293,14 +295,14 @@ public:
void void
add(StatsDMetricBase& metric) add(StatsDMetricBase& metric)
{ {
std::lock_guard const _(metricsLock_); std::scoped_lock const _(metricsLock_);
metrics_.push_back(metric); metrics_.push_back(metric);
} }
void void
remove(StatsDMetricBase& metric) remove(StatsDMetricBase& metric)
{ {
std::lock_guard const _(metricsLock_); std::scoped_lock const _(metricsLock_);
metrics_.erase(metrics_.iterator_to(metric)); metrics_.erase(metrics_.iterator_to(metric));
} }
@@ -444,7 +446,7 @@ public:
return; return;
} }
std::lock_guard const _(metricsLock_); std::scoped_lock const _(metricsLock_);
for (auto& m : metrics_) for (auto& m : metrics_)
m.do_process(); m.do_process();

View File

@@ -158,7 +158,7 @@ PropertyStream::Source::Source(std::string name) : m_name(std::move(name)), item
PropertyStream::Source::~Source() PropertyStream::Source::~Source()
{ {
std::lock_guard const _(lock_); std::scoped_lock const _(lock_);
if (parent_ != nullptr) if (parent_ != nullptr)
parent_->remove(*this); parent_->remove(*this);
removeAll(); removeAll();
@@ -173,9 +173,7 @@ PropertyStream::Source::name() const
void void
PropertyStream::Source::add(Source& source) PropertyStream::Source::add(Source& source)
{ {
std::lock(lock_, source.lock_); std::scoped_lock const lock(lock_, source.lock_);
std::lock_guard const lk1(lock_, std::adopt_lock);
std::lock_guard const lk2(source.lock_, std::adopt_lock);
XRPL_ASSERT( XRPL_ASSERT(
source.parent_ == nullptr, "beast::PropertyStream::Source::add : null source parent"); source.parent_ == nullptr, "beast::PropertyStream::Source::add : null source parent");
@@ -186,9 +184,7 @@ PropertyStream::Source::add(Source& source)
void void
PropertyStream::Source::remove(Source& child) PropertyStream::Source::remove(Source& child)
{ {
std::lock(lock_, child.lock_); std::scoped_lock const lock(lock_, child.lock_);
std::lock_guard const lk1(lock_, std::adopt_lock);
std::lock_guard const lk2(child.lock_, std::adopt_lock);
XRPL_ASSERT( XRPL_ASSERT(
child.parent_ == this, "beast::PropertyStream::Source::remove : child parent match"); child.parent_ == this, "beast::PropertyStream::Source::remove : child parent match");
@@ -199,10 +195,10 @@ PropertyStream::Source::remove(Source& child)
void void
PropertyStream::Source::removeAll() PropertyStream::Source::removeAll()
{ {
std::lock_guard const _(lock_); std::scoped_lock const _(lock_);
for (auto iter = children_.begin(); iter != children_.end();) for (auto iter = children_.begin(); iter != children_.end();)
{ {
std::lock_guard const _cl((*iter)->lock_); std::scoped_lock const _cl((*iter)->lock_);
remove(*(*iter)); remove(*(*iter));
} }
} }
@@ -222,7 +218,7 @@ PropertyStream::Source::write(PropertyStream& stream)
Map map(m_name, stream); Map map(m_name, stream);
onWrite(map); onWrite(map);
std::lock_guard const _(lock_); std::scoped_lock const _(lock_);
for (auto& child : children_) for (auto& child : children_)
child.source().write(stream); child.source().write(stream);
@@ -324,7 +320,7 @@ PropertyStream::Source::find_one_deep(std::string const& name)
if (found != nullptr) if (found != nullptr)
return found; return found;
std::lock_guard const _(lock_); std::scoped_lock const _(lock_);
for (auto& s : children_) for (auto& s : children_)
{ {
found = s.source().find_one_deep(name); found = s.source().find_one_deep(name);
@@ -355,7 +351,7 @@ PropertyStream::Source::find_path(std::string path)
PropertyStream::Source* PropertyStream::Source*
PropertyStream::Source::find_one(std::string const& name) PropertyStream::Source::find_one(std::string const& name)
{ {
std::lock_guard const _(lock_); std::scoped_lock const _(lock_);
for (auto& s : children_) for (auto& s : children_)
{ {
if (s.source().m_name == name) if (s.source().m_name == name)

View File

@@ -34,7 +34,7 @@ HashRouter::emplace(uint256 const& key) -> std::pair<Entry&, bool>
void void
HashRouter::addSuppression(uint256 const& key) HashRouter::addSuppression(uint256 const& key)
{ {
std::lock_guard const lock(mutex_); std::scoped_lock const lock(mutex_);
emplace(key); emplace(key);
} }
@@ -48,7 +48,7 @@ HashRouter::addSuppressionPeer(uint256 const& key, PeerShortID peer)
std::pair<bool, std::optional<Stopwatch::time_point>> std::pair<bool, std::optional<Stopwatch::time_point>>
HashRouter::addSuppressionPeerWithStatus(uint256 const& key, PeerShortID peer) HashRouter::addSuppressionPeerWithStatus(uint256 const& key, PeerShortID peer)
{ {
std::lock_guard const lock(mutex_); std::scoped_lock const lock(mutex_);
auto result = emplace(key); auto result = emplace(key);
result.first.addPeer(peer); result.first.addPeer(peer);
@@ -58,7 +58,7 @@ HashRouter::addSuppressionPeerWithStatus(uint256 const& key, PeerShortID peer)
bool bool
HashRouter::addSuppressionPeer(uint256 const& key, PeerShortID peer, HashRouterFlags& flags) HashRouter::addSuppressionPeer(uint256 const& key, PeerShortID peer, HashRouterFlags& flags)
{ {
std::lock_guard const lock(mutex_); std::scoped_lock const lock(mutex_);
auto [s, created] = emplace(key); auto [s, created] = emplace(key);
s.addPeer(peer); s.addPeer(peer);
@@ -73,7 +73,7 @@ HashRouter::shouldProcess(
HashRouterFlags& flags, HashRouterFlags& flags,
std::chrono::seconds tx_interval) std::chrono::seconds tx_interval)
{ {
std::lock_guard const lock(mutex_); std::scoped_lock const lock(mutex_);
auto result = emplace(key); auto result = emplace(key);
auto& s = result.first; auto& s = result.first;
@@ -85,7 +85,7 @@ HashRouter::shouldProcess(
HashRouterFlags HashRouterFlags
HashRouter::getFlags(uint256 const& key) HashRouter::getFlags(uint256 const& key)
{ {
std::lock_guard const lock(mutex_); std::scoped_lock const lock(mutex_);
return emplace(key).first.getFlags(); return emplace(key).first.getFlags();
} }
@@ -95,7 +95,7 @@ HashRouter::setFlags(uint256 const& key, HashRouterFlags flags)
{ {
XRPL_ASSERT(static_cast<bool>(flags), "xrpl::HashRouter::setFlags : valid input"); XRPL_ASSERT(static_cast<bool>(flags), "xrpl::HashRouter::setFlags : valid input");
std::lock_guard const lock(mutex_); std::scoped_lock const lock(mutex_);
auto& s = emplace(key).first; auto& s = emplace(key).first;
@@ -109,7 +109,7 @@ HashRouter::setFlags(uint256 const& key, HashRouterFlags flags)
auto auto
HashRouter::shouldRelay(uint256 const& key) -> std::optional<std::set<PeerShortID>> HashRouter::shouldRelay(uint256 const& key) -> std::optional<std::set<PeerShortID>>
{ {
std::lock_guard const lock(mutex_); std::scoped_lock const lock(mutex_);
auto& s = emplace(key).first; auto& s = emplace(key).first;

View File

@@ -39,7 +39,7 @@ JobQueue::JobQueue(
job_count = m_collector->make_gauge("job_count"); job_count = m_collector->make_gauge("job_count");
{ {
std::lock_guard const lock(m_mutex); std::scoped_lock const lock(m_mutex);
for (auto const& x : JobTypes::instance()) for (auto const& x : JobTypes::instance())
{ {
@@ -65,7 +65,7 @@ JobQueue::~JobQueue()
void void
JobQueue::collect() JobQueue::collect()
{ {
std::lock_guard const lock(m_mutex); std::scoped_lock const lock(m_mutex);
job_count = m_jobSet.size(); job_count = m_jobSet.size();
} }
@@ -91,7 +91,7 @@ JobQueue::addRefCountedJob(JobType type, std::string const& name, JobFunction co
"requires no threads"); "requires no threads");
{ {
std::lock_guard const lock(m_mutex); std::scoped_lock const lock(m_mutex);
auto result = m_jobSet.emplace(type, name, ++m_lastJob, data.load(), func); auto result = m_jobSet.emplace(type, name, ++m_lastJob, data.load(), func);
auto const& job = *result.first; auto const& job = *result.first;
@@ -119,7 +119,7 @@ JobQueue::addRefCountedJob(JobType type, std::string const& name, JobFunction co
int int
JobQueue::getJobCount(JobType t) const JobQueue::getJobCount(JobType t) const
{ {
std::lock_guard const lock(m_mutex); std::scoped_lock const lock(m_mutex);
JobDataMap::const_iterator const c = m_jobData.find(t); JobDataMap::const_iterator const c = m_jobData.find(t);
@@ -129,7 +129,7 @@ JobQueue::getJobCount(JobType t) const
int int
JobQueue::getJobCountTotal(JobType t) const JobQueue::getJobCountTotal(JobType t) const
{ {
std::lock_guard const lock(m_mutex); std::scoped_lock const lock(m_mutex);
JobDataMap::const_iterator const c = m_jobData.find(t); JobDataMap::const_iterator const c = m_jobData.find(t);
@@ -142,7 +142,7 @@ JobQueue::getJobCountGE(JobType t) const
// return the number of jobs at this priority level or greater // return the number of jobs at this priority level or greater
int ret = 0; int ret = 0;
std::lock_guard const lock(m_mutex); std::scoped_lock const lock(m_mutex);
for (auto const& x : m_jobData) for (auto const& x : m_jobData)
{ {
@@ -192,7 +192,7 @@ JobQueue::getJson(int c)
Json::Value priorities = Json::arrayValue; Json::Value priorities = Json::arrayValue;
std::lock_guard const lock(m_mutex); std::scoped_lock const lock(m_mutex);
for (auto& x : m_jobData) for (auto& x : m_jobData)
{ {
@@ -349,7 +349,7 @@ JobQueue::processTask(int instance)
{ {
Job job; Job job;
{ {
std::lock_guard const lock(m_mutex); std::scoped_lock const lock(m_mutex);
getNextJob(job); getNextJob(job);
++m_processCount; ++m_processCount;
} }
@@ -376,7 +376,7 @@ JobQueue::processTask(int instance)
} }
{ {
std::lock_guard const lock(m_mutex); std::scoped_lock const lock(m_mutex);
// Job should be destroyed before stopping // Job should be destroyed before stopping
// otherwise destructors with side effects can access // otherwise destructors with side effects can access
// parent objects that are already destroyed. // parent objects that are already destroyed.

View File

@@ -108,7 +108,7 @@ LoadMonitor::addLoadSample(LoadEvent const& s)
void void
LoadMonitor::addSamples(int count, std::chrono::milliseconds latency) LoadMonitor::addSamples(int count, std::chrono::milliseconds latency)
{ {
std::lock_guard const sl(mutex_); std::scoped_lock const sl(mutex_);
update(); update();
mCounts += count; mCounts += count;
@@ -140,7 +140,7 @@ LoadMonitor::isOverTarget(std::chrono::milliseconds avg, std::chrono::millisecon
bool bool
LoadMonitor::isOver() LoadMonitor::isOver()
{ {
std::lock_guard const sl(mutex_); std::scoped_lock const sl(mutex_);
update(); update();
@@ -157,7 +157,7 @@ LoadMonitor::getStats()
using namespace std::chrono_literals; using namespace std::chrono_literals;
Stats stats; Stats stats;
std::lock_guard const sl(mutex_); std::scoped_lock const sl(mutex_);
update(); update();

View File

@@ -151,7 +151,7 @@ Workers::Worker::Worker(Workers& workers, std::string threadName, int const inst
Workers::Worker::~Worker() Workers::Worker::~Worker()
{ {
{ {
std::lock_guard const lock{mutex_}; std::scoped_lock const lock{mutex_};
++wakeCount_; ++wakeCount_;
shouldExit_ = true; shouldExit_ = true;
} }
@@ -163,7 +163,7 @@ Workers::Worker::~Worker()
void void
Workers::Worker::notify() Workers::Worker::notify()
{ {
std::lock_guard const lock{mutex_}; std::scoped_lock const lock{mutex_};
++wakeCount_; ++wakeCount_;
wakeup_.notify_one(); wakeup_.notify_one();
} }
@@ -179,7 +179,7 @@ Workers::Worker::run()
// //
if (++m_workers.m_activeCount == 1) if (++m_workers.m_activeCount == 1)
{ {
std::lock_guard const lk{m_workers.m_mut}; std::scoped_lock const lk{m_workers.m_mut};
m_workers.m_allPaused = false; m_workers.m_allPaused = false;
} }
@@ -226,7 +226,7 @@ Workers::Worker::run()
// the predicate evaluation and the actual sleep. // the predicate evaluation and the actual sleep.
if (--m_workers.m_runningTaskCount == 0) if (--m_workers.m_runningTaskCount == 0)
{ {
std::lock_guard const lk{m_workers.m_mut}; std::scoped_lock const lk{m_workers.m_mut};
m_workers.m_cv.notify_all(); m_workers.m_cv.notify_all();
} }
} }
@@ -242,7 +242,7 @@ Workers::Worker::run()
// //
if (--m_workers.m_activeCount == 0) if (--m_workers.m_activeCount == 0)
{ {
std::lock_guard const lk{m_workers.m_mut}; std::scoped_lock const lk{m_workers.m_mut};
m_workers.m_allPaused = true; m_workers.m_allPaused = true;
m_workers.m_cv.notify_all(); m_workers.m_cv.notify_all();
} }

View File

@@ -43,7 +43,7 @@ csprng_engine::mix_entropy(void* buffer, std::size_t count)
e = rd(); e = rd();
} }
std::lock_guard const lock(mutex_); std::scoped_lock const lock(mutex_);
// We add data to the pool, but we conservatively assume that // We add data to the pool, but we conservatively assume that
// it contributes no actual entropy. // it contributes no actual entropy.
@@ -60,7 +60,7 @@ csprng_engine::operator()(void* ptr, std::size_t count)
// with thread support, so we don't need to grab a mutex. // with thread support, so we don't need to grab a mutex.
// https://mta.openssl.org/pipermail/openssl-users/2020-November/013146.html // https://mta.openssl.org/pipermail/openssl-users/2020-November/013146.html
#if (OPENSSL_VERSION_NUMBER < 0x10100000L) || !defined(OPENSSL_THREADS) #if (OPENSSL_VERSION_NUMBER < 0x10100000L) || !defined(OPENSSL_THREADS)
std::lock_guard lock(mutex_); std::scoped_lock lock(mutex_);
#endif #endif
auto const result = RAND_bytes(reinterpret_cast<unsigned char*>(ptr), count); auto const result = RAND_bytes(reinterpret_cast<unsigned char*>(ptr), count);

View File

@@ -45,7 +45,7 @@ outputJson(Json::Value const& value, Writer& writer)
} }
case Json::arrayValue: { case Json::arrayValue: {
writer.startRoot(Writer::array); writer.startRoot(Writer::CollectionType::array);
for (auto const& i : value) for (auto const& i : value)
{ {
writer.rawAppend(); writer.rawAppend();
@@ -56,7 +56,7 @@ outputJson(Json::Value const& value, Writer& writer)
} }
case Json::objectValue: { case Json::objectValue: {
writer.startRoot(Writer::object); writer.startRoot(Writer::CollectionType::object);
auto members = value.getMemberNames(); auto members = value.getMemberNames();
for (auto const& tag : members) for (auto const& tag : members)
{ {

View File

@@ -81,7 +81,7 @@ public:
void void
start(CollectionType ct) start(CollectionType ct)
{ {
char const ch = (ct == array) ? openBracket : openBrace; char const ch = (ct == CollectionType::array) ? openBracket : openBrace;
output({&ch, 1}); output({&ch, 1});
stack_.emplace(Collection{.type = ct}); stack_.emplace(Collection{.type = ct});
} }
@@ -134,7 +134,9 @@ public:
auto t = stack_.top().type; auto t = stack_.top().type;
if (t != type) if (t != type)
{ {
check(false, "Not an " + ((type == array ? "array: " : "object: ") + message)); check(
false,
"Not an " + ((type == CollectionType::array ? "array: " : "object: ") + message));
} }
if (stack_.top().isFirst) if (stack_.top().isFirst)
{ {
@@ -171,7 +173,7 @@ public:
{ {
check(!empty(), "Empty stack in finish()"); check(!empty(), "Empty stack in finish()");
auto isArray = stack_.top().type == array; auto isArray = stack_.top().type == CollectionType::array;
auto ch = isArray ? closeBracket : closeBrace; auto ch = isArray ? closeBracket : closeBrace;
output_({&ch, 1}); output_({&ch, 1});
stack_.pop(); stack_.pop();
@@ -301,7 +303,7 @@ Writer::finishAll()
void void
Writer::rawAppend() Writer::rawAppend()
{ {
impl_->nextCollectionEntry(array, "append"); impl_->nextCollectionEntry(CollectionType::array, "append");
} }
void void
@@ -309,7 +311,7 @@ Writer::rawSet(std::string const& tag)
{ {
check(!tag.empty(), "Tag can't be empty"); check(!tag.empty(), "Tag can't be empty");
impl_->nextCollectionEntry(object, "set"); impl_->nextCollectionEntry(CollectionType::object, "set");
impl_->writeObjectTag(tag); impl_->writeObjectTag(tag);
} }
@@ -322,14 +324,14 @@ Writer::startRoot(CollectionType type)
void void
Writer::startAppend(CollectionType type) Writer::startAppend(CollectionType type)
{ {
impl_->nextCollectionEntry(array, "startAppend"); impl_->nextCollectionEntry(CollectionType::array, "startAppend");
impl_->start(type); impl_->start(type);
} }
void void
Writer::startSet(CollectionType type, std::string const& key) Writer::startSet(CollectionType type, std::string const& key)
{ {
impl_->nextCollectionEntry(object, "startSet"); impl_->nextCollectionEntry(CollectionType::object, "startSet");
impl_->writeObjectTag(key); impl_->writeObjectTag(key);
impl_->start(type); impl_->start(type);
} }

View File

@@ -62,8 +62,8 @@ AcceptedLedgerTx::AcceptedLedgerTx(
*ledger, *ledger,
account, account,
amount, amount,
fhIGNORE_FREEZE, FreezeHandling::fhIGNORE_FREEZE,
ahIGNORE_AUTH, AuthHandling::ahIGNORE_AUTH,
beast::Journal{beast::Journal::getNullSink()}); beast::Journal{beast::Journal::getNullSink()});
mJson[jss::transaction][jss::owner_funds] = ownerFunds.getText(); mJson[jss::transaction][jss::owner_funds] = ownerFunds.getText();
} }

View File

@@ -13,21 +13,21 @@ namespace xrpl {
void void
BookListeners::addSubscriber(InfoSub::ref sub) BookListeners::addSubscriber(InfoSub::ref sub)
{ {
std::lock_guard const sl(mLock); std::scoped_lock const sl(mLock);
mListeners[sub->getSeq()] = sub; mListeners[sub->getSeq()] = sub;
} }
void void
BookListeners::removeSubscriber(std::uint64_t seq) BookListeners::removeSubscriber(std::uint64_t seq)
{ {
std::lock_guard const sl(mLock); std::scoped_lock const sl(mLock);
mListeners.erase(seq); mListeners.erase(seq);
} }
void void
BookListeners::publish(MultiApiJson const& jvObj, hash_set<std::uint64_t>& havePublished) BookListeners::publish(MultiApiJson const& jvObj, hash_set<std::uint64_t>& havePublished)
{ {
std::lock_guard const sl(mLock); std::scoped_lock const sl(mLock);
auto it = mListeners.cbegin(); auto it = mListeners.cbegin();
while (it != mListeners.cend()) while (it != mListeners.cend())

View File

@@ -30,7 +30,7 @@ CachedViewImpl::read(Keylet const& k) const
auto const digest = [&]() -> std::optional<uint256> { auto const digest = [&]() -> std::optional<uint256> {
{ {
std::lock_guard const lock(mutex_); std::scoped_lock const lock(mutex_);
auto const iter = map_.find(k.key); auto const iter = map_.find(k.key);
if (iter != map_.end()) if (iter != map_.end())
{ {
@@ -66,7 +66,7 @@ CachedViewImpl::read(Keylet const& k) const
// Avoid acquiring this lock unless necessary. It is only necessary if // Avoid acquiring this lock unless necessary. It is only necessary if
// the key was not found in the map_. The lock is needed to add the key // the key was not found in the map_. The lock is needed to add the key
// and digest. // and digest.
std::lock_guard const lock(mutex_); std::scoped_lock const lock(mutex_);
map_.emplace(k.key, *digest); map_.emplace(k.key, *digest);
} }
if (!sle || !k.check(*sle)) if (!sle || !k.check(*sle))

View File

@@ -204,7 +204,7 @@ Ledger::Ledger(
rawInsert(sle); rawInsert(sle);
} }
stateMap_.flushDirty(hotACCOUNT_NODE); stateMap_.flushDirty(NodeObjectType::hotACCOUNT_NODE);
setImmutable(); setImmutable();
} }

View File

@@ -46,7 +46,8 @@ STAmount
ammLPTokens(STAmount const& asset1, STAmount const& asset2, Asset const& lptIssue) ammLPTokens(STAmount const& asset1, STAmount const& asset2, Asset const& lptIssue)
{ {
// AMM invariant: sqrt(asset1 * asset2) >= LPTokensBalance // AMM invariant: sqrt(asset1 * asset2) >= LPTokensBalance
auto const rounding = isFeatureEnabled(fixAMMv1_3) ? Number::downward : Number::getround(); auto const rounding =
isFeatureEnabled(fixAMMv1_3) ? Number::rounding_mode::downward : Number::getround();
NumberRoundModeGuard const g(rounding); NumberRoundModeGuard const g(rounding);
auto const tokens = root2(asset1 * asset2); auto const tokens = root2(asset1 * asset2);
return toSTAmount(lptIssue, tokens); return toSTAmount(lptIssue, tokens);
@@ -77,7 +78,7 @@ lpTokensOut(
// minimize tokens out // minimize tokens out
auto const frac = (r - c) / (1 + c); auto const frac = (r - c) / (1 + c);
return multiply(lptAMMBalance, frac, Number::downward); return multiply(lptAMMBalance, frac, Number::rounding_mode::downward);
} }
/* Equation 4 solves equation 3 for b: /* Equation 4 solves equation 3 for b:
@@ -113,7 +114,7 @@ ammAssetIn(
// maximize deposit // maximize deposit
auto const frac = solveQuadraticEq(a, b, c); auto const frac = solveQuadraticEq(a, b, c);
return multiply(asset1Balance, frac, Number::upward); return multiply(asset1Balance, frac, Number::rounding_mode::upward);
} }
/* Equation 7: /* Equation 7:
@@ -138,7 +139,7 @@ lpTokensIn(
// maximize tokens in // maximize tokens in
auto const frac = (c - root2(c * c - 4 * fr)) / 2; auto const frac = (c - root2(c * c - 4 * fr)) / 2;
return multiply(lptAMMBalance, frac, Number::upward); return multiply(lptAMMBalance, frac, Number::rounding_mode::upward);
} }
/* Equation 8 solves equation 7 for b: /* Equation 8 solves equation 7 for b:
@@ -168,7 +169,7 @@ ammAssetOut(
// minimize withdraw // minimize withdraw
auto const frac = (t1 * t1 - t1 * (2 - f)) / (t1 * f - 1); auto const frac = (t1 * t1 - t1 * (2 - f)) / (t1 * f - 1);
return multiply(assetBalance, frac, Number::downward); return multiply(assetBalance, frac, Number::rounding_mode::downward);
} }
Number Number

View File

@@ -93,8 +93,8 @@ loanPeriodicRate(TenthBips32 interestRate, std::uint32_t paymentInterval)
bool bool
isRounded(Asset const& asset, Number const& value, std::int32_t scale) isRounded(Asset const& asset, Number const& value, std::int32_t scale)
{ {
return roundToAsset(asset, value, scale, Number::downward) == return roundToAsset(asset, value, scale, Number::rounding_mode::downward) ==
roundToAsset(asset, value, scale, Number::upward); roundToAsset(asset, value, scale, Number::rounding_mode::upward);
} }
namespace detail { namespace detail {
@@ -458,7 +458,11 @@ tryOverpayment(
// preserved rounding errors. This ensures the loan's tracked state remains // preserved rounding errors. This ensures the loan's tracked state remains
// consistent with its payment history. // consistent with its payment history.
auto const principalOutstanding = std::clamp( auto const principalOutstanding = std::clamp(
roundToAsset(asset, newTheoreticalState.principalOutstanding, loanScale, Number::upward), roundToAsset(
asset,
newTheoreticalState.principalOutstanding,
loanScale,
Number::rounding_mode::upward),
numZero, numZero,
roundedOldState.principalOutstanding); roundedOldState.principalOutstanding);
auto const totalValueOutstanding = std::clamp( auto const totalValueOutstanding = std::clamp(
@@ -466,7 +470,7 @@ tryOverpayment(
asset, asset,
principalOutstanding + newTheoreticalState.interestOutstanding(), principalOutstanding + newTheoreticalState.interestOutstanding(),
loanScale, loanScale,
Number::upward), Number::rounding_mode::upward),
numZero, numZero,
roundedOldState.valueOutstanding); roundedOldState.valueOutstanding);
auto const managementFeeOutstanding = std::clamp( auto const managementFeeOutstanding = std::clamp(
@@ -836,7 +840,8 @@ computeFullPayment(
// Split the full payment interest into net interest (to vault) and // Split the full payment interest into net interest (to vault) and
// management fee (to broker), applying proper rounding. // management fee (to broker), applying proper rounding.
auto const [roundedFullInterest, roundedFullManagementFee] = [&]() { auto const [roundedFullInterest, roundedFullManagementFee] = [&]() {
auto const interest = roundToAsset(asset, fullPaymentInterest, loanScale, Number::downward); auto const interest =
roundToAsset(asset, fullPaymentInterest, loanScale, Number::rounding_mode::downward);
return computeInterestAndFeeParts(asset, interest, managementFeeRate, loanScale); return computeInterestAndFeeParts(asset, interest, managementFeeRate, loanScale);
}(); }();
@@ -1286,7 +1291,7 @@ checkLoanGuards(
// loan can't be amortized in the specified number of payments, raise an // loan can't be amortized in the specified number of payments, raise an
// error // error
{ {
NumberRoundModeGuard const mg(Number::upward); NumberRoundModeGuard const mg(Number::rounding_mode::upward);
if (std::int64_t const computedPayments{ if (std::int64_t const computedPayments{
properties.loanState.valueOutstanding / roundedPayment}; properties.loanState.valueOutstanding / roundedPayment};
@@ -1465,7 +1470,8 @@ computeManagementFee(
TenthBips32 managementFeeRate, TenthBips32 managementFeeRate,
std::int32_t scale) std::int32_t scale)
{ {
return roundToAsset(asset, tenthBipsOfValue(value, managementFeeRate), scale, Number::downward); return roundToAsset(
asset, tenthBipsOfValue(value, managementFeeRate), scale, Number::rounding_mode::downward);
} }
/* /*
@@ -1519,7 +1525,8 @@ computeLoanProperties(
auto const [totalValueOutstanding, loanScale] = [&]() { auto const [totalValueOutstanding, loanScale] = [&]() {
// only round up if there should be interest // only round up if there should be interest
NumberRoundModeGuard const mg(periodicRate == 0 ? Number::to_nearest : Number::upward); NumberRoundModeGuard const mg(
periodicRate == 0 ? Number::rounding_mode::to_nearest : Number::rounding_mode::upward);
// Use STAmount's internal rounding instead of roundToAsset, because // Use STAmount's internal rounding instead of roundToAsset, because
// we're going to use this result to determine the scale for all the // we're going to use this result to determine the scale for all the
// other rounding. // other rounding.
@@ -1548,7 +1555,7 @@ computeLoanProperties(
// validate that the principal fits in it, so to allow this function to // validate that the principal fits in it, so to allow this function to
// succeed, round it here, and let the caller do the validation. // succeed, round it here, and let the caller do the validation.
auto const roundedPrincipalOutstanding = auto const roundedPrincipalOutstanding =
roundToAsset(asset, principalOutstanding, loanScale, Number::to_nearest); roundToAsset(asset, principalOutstanding, loanScale, Number::rounding_mode::to_nearest);
// Equation (31) from XLS-66 spec, Section A-2 Equation Glossary // Equation (31) from XLS-66 spec, Section A-2 Equation Glossary
auto const totalInterestOutstanding = totalValueOutstanding - roundedPrincipalOutstanding; auto const totalInterestOutstanding = totalValueOutstanding - roundedPrincipalOutstanding;

View File

@@ -165,7 +165,7 @@ getLineIfUsable(
return nullptr; return nullptr;
} }
if (zeroIfFrozen == fhZERO_IF_FROZEN) if (zeroIfFrozen == FreezeHandling::fhZERO_IF_FROZEN)
{ {
if (isFrozen(view, account, currency, issuer) || if (isFrozen(view, account, currency, issuer) ||
isDeepFrozen(view, account, currency, issuer)) isDeepFrozen(view, account, currency, issuer))
@@ -252,7 +252,7 @@ accountHolds(
return {xrpLiquid(view, account, 0, j)}; return {xrpLiquid(view, account, 0, j)};
} }
bool const returnSpendable = (includeFullBalance == shFULL_BALANCE); bool const returnSpendable = (includeFullBalance == SpendableHandling::shFULL_BALANCE);
if (returnSpendable && account == issuer) if (returnSpendable && account == issuer)
{ {
// If the account is the issuer, then their limit is effectively // If the account is the issuer, then their limit is effectively
@@ -290,7 +290,7 @@ accountHolds(
beast::Journal j, beast::Journal j,
SpendableHandling includeFullBalance) SpendableHandling includeFullBalance)
{ {
bool const returnSpendable = (includeFullBalance == shFULL_BALANCE); bool const returnSpendable = (includeFullBalance == SpendableHandling::shFULL_BALANCE);
STAmount amount{mptIssue}; STAmount amount{mptIssue};
auto const& issuer = mptIssue.getIssuer(); auto const& issuer = mptIssue.getIssuer();
bool const mptokensV2 = view.rules().enabled(featureMPTokensV2); bool const mptokensV2 = view.rules().enabled(featureMPTokensV2);
@@ -317,7 +317,7 @@ accountHolds(
{ {
amount.clear(mptIssue); amount.clear(mptIssue);
} }
else if (zeroIfFrozen == fhZERO_IF_FROZEN && isFrozen(view, account, mptIssue)) else if (zeroIfFrozen == FreezeHandling::fhZERO_IF_FROZEN && isFrozen(view, account, mptIssue))
{ {
amount.clear(mptIssue); amount.clear(mptIssue);
} }
@@ -327,14 +327,14 @@ accountHolds(
// Only if auth check is needed, as it needs to do an additional read // Only if auth check is needed, as it needs to do an additional read
// operation. Note featureSingleAssetVault will affect error codes. // operation. Note featureSingleAssetVault will affect error codes.
if (zeroIfUnauthorized == ahZERO_IF_UNAUTHORIZED && if (zeroIfUnauthorized == AuthHandling::ahZERO_IF_UNAUTHORIZED &&
view.rules().enabled(featureSingleAssetVault)) view.rules().enabled(featureSingleAssetVault))
{ {
if (auto const err = requireAuth(view, mptIssue, account, AuthType::StrongAuth); if (auto const err = requireAuth(view, mptIssue, account, AuthType::StrongAuth);
!isTesSuccess(err)) !isTesSuccess(err))
amount.clear(mptIssue); amount.clear(mptIssue);
} }
else if (zeroIfUnauthorized == ahZERO_IF_UNAUTHORIZED) else if (zeroIfUnauthorized == AuthHandling::ahZERO_IF_UNAUTHORIZED)
{ {
auto const sleIssuance = view.read(keylet::mptIssuance(mptIssue.getMptID())); auto const sleIssuance = view.read(keylet::mptIssuance(mptIssue.getMptID()));
@@ -401,7 +401,13 @@ accountFunds(
[&](Issue const&) { return accountFunds(view, id, saDefault, freezeHandling, j); }, [&](Issue const&) { return accountFunds(view, id, saDefault, freezeHandling, j); },
[&](MPTIssue const&) { [&](MPTIssue const&) {
return accountHolds( return accountHolds(
view, id, saDefault.asset(), freezeHandling, authHandling, j, shFULL_BALANCE); view,
id,
saDefault.asset(),
freezeHandling,
authHandling,
j,
SpendableHandling::shFULL_BALANCE);
}); });
} }

View File

@@ -47,7 +47,7 @@ BatchWriter::store(std::shared_ptr<NodeObject> const& object)
int int
BatchWriter::getWriteLoad() BatchWriter::getWriteLoad()
{ {
std::lock_guard const sl(mWriteMutex); std::scoped_lock const sl(mWriteMutex);
return std::max(mWriteLoad, static_cast<int>(mWriteSet.size())); return std::max(mWriteLoad, static_cast<int>(mWriteSet.size()));
} }
@@ -68,7 +68,7 @@ BatchWriter::writeBatch()
set.reserve(batchWritePreallocationSize); set.reserve(batchWritePreallocationSize);
{ {
std::lock_guard const sl(mWriteMutex); std::scoped_lock const sl(mWriteMutex);
mWriteSet.swap(set); mWriteSet.swap(set);
XRPL_ASSERT( XRPL_ASSERT(

View File

@@ -143,7 +143,7 @@ void
Database::stop() Database::stop()
{ {
{ {
std::lock_guard const lock(readLock_); std::scoped_lock const lock(readLock_);
if (!readStopping_.exchange(true, std::memory_order_relaxed)) if (!readStopping_.exchange(true, std::memory_order_relaxed))
{ {
@@ -179,7 +179,7 @@ Database::asyncFetch(
std::uint32_t ledgerSeq, std::uint32_t ledgerSeq,
std::function<void(std::shared_ptr<NodeObject> const&)>&& cb) std::function<void(std::shared_ptr<NodeObject> const&)>&& cb)
{ {
std::lock_guard const lock(readLock_); std::scoped_lock const lock(readLock_);
if (!isStopping()) if (!isStopping())
{ {

View File

@@ -48,11 +48,11 @@ DatabaseNodeImp::fetchNodeObject(
bool duplicate) bool duplicate)
{ {
std::shared_ptr<NodeObject> nodeObject = nullptr; std::shared_ptr<NodeObject> nodeObject = nullptr;
Status status = ok; Status status = Status::ok;
try try
{ {
status = backend_->fetch(hash.data(), &nodeObject); status = backend_->fetch(hash, &nodeObject);
} }
catch (std::exception const& e) catch (std::exception const& e)
{ {
@@ -63,15 +63,15 @@ DatabaseNodeImp::fetchNodeObject(
switch (status) switch (status)
{ {
case ok: case Status::ok:
case notFound: case Status::notFound:
break; break;
case dataCorrupt: case Status::dataCorrupt:
JLOG(j_.fatal()) << "fetchNodeObject " << hash << ": nodestore data is corrupted"; JLOG(j_.fatal()) << "fetchNodeObject " << hash << ": nodestore data is corrupted";
break; break;
default: default:
JLOG(j_.warn()) << "fetchNodeObject " << hash << ": backend returns unknown result " JLOG(j_.warn()) << "fetchNodeObject " << hash << ": backend returns unknown result "
<< status; << static_cast<int>(status);
break; break;
} }
@@ -87,18 +87,10 @@ DatabaseNodeImp::fetchBatch(std::vector<uint256> const& hashes)
using namespace std::chrono; using namespace std::chrono;
auto const before = steady_clock::now(); auto const before = steady_clock::now();
std::vector<uint256 const*> batch{};
batch.reserve(hashes.size());
for (size_t i = 0; i < hashes.size(); ++i)
{
auto const& hash = hashes[i];
batch.push_back(&hash);
}
// Get the node objects that match the hashes from the backend. To protect // Get the node objects that match the hashes from the backend. To protect
// against the backends returning fewer or more results than expected, the // against the backends returning fewer or more results than expected, the
// container is resized to the number of hashes. // container is resized to the number of hashes.
auto results = backend_->fetchBatch(batch).first; auto results = backend_->fetchBatch(hashes).first;
XRPL_ASSERT( XRPL_ASSERT(
results.size() == hashes.size() || results.empty(), results.size() == hashes.size() || results.empty(),
"number of output objects either matches number of input hashes or is empty"); "number of output objects either matches number of input hashes or is empty");

View File

@@ -53,7 +53,7 @@ DatabaseRotatingImp::rotate(
// deleted. // deleted.
std::shared_ptr<NodeStore::Backend> oldArchiveBackend; std::shared_ptr<NodeStore::Backend> oldArchiveBackend;
{ {
std::lock_guard const lock(mutex_); std::scoped_lock const lock(mutex_);
archiveBackend_->setDeletePath(); archiveBackend_->setDeletePath();
oldArchiveBackend = std::move(archiveBackend_); oldArchiveBackend = std::move(archiveBackend_);
@@ -70,14 +70,14 @@ DatabaseRotatingImp::rotate(
std::string std::string
DatabaseRotatingImp::getName() const DatabaseRotatingImp::getName() const
{ {
std::lock_guard const lock(mutex_); std::scoped_lock const lock(mutex_);
return writableBackend_->getName(); return writableBackend_->getName();
} }
std::int32_t std::int32_t
DatabaseRotatingImp::getWriteLoad() const DatabaseRotatingImp::getWriteLoad() const
{ {
std::lock_guard const lock(mutex_); std::scoped_lock const lock(mutex_);
return writableBackend_->getWriteLoad(); return writableBackend_->getWriteLoad();
} }
@@ -85,7 +85,7 @@ void
DatabaseRotatingImp::importDatabase(Database& source) DatabaseRotatingImp::importDatabase(Database& source)
{ {
auto const backend = [&] { auto const backend = [&] {
std::lock_guard const lock(mutex_); std::scoped_lock const lock(mutex_);
return writableBackend_; return writableBackend_;
}(); }();
@@ -95,7 +95,7 @@ DatabaseRotatingImp::importDatabase(Database& source)
void void
DatabaseRotatingImp::sync() DatabaseRotatingImp::sync()
{ {
std::lock_guard const lock(mutex_); std::scoped_lock const lock(mutex_);
writableBackend_->sync(); writableBackend_->sync();
} }
@@ -105,7 +105,7 @@ DatabaseRotatingImp::store(NodeObjectType type, Blob&& data, uint256 const& hash
auto nObj = NodeObject::createObject(type, std::move(data), hash); auto nObj = NodeObject::createObject(type, std::move(data), hash);
auto const backend = [&] { auto const backend = [&] {
std::lock_guard const lock(mutex_); std::scoped_lock const lock(mutex_);
return writableBackend_; return writableBackend_;
}(); }();
@@ -121,11 +121,11 @@ DatabaseRotatingImp::fetchNodeObject(
bool duplicate) bool duplicate)
{ {
auto fetch = [&](std::shared_ptr<Backend> const& backend) { auto fetch = [&](std::shared_ptr<Backend> const& backend) {
Status status = ok; Status status = Status::ok;
std::shared_ptr<NodeObject> nodeObject; std::shared_ptr<NodeObject> nodeObject;
try try
{ {
status = backend->fetch(hash.data(), &nodeObject); status = backend->fetch(hash, &nodeObject);
} }
catch (std::exception const& e) catch (std::exception const& e)
{ {
@@ -135,14 +135,14 @@ DatabaseRotatingImp::fetchNodeObject(
switch (status) switch (status)
{ {
case ok: case Status::ok:
case notFound: case Status::notFound:
break; break;
case dataCorrupt: case Status::dataCorrupt:
JLOG(j_.fatal()) << "Corrupt NodeObject #" << hash; JLOG(j_.fatal()) << "Corrupt NodeObject #" << hash;
break; break;
default: default:
JLOG(j_.warn()) << "Unknown status=" << status; JLOG(j_.warn()) << "Unknown status=" << static_cast<int>(status);
break; break;
} }
@@ -153,7 +153,7 @@ DatabaseRotatingImp::fetchNodeObject(
std::shared_ptr<NodeObject> nodeObject; std::shared_ptr<NodeObject> nodeObject;
auto [writable, archive] = [&] { auto [writable, archive] = [&] {
std::lock_guard const lock(mutex_); std::scoped_lock const lock(mutex_);
return std::make_pair(writableBackend_, archiveBackend_); return std::make_pair(writableBackend_, archiveBackend_);
}(); }();
@@ -167,7 +167,7 @@ DatabaseRotatingImp::fetchNodeObject(
{ {
{ {
// Refresh the writable backend pointer // Refresh the writable backend pointer
std::lock_guard const lock(mutex_); std::scoped_lock const lock(mutex_);
writable = writableBackend_; writable = writableBackend_;
} }
@@ -187,7 +187,7 @@ void
DatabaseRotatingImp::for_each(std::function<void(std::shared_ptr<NodeObject>)> f) DatabaseRotatingImp::for_each(std::function<void(std::shared_ptr<NodeObject>)> f)
{ {
auto [writable, archive] = [&] { auto [writable, archive] = [&] {
std::lock_guard const lock(mutex_); std::scoped_lock const lock(mutex_);
return std::make_pair(writableBackend_, archiveBackend_); return std::make_pair(writableBackend_, archiveBackend_);
}(); }();

View File

@@ -25,7 +25,7 @@ DecodedBlob::DecodedBlob(void const* key, void const* value, int valueBytes)
m_success = false; m_success = false;
m_key = key; m_key = key;
m_objectType = hotUNKNOWN; m_objectType = NodeObjectType::hotUNKNOWN;
m_objectData = nullptr; m_objectData = nullptr;
m_dataBytes = std::max(0, valueBytes - 9); m_dataBytes = std::max(0, valueBytes - 9);
@@ -46,10 +46,10 @@ DecodedBlob::DecodedBlob(void const* key, void const* value, int valueBytes)
default: default:
break; break;
case hotUNKNOWN: case NodeObjectType::hotUNKNOWN:
case hotLEDGER: case NodeObjectType::hotLEDGER:
case hotACCOUNT_NODE: case NodeObjectType::hotACCOUNT_NODE:
case hotTRANSACTION_NODE: case NodeObjectType::hotTRANSACTION_NODE:
m_success = true; m_success = true;
break; break;
} }

View File

@@ -96,14 +96,14 @@ ManagerImp::make_Database(
void void
ManagerImp::insert(Factory& factory) ManagerImp::insert(Factory& factory)
{ {
std::lock_guard const _(mutex_); std::scoped_lock const _(mutex_);
list_.push_back(&factory); list_.push_back(&factory);
} }
void void
ManagerImp::erase(Factory& factory) ManagerImp::erase(Factory& factory)
{ {
std::lock_guard const _(mutex_); std::scoped_lock const _(mutex_);
auto const iter = auto const iter =
std::ranges::find_if(list_, [&factory](Factory* other) { return other == &factory; }); std::ranges::find_if(list_, [&factory](Factory* other) { return other == &factory; });
XRPL_ASSERT(iter != list_.end(), "xrpl::NodeStore::ManagerImp::erase : valid input"); XRPL_ASSERT(iter != list_.end(), "xrpl::NodeStore::ManagerImp::erase : valid input");
@@ -113,7 +113,7 @@ ManagerImp::erase(Factory& factory)
Factory* Factory*
ManagerImp::find(std::string const& name) ManagerImp::find(std::string const& name)
{ {
std::lock_guard const _(mutex_); std::scoped_lock const _(mutex_);
auto const iter = std::ranges::find_if( auto const iter = std::ranges::find_if(
list_, [&name](Factory* other) { return boost::iequals(name, other->getName()); }); list_, [&name](Factory* other) { return boost::iequals(name, other->getName()); });
if (iter == list_.end()) if (iter == list_.end())

View File

@@ -59,7 +59,7 @@ public:
MemoryDB& MemoryDB&
open(std::string const& path) open(std::string const& path)
{ {
std::lock_guard const _(mutex_); std::scoped_lock const _(mutex_);
auto const result = auto const result =
map_.emplace(std::piecewise_construct, std::make_tuple(path), std::make_tuple()); map_.emplace(std::piecewise_construct, std::make_tuple(path), std::make_tuple());
MemoryDB& db = result.first->second; MemoryDB& db = result.first->second;
@@ -134,16 +134,16 @@ public:
{ {
XRPL_ASSERT(db_, "xrpl::NodeStore::MemoryBackend::fetch : non-null database"); XRPL_ASSERT(db_, "xrpl::NodeStore::MemoryBackend::fetch : non-null database");
std::lock_guard const _(db_->mutex); std::scoped_lock const _(db_->mutex);
Map::iterator const iter = db_->table.find(hash); Map::iterator const iter = db_->table.find(hash);
if (iter == db_->table.end()) if (iter == db_->table.end())
{ {
pObject->reset(); pObject->reset();
return notFound; return Status::notFound;
} }
*pObject = iter->second; *pObject = iter->second;
return ok; return Status::ok;
} }
std::pair<std::vector<std::shared_ptr<NodeObject>>, Status> std::pair<std::vector<std::shared_ptr<NodeObject>>, Status>
@@ -155,7 +155,7 @@ public:
{ {
std::shared_ptr<NodeObject> nObj; std::shared_ptr<NodeObject> nObj;
Status const status = fetch(h, &nObj); Status const status = fetch(h, &nObj);
if (status != ok) if (status != Status::ok)
{ {
results.push_back({}); results.push_back({});
} }
@@ -165,14 +165,14 @@ public:
} }
} }
return {results, ok}; return {results, Status::ok};
} }
void void
store(std::shared_ptr<NodeObject> const& object) override store(std::shared_ptr<NodeObject> const& object) override
{ {
XRPL_ASSERT(db_, "xrpl::NodeStore::MemoryBackend::store : non-null database"); XRPL_ASSERT(db_, "xrpl::NodeStore::MemoryBackend::store : non-null database");
std::lock_guard const _(db_->mutex); std::scoped_lock const _(db_->mutex);
db_->table.emplace(object->getHash(), object); db_->table.emplace(object->getHash(), object);
} }

View File

@@ -207,7 +207,7 @@ public:
Status Status
fetch(uint256 const& hash, std::shared_ptr<NodeObject>* pno) override fetch(uint256 const& hash, std::shared_ptr<NodeObject>* pno) override
{ {
Status status = ok; Status status = Status::ok;
pno->reset(); pno->reset();
nudb::error_code ec; nudb::error_code ec;
db_.fetch( db_.fetch(
@@ -218,15 +218,15 @@ public:
DecodedBlob decoded(hash.data(), result.first, result.second); DecodedBlob decoded(hash.data(), result.first, result.second);
if (!decoded.wasOk()) if (!decoded.wasOk())
{ {
status = dataCorrupt; status = Status::dataCorrupt;
return; return;
} }
*pno = decoded.createObject(); *pno = decoded.createObject();
status = ok; status = Status::ok;
}, },
ec); ec);
if (ec == nudb::error::key_not_found) if (ec == nudb::error::key_not_found)
return notFound; return Status::notFound;
if (ec) if (ec)
Throw<nudb::system_error>(ec); Throw<nudb::system_error>(ec);
return status; return status;
@@ -241,7 +241,7 @@ public:
{ {
std::shared_ptr<NodeObject> nObj; std::shared_ptr<NodeObject> nObj;
Status const status = fetch(h, &nObj); Status const status = fetch(h, &nObj);
if (status != ok) if (status != Status::ok)
{ {
results.push_back({}); results.push_back({});
} }
@@ -251,7 +251,7 @@ public:
} }
} }
return {results, ok}; return {results, Status::ok};
} }
void void

View File

@@ -47,13 +47,13 @@ public:
} }
Status Status
fetch(void const*, std::shared_ptr<NodeObject>*) override fetch(uint256 const&, std::shared_ptr<NodeObject>*) override
{ {
return notFound; return Status::notFound;
} }
std::pair<std::vector<std::shared_ptr<NodeObject>>, Status> std::pair<std::vector<std::shared_ptr<NodeObject>>, Status>
fetchBatch(std::vector<uint256 const*> const& hashes) override fetchBatch(std::vector<uint256> const& hashes) override
{ {
return {}; return {};
} }

View File

@@ -285,7 +285,7 @@ public:
XRPL_ASSERT(m_db, "xrpl::NodeStore::RocksDBBackend::fetch : non-null database"); XRPL_ASSERT(m_db, "xrpl::NodeStore::RocksDBBackend::fetch : non-null database");
pObject->reset(); pObject->reset();
Status status(ok); Status status(Status::ok);
rocksdb::ReadOptions const options; rocksdb::ReadOptions const options;
rocksdb::Slice const slice(std::bit_cast<char const*>(hash.data()), m_keyBytes); rocksdb::Slice const slice(std::bit_cast<char const*>(hash.data()), m_keyBytes);
@@ -306,22 +306,23 @@ public:
{ {
// Decoding failed, probably corrupted! // Decoding failed, probably corrupted!
// //
status = dataCorrupt; status = Status::dataCorrupt;
} }
} }
else else
{ {
if (getStatus.IsCorruption()) if (getStatus.IsCorruption())
{ {
status = dataCorrupt; status = Status::dataCorrupt;
} }
else if (getStatus.IsNotFound()) else if (getStatus.IsNotFound())
{ {
status = notFound; status = Status::notFound;
} }
else else
{ {
status = Status(customCode + unsafe_cast<int>(getStatus.code())); status = static_cast<Status>(
static_cast<int>(Status::customCode) + unsafe_cast<int>(getStatus.code()));
JLOG(m_journal.error()) << getStatus.ToString(); JLOG(m_journal.error()) << getStatus.ToString();
} }
@@ -339,7 +340,7 @@ public:
{ {
std::shared_ptr<NodeObject> nObj; std::shared_ptr<NodeObject> nObj;
Status const status = fetch(h, &nObj); Status const status = fetch(h, &nObj);
if (status != ok) if (status != Status::ok)
{ {
results.push_back({}); results.push_back({});
} }
@@ -349,7 +350,7 @@ public:
} }
} }
return {results, ok}; return {results, Status::ok};
} }
void void

View File

@@ -56,7 +56,7 @@ public:
packed_spinlock sl(locks_, index % 64); packed_spinlock sl(locks_, index % 64);
{ {
std::lock_guard const lock(sl); std::scoped_lock const lock(sl);
// The check against the first character of the encoding ensures // The check against the first character of the encoding ensures
// that we don't mishandle the case of the all-zero account: // that we don't mishandle the case of the all-zero account:
@@ -69,7 +69,7 @@ public:
XRPL_ASSERT(ret.size() <= 38, "xrpl::detail::AccountIdCache : maximum result size"); XRPL_ASSERT(ret.size() <= 38, "xrpl::detail::AccountIdCache : maximum result size");
{ {
std::lock_guard const lock(sl); std::scoped_lock const lock(sl);
cache_[index].id = id; cache_[index].id = id;
std::strcpy(cache_[index].encoding, ret.c_str()); std::strcpy(cache_[index].encoding, ret.c_str());
} }

View File

@@ -40,7 +40,9 @@ setCurrentTransactionRules(std::optional<Rules> r)
// the value is needed. That could get expensive fast. // the value is needed. That could get expensive fast.
bool const enableLargeNumbers = bool const enableLargeNumbers =
!r || (r->enabled(featureSingleAssetVault) || r->enabled(featureLendingProtocol)); !r || (r->enabled(featureSingleAssetVault) || r->enabled(featureLendingProtocol));
Number::setMantissaScale(enableLargeNumbers ? MantissaRange::large : MantissaRange::small); Number::setMantissaScale(
enableLargeNumbers ? MantissaRange::mantissa_scale::large
: MantissaRange::mantissa_scale::small);
*getCurrentTransactionRulesRef() = std::move(r); *getCurrentTransactionRulesRef() = std::move(r);
} }

Some files were not shown because too many files have changed in this diff Show More