Compare commits

..

166 Commits

Author SHA1 Message Date
Ed Hennis
ed5e1dbeb3 Merge branch 'develop' into ximinez/number-maxint-range 2026-07-09 19:49:46 -04:00
Ed Hennis
642e09ac0a Merge remote-tracking branch 'XRPLF/develop' into ximinez/number-maxint-range
* XRPLF/develop:
  test: Migrate basics Beast tests to GTest (7136)
  test: Migrate resource, shamap Beast tests to GTest (7133)
  chore: Enable most misc checks (7663)
  chore: Fix unity build (7730)
  chore: Enable most modernize checks (7664)
  chore: Delete dead code (7718)
  chore: Enable modernize-use-constraints (7715)
  chore: Enable modernize-avoid-bind (7711)
2026-07-06 20:42:48 -04:00
Ed Hennis
82ca28f329 Fix some UB in test 2026-07-02 21:07:59 -04:00
Ed Hennis
f6a58620b2 Merge remote-tracking branch 'XRPLF/develop' into ximinez/number-maxint-range
* XRPLF/develop:
  chore: Enable modernize-use-auto (7707)
  build: Add protobuf dependencies to Nix (7706)
  feat: Enable ConfidentialTransfer and BatchV1_1 (7698)
  chore: Enable modernize-unary-static-assert (7705)
  chore: Make clang-tidy happy on macOS (7701)
  chore: Improve pre-commit hooks (7702)
2026-07-02 20:14:54 -04:00
Ed Hennis
e888522fbc clang-format: headers 2026-07-02 19:48:11 -04:00
Ed Hennis
ab6e0a9223 Merge remote-tracking branch 'XRPLF/develop' into ximinez/number-maxint-range
* XRPLF/develop: (80 commits)
  refactor: Retire DisallowIncomingV1 fix (7364)
  build: Add verify-headers target to cleanup headers (7670)
  refactor: Retire InnerObjTemplate fix (7368)
  fix: Disable AMM creation with Vault shares (7666)
  test: Add tests for TMProofPathResponse and TMReplayDeltaResponse invalid hash/key sizes (7593)
  ci: [DEPENDABOT] bump actions/setup-python from 6.2.0 to 6.3.0 (7657)
  build: Don't reuse binaries between different C++ versions (7681)
  chore: Update pre-commit hooks && actions (7686)
  feat: Add an invariant to ensure object deletion also deletes its pseudo-account (7445)
  feat: Add Batch (XLS-56) V1_1 (6446)
  feat: Introduce lending 1.1 amendment and add `MemoData` field to `VaultDelete` transaction (6324)
  chore: Use std::ranges where possible (7634)
  ci: Use macOS 26 Tahoe with apple-clang 21 (7601)
  build: Mark sec256k1 and mpt-crypto as transitive headers (7658)
  chore: Add a script to nicely format clang-tidy output (7650)
  chore: Enable most bugprone checks (7643)
  feat: Confidential Transfer for MPT (5860)
  fix: Use trustline balance direction to validate IOU PaymentMint/PaymentBurn (7584)
  fix: Unify freeze checks for pseudo-account deposit/withdraw (7382)
  fix: Block delegate tx from being queued (7640)
  ...
2026-07-02 11:23:35 -04:00
Ed Hennis
42a1106952 fix: Fix Number comparison operator for signed types
- Instead of completely removing the code, it is wrapped in an `if
  constexpr` sign check. That way, it's future proof in case the type of
  mantissa_ ever changes again.
- Ironically, this partially reverts PR 7406.
2026-06-12 14:57:37 -04:00
Ed Hennis
f75f3ca2ad Merge remote-tracking branch 'XRPLF/develop' into ximinez/number-maxint-range
* XRPLF/develop: (37 commits)
  test: Add null check unit test for `Oracle::aggregatePrice` (7306)
  ci: Patch conan recipe for Nix to be able to use on macOS (7532)
  ci: Run sanitizers on release builds too (7527)
  fix: Correct hybrid offer deletion on credential expiry (6843)
  ci: Make sanitizer flags lists in the profile, not a string (7449)
  ci: Make configurations launch on certain event types (7447)
  fix: Add [[maybe_unused]] to fix320Enabled for assert=OFF builds (7446)
  ci: Add `gh` and `file` to nix packages (7444)
  fix: Disable transaction invariants (7409)
  perf: Dispatch "hasInvalidAmount()" on type tag instead of dynamic_cast (7402)
  refactor: Retire fixUniversalNumber amendment (5962)
  test: Do not create data directory for memory databases (7323)
  ci: Launch upload-conan-deps on profile change (7442)
  fix: Fix Number comparison operator (7406)
  feat: Use C++ 23 standard (7431)
  refactor: Introduce XRPL_ASSERT_IF for amendment-gated assertions (7378)
  refactor: Change config section and key string literals into constants (7095)
  refactor: Use `std::move` and `std::string_view` where possible (7424)
  refactor: Use const function arguments where possible (7423)
  ci: Use XRPLF/actions build-multiarch-image workflow (7428)
  ...
2026-06-12 14:23:00 -04:00
Ed Hennis
6ce2752cad clang-tidy: readability-math-missing-parentheses 2026-06-02 11:56:28 -04:00
Ed Hennis
8c1b12c5f2 clang-tidy fixes: braces and variable names 2026-06-01 17:19:23 -04:00
Ed Hennis
4ac4ed179a Merge remote-tracking branch 'XRPLF/develop' into ximinez/number-maxint-range
* XRPLF/develop:
  ci: Check binaries separately from building them (7355)
  ci: [DEPENDABOT] bump eps1lon/actions-label-merge-conflict from 3.0.3 to 3.1.0 (7375)
  refactor: Use `STLedgerEntry` type aliases instead of `std::shared_ptr` (7282)
  fix: Adjust xrpld systemd service and update timer (7374)
  release: Bump version to 3.2.0-rc3 (7371)
  fix: Pin overpayment principal reduction to exact on-grid value (7360)
2026-06-01 14:37:14 -04:00
Ed Hennis
1e2d25b273 Merge commit '47365f4220' into ximinez/number-maxint-range
* commit '47365f4220':
  fix: Improve upward rounding edge cases for Number::operator/= (7328)
2026-06-01 14:37:02 -04:00
Ed Hennis
647685695e Merge commit '1599c1a672' into ximinez/number-maxint-range
* commit '1599c1a672':
  refactor: Revert "perf: Remove unnecessary caches (5439)" (7359)
  fix: Add zero domainID check for permissionedDomain (7362)
2026-06-01 14:33:08 -04:00
Ed Hennis
6e1ee4720a Merge remote-tracking branch 'XRPLF/ximinez/number-division-accuracy' into ximinez/number-maxint-range
* XRPLF/ximinez/number-division-accuracy:
  CI feedback: Add test cases covering other rounding modes
  Apply suggestions from code review
  Accept AI suggestion
  Update the testUpwardRoundsDown test to run under all scales
  Review feedback from Tapanito and AI
  Skip clang-tidy false positive: misc-include-cleaner
  ci: Run PR title and description checks on staging and release branches (7331)
  style: Run shfmt on workflows, actions and markdown bash code (7333)
  Remove TMax entirely from normalizeToRange; check type matching directly
  Tweak how the denominator is handled in division
  Minor fixes: missing include, variable init, typo
  Test optimization: Number_test::pow10
  Significant rewrite
  Use the local range instead of calling a function
  Make Number::operator/= significantly more accurate
2026-06-01 13:16:25 -04:00
Ed Hennis
f6a26ca34f CI feedback: Add test cases covering other rounding modes
- Downward with a negative result, and ToNearest with a remainder
  slightly larger than 0.5.
2026-05-29 18:54:08 -04:00
Ed Hennis
c0569037f8 Apply suggestions from code review
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
2026-05-29 16:34:51 -04:00
Ed Hennis
be9ae88d48 Accept AI suggestion
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
2026-05-28 23:38:54 -04:00
Ed Hennis
cd21d74538 Update the testUpwardRoundsDown test to run under all scales
- Demonstrates the incorrect "before" behavior
2026-05-28 19:58:52 -04:00
Ed Hennis
2fdfd2b420 Review feedback from Tapanito and AI
- Add missing headers.
- Improve code coverage exclusions.
- Clean up several variable names.
- Improve explanatory comments.
- Remove the switch statement from MantissaRange::getMin. Change it to
  a straight power of ten lookup.
2026-05-28 18:41:19 -04:00
Ed Hennis
06a3f76ccd Skip clang-tidy false positive: misc-include-cleaner 2026-05-28 17:47:41 -04:00
Ed Hennis
dadf4d737d Merge branch 'develop' into ximinez/number-division-accuracy 2026-05-28 17:46:40 -04:00
Ed Hennis
7b66b42713 Merge branch 'develop' into ximinez/number-division-accuracy 2026-05-27 17:00:59 -04:00
Ed Hennis
f622707b36 Merge remote-tracking branch 'XRPLF/develop' into ximinez/number-maxint-range
* XRPLF/develop:
  release: Bump version to 3.2.0-rc2 (7348)
  refactor: Enable support for `fixCleanup3_2_0` amendment (7347)
  release: Bump version to 3.2.0-rc1 (7335)
  fix: Fix a rounding error at the `Number::maxRep` cusp (7051)
2026-05-27 16:44:50 -04:00
Ed Hennis
18ac8a0583 Merge branch 'develop' into ximinez/number-division-accuracy 2026-05-27 15:18:17 -04:00
Ed Hennis
de2efa5cb9 Remove TMax entirely from normalizeToRange; check type matching directly 2026-05-27 13:06:52 -04:00
Ed Hennis
8dcd88e83c Tweak how the denominator is handled in division
- Removes one int64 to 128 conversion
2026-05-27 12:34:49 -04:00
Ed Hennis
5333422402 Merge remote-tracking branch 'XRPLF/develop' into ximinez/number-division-accuracy
* XRPLF/develop:
  fix: Fix a rounding error at the `Number::maxRep` cusp (7051)
2026-05-27 12:17:30 -04:00
Ed Hennis
4ec049e727 Minor fixes: missing include, variable init, typo 2026-05-27 12:09:13 -04:00
Ed Hennis
ae9c72bb7c Test optimization: Number_test::pow10 2026-05-27 00:36:38 -04:00
Ed Hennis
5abecb9fcb Significant rewrite
- Simplify Number::operator/= to use more constexpr values, and fewer
  variations.
  - Most significantly, rounding up doesn't need more precision, it only
    needs to know if there's a remainder after the current precision work
    is done. Tracked similarly Guard::xbit_.
- Build a constexpr lookup array for powers of 10. Only a handful of
  values are used, but since it's built at compile time, and constexpr,
  unused values do not affect memory or performance.
2026-05-27 00:07:48 -04:00
Ed Hennis
7c45a3b197 Merge remote-tracking branch 'XRPLF/ximinez/number-fix-maxrepcusp' into ximinez/number-maxint-range
* XRPLF/ximinez/number-fix-maxrepcusp: (32 commits)
  ci: Only push docker images in XRPLF/rippled (7330)
  clang-tidy: missing header
  ci: [DEPENDABOT] bump docker/setup-buildx-action from 4.0.0 to 4.1.0 (7322)
  ci: [DEPENDABOT] bump codecov/codecov-action from 6.0.0 to 6.0.1 (7321)
  ci: [DEPENDABOT] bump docker/build-push-action from 7.1.0 to 7.2.0 (7320)
  ci: [DEPENDABOT] bump docker/metadata-action from 6.0.0 to 6.1.0 (7319)
  ci: [DEPENDABOT] bump docker/login-action from 4.1.0 to 4.2.0 (7318)
  fix: Update `clang-tidy` to include `src/tests` directory header check (7307)
  clang-tidy: implicit bool conversion
  chore: Pin Python packages for codegen using uv (7329)
  style: Use shfmt instead of bashate (7326)
  fix: Fix edge-case where vault-depositor may get stuck (7139)
  Address some AI review feedback: predeclare, include, format, comment
  fix: Fix `VaultInvariant` and `VaultDeposit` precision bugs at IOU scale boundaries (7272)
  ci: Add clang to nix images (7308)
  fix: Include management-fee delta in doOverpayment assertion (7039)
  fix: Fix clang-tidy pre-commit hook to locate compile_commands.json from repo root (7325)
  fix: Use consistent scale for `debtTotal` (7093)
  fix: Skip deleted book directories and non-root modifications in `ValidBookDirectory` invariant (7312)
  fix: Address review feedback on FD/handle guarding (5823 follow-up) (7310)
  ...
2026-05-26 22:51:14 -04:00
Ed Hennis
12670b0c3f Merge branch 'ximinez/number-fix-maxrepcusp' into ximinez/number-division-accuracy 2026-05-26 19:21:05 -04:00
Ed Hennis
1e7876a03c Merge branch 'develop' into ximinez/number-fix-maxrepcusp 2026-05-26 19:21:01 -04:00
Ed Hennis
e851e80de0 Merge branch 'ximinez/number-fix-maxrepcusp' into ximinez/number-division-accuracy 2026-05-26 16:56:47 -04:00
Ed Hennis
a963035f76 Merge branch 'develop' into ximinez/number-fix-maxrepcusp 2026-05-26 16:56:43 -04:00
Ed Hennis
8ab904de57 Merge branch 'ximinez/number-fix-maxrepcusp' into ximinez/number-division-accuracy 2026-05-26 16:01:44 -04:00
Ed Hennis
100ec464d9 Merge branch 'develop' into ximinez/number-fix-maxrepcusp 2026-05-26 16:01:40 -04:00
Ed Hennis
e89e6f50e8 Merge remote-tracking branch 'XRPLF/ximinez/number-fix-maxrepcusp' into ximinez/number-division-accuracy
* XRPLF/ximinez/number-fix-maxrepcusp:
  clang-tidy: implicit bool conversion
  Address some AI review feedback: predeclare, include, format, comment
  fix: Fix `VaultInvariant` and `VaultDeposit` precision bugs at IOU scale boundaries (7272)
  ci: Add clang to nix images (7308)
  fix: Include management-fee delta in doOverpayment assertion (7039)
  fix: Fix clang-tidy pre-commit hook to locate compile_commands.json from repo root (7325)
  fix: Use consistent scale for `debtTotal` (7093)
  fix: Skip deleted book directories and non-root modifications in `ValidBookDirectory` invariant (7312)
  fix: Address review feedback on FD/handle guarding (5823 follow-up) (7310)
  fix: Fix non-canonical MPT amount (7117)
2026-05-26 15:53:36 -04:00
Ed Hennis
27456fa439 Use the local range instead of calling a function 2026-05-26 15:52:25 -04:00
Ed Hennis
d6844311c0 clang-tidy: missing header 2026-05-26 15:48:29 -04:00
Ed Hennis
fbee0349f5 clang-tidy: implicit bool conversion 2026-05-26 15:21:42 -04:00
Ed Hennis
84ca271d95 Address some AI review feedback: predeclare, include, format, comment
- Predeclare type reference in Rules.h
- Remove an unneeded include in EscrowToken_test
- Number_test will format negative BigInts correctly (unused)
- Remove an inaccurate comment
2026-05-26 13:51:06 -04:00
Ed Hennis
75dfc65f5f Merge branch 'develop' into ximinez/number-fix-maxrepcusp 2026-05-26 13:47:33 -04:00
Ed Hennis
48b1716e6f Make Number::operator/= significantly more accurate
- Prevents extreme dust rounding from getting lost, especially when
  rounding away from zero. (Upward for positive, downward for negative.)
2026-05-23 19:02:03 +01:00
Ed Hennis
4ab886bcbc Merge branch 'develop' into ximinez/number-fix-maxrepcusp 2026-05-22 17:56:15 -04:00
Ed Hennis
7f64c337d8 Merge branch 'develop' into ximinez/number-fix-maxrepcusp 2026-05-21 14:25:50 -04:00
Ed Hennis
61bdd6fb78 Merge branch 'develop' into ximinez/number-fix-maxrepcusp 2026-05-21 10:10:00 -04:00
Ed Hennis
19c60924a5 Merge remote-tracking branch 'XRPLF/ximinez/number-fix-maxrepcusp' into ximinez/number-maxint-range
* XRPLF/ximinez/number-fix-maxrepcusp:
  Fix more AMM tests, and to not exclude fixCleanup3_2_0
  docs: Add --parallel flag to cmake build commands in BUILD.md (7302)
  fix: Fix wrong hybrid offer orderbook placement and update `LedgerStateFix` to amend `ExchangeRate` meta (7087)
  Change the priority of the amendments for large mantissas
  Apply suggestions from @Tapanito code review
  Apply suggestions from Copilot code review
  Review feedback from @tapanito: lambda checks condition in doRoundUp
  style: More clang-tidy identifier renaming (7290)
  fix: Update pDEX invariant firing under a valid offer deletion (7118)
  fix: Fix multisign and signfor to check for delegate (7064)
  refactor: Fix `sfGeneric` and `sfInvalid` field names (7300)
  docs: Fix some comments to improve readability (7122)
  feat: Propagate underlying MPT flags to vault shares (7077)
2026-05-21 15:07:39 +01:00
Ed Hennis
8e06e78f11 Merge branch 'develop' into ximinez/number-fix-maxrepcusp 2026-05-21 07:11:49 -04:00
Ed Hennis
42fda85fbc Fix more AMM tests, and to not exclude fixCleanup3_2_0 2026-05-21 12:04:29 +01:00
Ed Hennis
3a4b92b050 Change the priority of the amendments for large mantissas
- Order the checks so that large mantissa is only enabled if SAV or LP
  are enabled. fixCleanup3_2_0 only enables the rounding fix.
- Fix tests, and don't exclude fixCleanup3_2_0 in AMM tests
- Also fix formatting
2026-05-21 00:53:07 +01:00
Ed Hennis
aea19df3c1 Apply suggestions from @Tapanito code review
Co-authored-by: Vito Tumas <5780819+Tapanito@users.noreply.github.com>
2026-05-20 18:46:17 -04:00
Ed Hennis
8b56749ca3 Apply suggestions from Copilot code review
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
2026-05-20 18:39:46 -04:00
Ed Hennis
71cf996fc6 Review feedback from @tapanito: lambda checks condition in doRoundUp 2026-05-20 23:28:26 +01:00
Ed Hennis
7cacb3cce5 Merge remote-tracking branch 'XRPLF/ximinez/number-fix-maxrepcusp' into ximinez/number-maxint-range
* XRPLF/ximinez/number-fix-maxrepcusp:
  fix: Disable unnecessary sanity-check in VaultDeposit (7288)
  ci: [DEPENDABOT] bump actions/upload-artifact from 7.0.0 to 7.0.1 (7286)
  ci: Only run reusable package in public repos (7293)
  fix: Set default peering port to 2459 (6848)
  fix: Use account ledger entry when canceling token escrows (6171)
  refactor: Rename `account_` to `accountID_` (7284)
  ci: Add Linux package builds (DEB + RPM) to CI (6639)
  refactor: Clean up comments post-clang-tidy changes (7283)
  release: Set version to 3.3.0-b0 (7280)
  refactor: Rename static constants (7120)
  refactor: Use `isFlag` where possible instead of bitwise math (7278)
  ci: Update XRPLF/actions (7281)
  clang-tidy: this is ridiculous
  clang-tidy: {}
2026-05-20 12:19:15 +01:00
Ed Hennis
4c7ea64b6c Merge branch 'develop' into ximinez/number-fix-maxrepcusp 2026-05-19 16:53:33 -04:00
Ed Hennis
c8947c6f75 Merge branch 'develop' into ximinez/number-fix-maxrepcusp 2026-05-19 10:15:10 -04:00
Ed Hennis
09ae5b719f Merge branch 'develop' into ximinez/number-fix-maxrepcusp 2026-05-19 05:15:47 -04:00
Ed Hennis
09f2d06dd4 Merge branch 'develop' into ximinez/number-fix-maxrepcusp 2026-05-15 21:32:09 -04:00
Ed Hennis
6964013941 Merge remote-tracking branch 'XRPLF/develop' into ximinez/number-fix-maxrepcusp
* XRPLF/develop:
  release: Set version to 3.3.0-b0 (7280)
  refactor: Rename static constants (7120)
  refactor: Use `isFlag` where possible instead of bitwise math (7278)
  ci: Update XRPLF/actions (7281)
2026-05-15 21:14:34 -04:00
Ed Hennis
ad32568f7e clang-tidy: Capitalization and other small things 2026-05-14 21:14:53 -04:00
Ed Hennis
70c6e01d7e clang-tidy: this is ridiculous 2026-05-14 21:02:49 -04:00
Ed Hennis
ddfb7ee69c clang-tidy: {} 2026-05-14 20:48:34 -04:00
Ed Hennis
29eb9a6df4 Merge branch 'ximinez/number-fix-maxrepcusp' into ximinez/number-maxint-range 2026-05-14 20:38:59 -04:00
Ed Hennis
b69b9242e2 fixup! clang-tidy: Avoid nested "?:" in global Rules initialization 2026-05-14 20:33:15 -04:00
Ed Hennis
cd2fcf0a5e Merge branch 'develop' into ximinez/number-fix-maxrepcusp 2026-05-14 18:25:17 -04:00
Ed Hennis
69656d6b67 clang-tidy: Avoid nested "?:" in global Rules initialization 2026-05-14 18:24:05 -04:00
Ed Hennis
06b9e18333 Merge branch 'ximinez/number-fix-maxrepcusp' into ximinez/number-maxint-range 2026-05-14 10:49:08 -04:00
Ed Hennis
46b946b22e clang-tidy: missing include 2026-05-13 22:32:37 -04:00
Ed Hennis
ae03b30f29 Merge branch 'develop' into ximinez/number-fix-maxrepcusp 2026-05-13 20:16:19 -04:00
Ed Hennis
974f36fc72 Merge branch 'ximinez/number-fix-maxrepcusp' into ximinez/number-maxint-range 2026-05-13 12:04:28 -04:00
Ed Hennis
4c7c019add Merge branch 'develop' into ximinez/number-fix-maxrepcusp 2026-05-13 12:03:35 -04:00
Ed Hennis
47f30c913d Fix broken unit tests: EscrowToken
- Some EscrowToken tests used a hard-coded list of amendments to
  determine whether to expect large mantissa logic. That ignored the
  effects of fixCleanup3_2_0, especially as applied to the previous fix
  affecting preflight, preclaim, etc.
- Add a helper function, useRulesGuards, which will return the same
  decision as createGuards and setCurrentRulesImpl. Use that helper
  function in the relevant tests.
- Also remove an #include that clang-tidy was complaining about.
2026-05-12 21:26:54 -04:00
Ed Hennis
e50bb3d307 Merge branch 'ximinez/number-fix-maxrepcusp' into ximinez/number-maxint-range 2026-05-12 20:11:56 -04:00
Ed Hennis
d7d5b83f6d Merge branch 'develop' into ximinez/number-fix-maxrepcusp 2026-05-12 19:18:45 -04:00
Ed Hennis
abc5f59fed Tweak tests after another big merge 2026-05-12 19:16:50 -04:00
Ed Hennis
e22938d69f AI review feedback: createGuards
- Refactor the Guard decision in withTxnType into createGuards, which
  lives in Rules.cpp. It is physically located near
  setCurrentTransactionRules, and documented to explain that changes
  need to be synchronized.
2026-05-12 18:44:05 -04:00
Ed Hennis
dae0943dc3 Fix a couple of bugs introduced by the previous merge 2026-05-12 16:57:01 -04:00
Ed Hennis
7c9a56ff24 Merge branch 'develop' into ximinez/number-fix-maxrepcusp 2026-05-12 16:26:09 -04:00
Ed Hennis
5a40416673 Merge branch 'develop' into ximinez/number-fix-maxrepcusp 2026-05-12 15:59:19 -04:00
Ed Hennis
f483118498 Merge remote-tracking branch 'mywork/ximinez/number-fix-maxrepcusp' into ximinez/number-maxint-range
* mywork/ximinez/number-fix-maxrepcusp:
  Address more nitpicky AI comments
  What is it going to take to get clang-tidy to shut up?
  More clang-tidy changes: AMMExtended_test member and Number_test includes
  Fix clang-tidy issues, and more AI complaints
  Fix AI-identified mistakes
  fix: Fix a rounding error at the Number::maxRep cusp
2026-05-12 01:24:36 -04:00
Ed Hennis
30334cd1f4 Merge branch 'develop' into ximinez/number-fix-maxrepcusp 2026-05-11 13:34:11 -04:00
Ed Hennis
257da7972f Merge branch 'develop' into ximinez/number-maxint-range 2026-05-07 18:10:49 -04:00
Ed Hennis
5558e1b522 Merge branch 'develop' into ximinez/number-fix-maxrepcusp 2026-05-07 18:10:03 -04:00
Ed Hennis
cd0f49a003 Address more nitpicky AI comments 2026-05-07 17:05:10 -04:00
Ed Hennis
22d2703ce8 What is it going to take to get clang-tidy to shut up? 2026-05-07 16:50:43 -04:00
Ed Hennis
501b027a76 Merge branch 'develop' into ximinez/number-maxint-range 2026-05-07 14:19:57 -04:00
Ed Hennis
d03274b731 Merge branch 'develop' into ximinez/number-fix-maxrepcusp 2026-05-07 14:18:28 -04:00
Ed Hennis
1b6047afe1 More clang-tidy changes: AMMExtended_test member and Number_test includes 2026-05-07 13:51:48 -04:00
Ed Hennis
668fa65384 Merge branch 'develop' into ximinez/number-maxint-range 2026-05-07 13:29:17 -04:00
Ed Hennis
175a04160d Merge branch 'develop' into ximinez/number-fix-maxrepcusp 2026-05-07 13:28:33 -04:00
Ed Hennis
b050c151f8 Fix clang-tidy issues, and more AI complaints 2026-05-06 23:26:11 -04:00
Ed Hennis
a2b21d75ce Fix AI-identified mistakes 2026-05-06 22:56:07 -04:00
Ed Hennis
b40d2a8e7d fix: Fix a rounding error at the Number::maxRep cusp
- Add helper function, doDropDigit, to wrap the common pattern:
    push(mantissa % 10);
    mantissa /= 10;
    ++exponent;
- Might have been helpful to catch this issue when developing.
2026-05-06 22:49:44 -04:00
Ed Hennis
54db82dc42 Merge branch 'develop' into ximinez/number-maxint-range 2026-05-06 22:35:06 -04:00
Ed Hennis
1b67c2260c Merge branch 'develop' into ximinez/number-maxint-range 2026-05-06 14:18:47 -04:00
Ed Hennis
257e568cb6 Merge remote-tracking branch 'XRPLF/develop' into ximinez/number-maxint-range
* XRPLF/develop:
  fix: Fix regressions in `server_definitions` (7008)
  chore: Do not duplicate sanitizer flags (7058)
  ci: Run pre-commit on diff in clang-tidy workflow (7078)
  ci: Use XRPLF/create-issue (7076)
  ci: Rewrite clang-tidy workflow(s) in a reusable manner (7062)
  chore: Ignore identifier-naming update in git blame (7066)
  refactor: Enable clang-tidy `readability-identifier-naming` check (6571)
2026-05-05 21:08:35 -04:00
Ed Hennis
fd2040a56d Merge remote-tracking branch 'XRPLF/develop' into ximinez/number-maxint-range
* XRPLF/develop:
  refactor: Revert certain `Throw`s by `LogicError`s (7036)
  ci: Rename print-env -> print-build-env (7061)
  fix: Gate -mcmodel flags to x86_64 in sanitizer builds (7049)
  fix: Prevents overwriting a bool value in an invariant (6609)
  fix: Address code review comments regarding `boost::coroutine2` (6977)
  refactor: Apply various minor improvements and corrections (7045)
  fix: Store `Delegate` object in delegating and authorized account directories for proper deletion (6681)
  ci: Use print-env from XRPLF/actions (7052)
  fix: Make assorted RPC fixes (6529)
  chore: Enable clang-tidy v21 new checks (7031)
2026-05-01 14:32:51 -04:00
Ed Hennis
c06504353c Number perf test
- Run the Number test suite 1000 times to allow for performance measurement
2026-05-01 14:02:39 -04:00
Ed Hennis
51ab048b97 fixup! Fix clang-tidy 2026-04-29 12:10:11 -04:00
Ed Hennis
fc569b9410 Merge branch 'develop' into ximinez/number-maxint-range 2026-04-29 11:05:57 -04:00
Ed Hennis
c2f25c2a34 Merge remote-tracking branch 'XRPLF/develop' into ximinez/number-maxint-range
* XRPLF/develop:
  chore: Enable clang-tidy modernize-use-nodiscard check (7015)
  fix: Resolve MSVC Debug build failure in JobQueue.h; re-enable _CRTDBG_MAP_ALLOC in CI (6993)
  docs: Update hybrid offer invariant comment (7007)
2026-04-26 22:29:50 -05:00
Ed Hennis
ee33d98f50 Merge branch 'develop' into ximinez/number-maxint-range 2026-04-24 12:54:01 -04:00
Ed Hennis
1226255662 Merge branch 'develop' into ximinez/number-maxint-range 2026-04-23 15:56:51 -04:00
Ed Hennis
d914b633da Merge branch 'develop' into ximinez/number-maxint-range 2026-04-22 23:53:36 -04:00
Ed Hennis
e3b390f949 Merge branch 'develop' into ximinez/number-maxint-range 2026-04-22 14:49:47 -04:00
Ed Hennis
5a7be26402 Merge branch 'develop' into ximinez/number-maxint-range 2026-04-22 13:11:20 -04:00
Ed Hennis
25e0b4eeb5 Merge branch 'develop' into ximinez/number-maxint-range 2026-04-21 19:35:21 -04:00
Ed Hennis
c4ef1e6997 Merge remote-tracking branch 'XRPLF/develop' into ximinez/number-maxint-range
* XRPLF/develop:
  fix: Disallow MPTClearRequireAuth if is set (6712)
  feat: Add GRPC TLS support (6374)
  fix: Check for empty `sfAdditionalBooks` array in hybrid offer invariant (6716)
  chore: Remove repetitive word in multiple files (6978)
  ci: Add workflow to check PR description has been filled (6965)
  ci: [DEPENDABOT] Bump tj-actions/changed-files from 47.0.5 to 47.0.6 (6973)
  chore: Enable clang-tidy include cleaner (6947)
  fix: Change AMMClawback return code to tecNO_PERMISSION (6946)
  ci: [DEPENDABOT] bump actions/upload-pages-artifact from 4.0.0 to 5.0.0 (6927)
  ci: [DEPENDABOT] bump actions/upload-artifact from 7.0.0 to 7.0.1 (6928)
  chore: Enable clang-tidy readability checks (6930)
2026-04-20 18:59:21 -04:00
Ed Hennis
ac20f3221f Merge branch 'develop' into ximinez/number-maxint-range 2026-04-16 13:45:08 -04:00
Ed Hennis
1e764cd172 Merge branch 'develop' into ximinez/number-maxint-range 2026-04-15 19:09:51 -04:00
Ed Hennis
371d3a6f30 Merge branch 'develop' into ximinez/number-maxint-range 2026-04-15 14:29:29 -04:00
Ed Hennis
018e36f1ca Merge branch 'develop' into ximinez/number-maxint-range 2026-04-13 20:45:31 -04:00
Ed Hennis
ee9b486f8b Fix clang-tidy 2026-04-13 20:17:55 -04:00
Ed Hennis
47f6422ee7 Merge branch 'develop' into ximinez/number-maxint-range 2026-04-10 12:12:38 -04:00
Ed Hennis
8201d0330e Merge branch 'develop' into ximinez/number-maxint-range 2026-04-10 09:11:23 -04:00
Ed Hennis
9ac062c5a0 Merge branch 'develop' into ximinez/number-maxint-range 2026-04-09 11:41:18 -04:00
Ed Hennis
f631d95585 Merge branch 'develop' into ximinez/number-maxint-range 2026-04-08 16:57:46 -04:00
Ed Hennis
efa3328aba Merge branch 'develop' into ximinez/number-maxint-range 2026-04-08 15:13:36 -04:00
Ed Hennis
9daa985bf1 Merge branch 'develop' into ximinez/number-maxint-range 2026-04-07 16:48:22 -04:00
Ed Hennis
d3b1ee9ec0 Merge branch 'develop' into ximinez/number-maxint-range 2026-04-06 19:07:42 -04:00
Ed Hennis
e160b95aef Merge branch 'develop' into ximinez/number-maxint-range 2026-04-06 18:34:11 -04:00
Ed Hennis
14843e15d8 Merge branch 'develop' into ximinez/number-maxint-range 2026-04-06 16:54:12 -04:00
Ed Hennis
f8359d9b0c Merge branch 'develop' into ximinez/number-maxint-range 2026-04-01 17:26:22 -04:00
Ed Hennis
8ed8b52dfe Merge remote-tracking branch 'XRPLF/develop' into ximinez/number-maxint-range
* XRPLF/develop:
  fix: Remove fatal assertion on Linux thread name truncation  (6690)
  chore: Enable clang-tidy `coreguidelines` checks (6698)
  ci: Allow uploading artifacts for XRPLF org (6702)
  fix: Enforce aggregate MaximumAmount in multi-send MPT (6644)
  chore: Use nudb recipe from the upstream (6701)
  fix: Fix previous ledger size typo in RCLConsensus (6696)
  chore: Enable clang-tidy misc checks (6655)
  ci: Use pull_request_target to check for signed commits (6697)
  chore: Remove unnecessary clang-format off/on directives (6682)
  fix: Fix Workers::stop() race between m_allPaused and m_runningTaskCount (6574)
2026-04-01 14:07:25 -04:00
Ed Hennis
62d0b07ee8 Merge remote-tracking branch 'XRPLF/develop' into ximinez/number-maxint-range
* XRPLF/develop: (81 commits)
  ci: Only publish docs in public repos (6687)
  chore: Enable remaining clang-tidy `performance` checks (6648)
  refactor: Address PR comments after the modularisation PRs (6389)
  chore: Fix clang-tidy header filter (6686)
  ci: [DEPENDABOT] bump actions/deploy-pages from 4.0.5 to 5.0.0 (6684)
  ci: [DEPENDABOT] bump codecov/codecov-action from 5.5.3 to 6.0.0 (6685)
  fix: Guard Coro::resume() against completed coroutines (6608)
  refactor: Split LoanInvariant into LoanBrokerInvariant and LoanInvariant (6674)
  ci: Don't publish docs on release branches (6673)
  refactor: Make function naming in ServiceRegistry consistent (6390)
  chore: Shorten job names to stay within Linux 15-char thread limit (6669)
  fix: Improve loan invariant message (6668)
  ci: Upload artifacts only in public repositories (6670)
  ci: Add conflicting-pr workflow (6656)
  chore: Add more AI tools to .gitignore (6658)
  chore: Show warning message if user may need to connect to VPN (6619)
  feat: Add placeholder amendment for assorted bug fixes (6652)
  chore: Update sqlite3->3.51.0, protobuf->6.33.5, openssl->3.6.1, grpc->1.78.1 (6653)
  refactor: Modularise ledger (6536)
  chore: Use unpatched version of soci (6649)
  ...
2026-03-30 22:01:54 -04:00
Ed Hennis
44ea0b24c8 Merge branch 'develop' into ximinez/number-maxint-range 2026-03-12 15:04:55 -04:00
Ed Hennis
e443a76d83 Merge branch 'develop' into ximinez/number-maxint-range 2026-03-10 13:38:28 -04:00
Ed Hennis
eef1f791e8 Merge branch 'develop' into ximinez/number-maxint-range 2026-03-06 13:04:09 -04:00
Ed Hennis
2191ef8d75 Merge branch 'develop' into ximinez/number-maxint-range 2026-03-04 17:11:35 -04:00
Ed Hennis
ea4f922492 Merge branch 'develop' into ximinez/number-maxint-range 2026-03-03 18:38:31 -04:00
Ed Hennis
9250ba9e27 Merge branch 'develop' into ximinez/number-maxint-range 2026-03-03 15:54:39 -04:00
Ed Hennis
61f38ba068 Review feedback from @copilot 2026-02-25 20:37:22 -05:00
Ed Hennis
3d5ff2c8a2 Apply suggestions from code review
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2026-02-25 21:10:11 -04:00
Ed Hennis
e27249134a Merge branch 'develop' into ximinez/number-maxint-range 2026-02-24 17:34:41 -04:00
Ed Hennis
d79fdec886 Merge branch 'develop' into ximinez/number-maxint-range 2026-02-24 16:46:05 -04:00
Ed Hennis
024d05b70c Merge branch 'develop' into ximinez/number-maxint-range 2026-02-20 18:49:46 -04:00
Ed Hennis
ffb3e1da53 Merge branch 'develop' into ximinez/number-maxint-range 2026-02-20 18:26:05 -04:00
Ed Hennis
aef7e5b335 Merge branch 'develop' into ximinez/number-maxint-range 2026-02-20 17:31:47 -04:00
Ed Hennis
e2c09e79d0 Merge branch 'develop' into ximinez/number-maxint-range 2026-02-20 17:21:09 -04:00
Ed Hennis
c6f854bbd8 Merge branch 'develop' into ximinez/number-maxint-range 2026-02-20 15:14:29 -04:00
Ed Hennis
6a1e0b0f5a Merge remote-tracking branch 'upstream/develop' into ximinez/number-maxint-range
* upstream/develop:
  ci: Add dependabot config (6379)
  Fix tautological assertion (6393)
2026-02-20 13:38:46 -05:00
Ed Hennis
01f5ae0927 Merge commit '2c1fad1023' into ximinez/number-maxint-range
* commit '2c1fad1023':
  chore: Apply clang-format width 100 (6387)
2026-02-20 13:38:00 -05:00
Ed Hennis
9b4587f9af Update formatting 2026-02-20 13:29:51 -05:00
Ed Hennis
fbc6f87983 Merge commit '25cca465538a56cce501477f9e5e2c1c7ea2d84c' into ximinez/number-maxint-range
* commit '25cca465538a56cce501477f9e5e2c1c7ea2d84c':
  chore: Set clang-format width to 100 in config file (6387)
2026-02-20 13:29:06 -05:00
Ed Hennis
0871eb0cb6 Address review feedback from @Copilot
- Clarify comments and add missing header
2026-02-19 19:06:03 -05:00
Ed Hennis
2ccf132f79 Apply suggestions from code review
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2026-02-19 19:02:03 -05:00
Ed Hennis
6600153958 Merge branch 'develop' into ximinez/number-maxint-range 2026-02-19 16:21:18 -05:00
Ed Hennis
fff73dac51 Merge branch 'develop' into ximinez/number-maxint-range 2026-02-18 20:18:56 -04:00
Ed Hennis
06ff77458a fixup! fixup! fixup! fixup! Address review feedback from @copilot 2026-02-05 20:33:30 -05:00
Ed Hennis
f19ecb3b80 fixup! fixup! fixup! Address review feedback from @copilot 2026-02-05 19:56:18 -05:00
Ed Hennis
cc2406bf3f fixup! fixup! Address review feedback from @copilot 2026-02-05 19:13:14 -05:00
Ed Hennis
30c65320e4 fixup! Address review feedback from @copilot 2026-02-05 18:25:23 -05:00
Ed Hennis
569d9ea94e Address review feedback from @copilot
- Update explanations.
- Use saver conversions between signed and unsigned.
2026-02-05 14:06:09 -05:00
Ed Hennis
02b7bcfa2b Merge branch 'develop' into ximinez/number-maxint-range 2026-02-05 13:29:56 -04:00
Ed Hennis
07c0c320a7 Fix formatting 2026-02-05 12:28:43 -05:00
Ed Hennis
d57e37c34b Fix renaming 2026-02-05 12:28:43 -05:00
Ed Hennis
154bb65c35 Merge remote-tracking branch 'upstream/develop' into ximinez/number-maxint-range
* upstream/develop:
  chore: Update secp256k1 and openssl (6327)
  chore: Remove unnecessary script (6326)
  refactor: Replace include guards by '#pragma once' (6322)
  chore: Remove unity builds (6300)
  refactor: Add ServiceRegistry to help modularization (6222)
  fix: Deletes expired NFToken offers from ledger (5707)
  chore: Add .zed editor config directory to .gitignore (6317)
  docs: Update API changelog, add APIv2+APIv3 version documentation (6308)
  fix: Restore config changes that broke standalone mode (6301)
  chore: Add upper-case match for ARM64 in CompilationEnv (6315)
  ci: Update hashes of XRPLF/actions (6316)
  chore: Format all cmake files without comments (6294)
  chore: Add cmake-format pre-commit hook (6279)
  chore: Remove unnecessary `boost::system` requirement from conanfile (6290)
2026-02-04 21:10:15 -05:00
Ed Hennis
111eda22e9 Merge commit '5f638f55536def0d88b970d1018a465a238e55f4' into ximinez/number-maxint-range
* commit '5f638f55536def0d88b970d1018a465a238e55f4':
  chore: Set ColumnLimit to 120 in clang-format (6288)
2026-02-04 21:09:02 -05:00
Ed Hennis
f7b6834d2a Add unit tests for normalizeToRange
- Steal changes from @pratik's #6150 to avoid UB
2026-02-04 21:08:48 -05:00
Ed Hennis
e464adaee6 Clean-ups and tweaks 2026-02-04 21:08:48 -05:00
Ed Hennis
cca92dedca Reduce expensive(?) accesses to thread_local MantissaRange 2026-02-04 21:08:48 -05:00
Ed Hennis
3d6f57a4df Fix bugs
- Simplify shiftExponent().
- Clean up to_string() to prevent integers from including "e0".
- Fix root() and root2() computations by ensuring the mantissas have
  a consistent length.
2026-02-04 21:08:46 -05:00
Ed Hennis
fc29fbe946 Convert "bool negative_ & uint64_t mantissa_" combo back to "rep mantissa_" 2026-02-04 21:08:34 -05:00
Ed Hennis
5e0a8d5c8a Remove the _ suffixes from doNormalize function parameters 2026-02-04 21:08:33 -05:00
Ed Hennis
d27788f12a Use 2^63-1 as maxMantissa for large range
- That makes minMantissa 2^63/10+1.
- Simplifies many of the existing operations, and removes the need for
  the accessors (mantissa() & exponent()) to do any math.
2026-02-04 21:08:33 -05:00
839 changed files with 15894 additions and 35580 deletions

View File

@@ -56,17 +56,32 @@ Checks: "-*,
readability-*,
-readability-avoid-const-params-in-decls,
-readability-avoid-unconditional-preprocessor-if,
-readability-container-data-pointer,
-readability-delete-null-pointer,
-readability-function-cognitive-complexity,
-readability-function-size,
-readability-identifier-length,
-readability-inconsistent-declaration-parameter-name,
-readability-isolate-declaration,
-readability-magic-numbers,
-readability-misplaced-array-index,
-readability-named-parameter,
-readability-operators-representation,
-readability-qualified-auto,
-readability-redundant-access-specifiers,
-readability-redundant-control-flow,
-readability-redundant-function-ptr-dereference,
-readability-redundant-preprocessor,
-readability-redundant-smartptr-get,
-readability-redundant-string-cstr,
-readability-simplify-subscript-expr,
-readability-static-accessed-through-instance,
-readability-uppercase-literal-suffix
-readability-string-compare,
-readability-uniqueptr-delete-release,
-readability-uppercase-literal-suffix,
-readability-use-anyofallof,
-readability-use-concise-preprocessor-directives
"
# ---
# bugprone-narrowing-conversions, # This will break a lot of code but we should enable it in the future because it can eliminate a lot of bugs

View File

@@ -65,7 +65,6 @@ words:
- Btrfs
- Buildx
- canonicality
- canonicalised
- changespq
- checkme
- choco
@@ -73,7 +72,6 @@ words:
- citardauq
- clawback
- clawbacks
- clippy
- cmaketoolchain
- coeffs
- coldwallet
@@ -261,7 +259,6 @@ words:
- rocksdb
- Rohrs
- roundings
- rustc
- sahyadri
- Satoshi
- scons
@@ -282,8 +279,6 @@ words:
- sles
- soci
- socidb
- sponsee
- sponsees
- SRPMS
- sslws
- statsd
@@ -305,7 +300,6 @@ words:
- takerpays
- ters
- TMEndpointv2
- tparam
- trixie
- tx
- txid
@@ -333,7 +327,6 @@ words:
- unserviced
- unshareable
- unshares
- unsponsored
- unsquelch
- unsquelched
- unsquelching

View File

@@ -25,16 +25,24 @@ def get_cmake_args(build_type: str, extra_args: str) -> str:
return " ".join(args)
def runs_on_event(exclude_event_types: list[str], event: str | None) -> bool:
"""Whether a config should run for the current event.
'exclude_event_types' is a list of GitHub event names (e.g.
["pull_request"]) on which the config should NOT run; an empty list means
the config runs on every event. When no event is given (event is None), no
filtering is applied.
"""
if event is None:
return True
return event not in exclude_event_types
# ---------------------------------------------------------------------------
# Input types — shapes of the JSON config files
# ---------------------------------------------------------------------------
# Every config must declare 'minimal'. Minimal configs form the reduced matrix
# built for pull requests by default; the full matrix adds the rest. Packaging
# configs declare it too, but packaging is gated in the workflow, not by it.
@dataclasses.dataclass
class LinuxConfig:
"""One entry in linux.json's 'configs' or 'package_configs' arrays."""
@@ -42,11 +50,13 @@ class LinuxConfig:
compiler: list[str]
build_type: list[str]
arch: list[str]
minimal: bool
sanitizers: list[str] = dataclasses.field(default_factory=list)
suffix: str = ""
extra_cmake_args: str = ""
image: str = "" # only used by package_configs entries
# List of GitHub event names (e.g. "pull_request") on which this config
# should NOT run. Empty means it runs on every event.
exclude_event_types: list[str] = dataclasses.field(default_factory=list)
@dataclasses.dataclass
@@ -79,9 +89,11 @@ class PlatformConfig:
"""One entry in macos.json's or windows.json's 'configs' array."""
build_type: list[str]
minimal: bool
build_only: bool = False # if true, skip tests (e.g. macos/Windows Debug)
extra_cmake_args: str = ""
# List of GitHub event names (e.g. "pull_request") on which this config
# should NOT run. Empty means it runs on every event.
exclude_event_types: list[str] = dataclasses.field(default_factory=list)
def __post_init__(self) -> None:
if isinstance(self.build_type, str):
@@ -156,18 +168,20 @@ _ARCHS: dict[str, Architecture] = {
}
def expand_linux_matrix(linux: LinuxFile, minimal: bool) -> list[MatrixEntry]:
def expand_linux_matrix(
linux: LinuxFile, event: str | None = None
) -> list[MatrixEntry]:
"""Expand a LinuxFile into a flat list of matrix entries.
Each config entry is expanded over the cross-product of its
compiler, build_type, sanitizers, and architecture lists. When 'minimal' is
true, only configs flagged as minimal are included.
compiler, build_type, sanitizers, and architecture lists. Configs that
exclude the current event are skipped.
"""
entries: list[MatrixEntry] = []
for distro, configs in linux.configs.items():
for cfg in configs:
if minimal and not cfg.minimal:
if not runs_on_event(cfg.exclude_event_types, event):
continue
# An empty sanitizers list means "one entry with no sanitizer".
effective_sanitizers = cfg.sanitizers or [""]
@@ -226,17 +240,19 @@ def expand_linux_packaging(linux: LinuxFile) -> list[PackagingEntry]:
return entries
def expand_platform_matrix(pf: PlatformFile, minimal: bool) -> list[MatrixEntry]:
def expand_platform_matrix(
pf: PlatformFile, event: str | None = None
) -> list[MatrixEntry]:
"""Expand a PlatformFile (macOS or Windows) into matrix entries.
When 'minimal' is true, only configs flagged as minimal are included.
Configs that exclude the current event are skipped.
"""
platform_name, arch = pf.platform.split("/")
is_windows = platform_name == "windows"
entries: list[MatrixEntry] = []
for cfg in pf.configs:
if minimal and not cfg.minimal:
if not runs_on_event(cfg.exclude_event_types, event):
continue
for build_type in cfg.build_type:
entries.append(
@@ -276,12 +292,12 @@ if __name__ == "__main__":
action="store_true",
)
parser.add_argument(
"-m",
"--minimal",
help="Emit only the minimal matrix (the configs flagged 'minimal'), "
"used for pull requests by default. If omitted, the full matrix is "
"emitted.",
action="store_true",
"-e",
"--event",
help="The GitHub event name that triggered the workflow (e.g. 'push', "
"'pull_request'). Configs are filtered by their 'event_type'. If "
"omitted, no filtering is applied.",
default=None,
)
args = parser.parse_args()
@@ -292,15 +308,15 @@ if __name__ == "__main__":
else:
if args.config in ("linux", None):
matrix += expand_linux_matrix(
LinuxFile.load(THIS_DIR / "linux.json"), args.minimal
LinuxFile.load(THIS_DIR / "linux.json"), args.event
)
if args.config in ("macos", None):
matrix += expand_platform_matrix(
PlatformFile.load(THIS_DIR / "macos.json"), args.minimal
PlatformFile.load(THIS_DIR / "macos.json"), args.event
)
if args.config in ("windows", None):
matrix += expand_platform_matrix(
PlatformFile.load(THIS_DIR / "windows.json"), args.minimal
PlatformFile.load(THIS_DIR / "windows.json"), args.event
)
print(f"matrix={json.dumps({'include': [dataclasses.asdict(e) for e in matrix]})}")

View File

@@ -2,30 +2,16 @@
"image_tag": "sha-e29b523",
"configs": {
"ubuntu": [
{
"compiler": ["clang"],
"build_type": ["Release"],
"arch": ["amd64"],
"minimal": true
},
{
"compiler": ["gcc"],
"build_type": ["Release"],
"arch": ["amd64"],
"minimal": false
},
{
"compiler": ["gcc", "clang"],
"build_type": ["Debug", "Release"],
"arch": ["arm64"],
"minimal": false
"arch": ["amd64", "arm64"]
},
{
"compiler": ["gcc", "clang"],
"build_type": ["Debug", "Release"],
"arch": ["amd64"],
"minimal": false,
"sanitizers": ["address", "undefinedbehavior"]
},
@@ -33,7 +19,6 @@
"compiler": ["gcc"],
"build_type": ["Debug"],
"arch": ["amd64"],
"minimal": true,
"suffix": "coverage",
"extra_cmake_args": "-DUNIT_TEST_REFERENCE_FEE=500 -Dcoverage=ON -Dcoverage_format=xml -DCODE_COVERAGE_VERBOSE=ON -DCMAKE_C_FLAGS=-O0 -DCMAKE_CXX_FLAGS=-O0"
},
@@ -41,7 +26,6 @@
"compiler": ["clang"],
"build_type": ["Debug"],
"arch": ["amd64"],
"minimal": false,
"suffix": "voidstar",
"extra_cmake_args": "-Dvoidstar=ON"
},
@@ -49,7 +33,6 @@
"compiler": ["clang"],
"build_type": ["Release"],
"arch": ["amd64"],
"minimal": false,
"suffix": "reffee",
"extra_cmake_args": "-DUNIT_TEST_REFERENCE_FEE=1000"
},
@@ -57,9 +40,9 @@
"compiler": ["gcc"],
"build_type": ["Debug"],
"arch": ["amd64"],
"minimal": false,
"suffix": "unity",
"extra_cmake_args": "-Dunity=ON"
"extra_cmake_args": "-Dunity=ON",
"exclude_event_types": ["pull_request"]
}
],
@@ -67,8 +50,7 @@
{
"compiler": ["gcc"],
"build_type": ["Release"],
"arch": ["amd64"],
"minimal": false
"arch": ["amd64"]
}
],
@@ -76,8 +58,7 @@
{
"compiler": ["gcc"],
"build_type": ["Release"],
"arch": ["amd64"],
"minimal": false
"arch": ["amd64"]
}
]
},
@@ -87,7 +68,6 @@
"compiler": ["gcc"],
"build_type": ["Release"],
"arch": ["amd64"],
"minimal": false,
"image": "ghcr.io/xrplf/xrpld/packaging-debian:sha-577d745"
}
],
@@ -97,7 +77,6 @@
"compiler": ["gcc"],
"build_type": ["Release"],
"arch": ["amd64"],
"minimal": false,
"image": "ghcr.io/xrplf/xrpld/packaging-rhel:sha-577d745"
}
]

View File

@@ -4,14 +4,13 @@
"configs": [
{
"build_type": "Release",
"extra_cmake_args": "-DCMAKE_POLICY_VERSION_MINIMUM=3.5",
"minimal": true
"extra_cmake_args": "-DCMAKE_POLICY_VERSION_MINIMUM=3.5"
},
{
"build_type": "Debug",
"extra_cmake_args": "-DCMAKE_POLICY_VERSION_MINIMUM=3.5",
"build_only": true,
"minimal": false
"exclude_event_types": ["pull_request"]
}
]
}

View File

@@ -2,11 +2,11 @@
"platform": "windows/amd64",
"runner": ["self-hosted", "Windows", "dev-box-windows-2026"],
"configs": [
{ "build_type": "Release", "minimal": true },
{ "build_type": "Release" },
{
"build_type": "Debug",
"build_only": true,
"minimal": false
"exclude_event_types": ["pull_request"]
}
]
}

View File

@@ -14,7 +14,6 @@ permissions:
jobs:
main:
if: ${{ !contains(github.event.pull_request.labels.*.name, 'IgnoreConflicts') }}
runs-on: ubuntu-latest
steps:
- name: Check if PRs are dirty

View File

@@ -1,11 +1,7 @@
# This workflow runs workflows to check, build and test the project
# on every meaningful change on pull_request.
# However, it will not run if the PR is a draft
# unless it has the 'DraftRunCI' or 'Full CI build' label.
#
# By default a PR builds only a minimal matrix.
# The full matrix runs once the PR is labeled "Ready to merge" or "Full CI build".
# For commits to PRs that target a release branch,
# This workflow runs all workflows to check, build and test the project on
# various Linux flavors, as well as on MacOS and Windows, on every push to a
# user branch. However, it will not run if the pull request is a draft unless it
# has the 'DraftRunCI' label. For commits to PRs that target a release branch,
# it also uploads the libxrpl recipe to the Conan remote.
name: PR
@@ -19,24 +15,9 @@ on:
- reopened
- synchronize
- ready_for_review
# Trigger on label changes so toggling "Ready to merge" or "Full CI build"
# switches between the minimal and full matrix without needing a new push.
- labeled
- unlabeled
concurrency:
# Use a per-ref group so a newer run (a push, or a change to a label below)
# supersedes the in-progress one for that ref. Label events we don't act on get
# their own unique group (per run id) instead, keeping them out of the shared
# group so real builds keep running. Keep this list in sync with `should-run`.
group: >-
${{ github.workflow }}-${{ github.ref }}${{
((github.event.action == 'labeled' || github.event.action == 'unlabeled')
&& github.event.label.name != 'Ready to merge'
&& github.event.label.name != 'DraftRunCI'
&& github.event.label.name != 'Full CI build')
&& format('-{0}', github.run_id) || ''
}}
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
defaults:
@@ -45,21 +26,10 @@ defaults:
jobs:
# This job determines whether the rest of the workflow should run. It runs
# when the PR is not a draft (which should also cover merge-group) or has the
# 'DraftRunCI' or 'Full CI build' label. For label events it only runs when the
# label added or removed is one we act on ('Ready to merge', 'DraftRunCI' or
# 'Full CI build'), so unrelated label changes do not trigger a redundant run.
# when the PR is not a draft (which should also cover merge-group) or
# has the 'DraftRunCI' label.
should-run:
if: >-
${{
((github.event.action != 'labeled' && github.event.action != 'unlabeled')
|| github.event.label.name == 'Ready to merge'
|| github.event.label.name == 'DraftRunCI'
|| github.event.label.name == 'Full CI build')
&& (!github.event.pull_request.draft
|| contains(github.event.pull_request.labels.*.name, 'DraftRunCI')
|| contains(github.event.pull_request.labels.*.name, 'Full CI build'))
}}
if: ${{ !github.event.pull_request.draft || contains(github.event.pull_request.labels.*.name, 'DraftRunCI') }}
runs-on: ubuntu-latest
steps:
- name: Checkout repository
@@ -121,17 +91,15 @@ jobs:
# least one of:
# * Any of the files checked in the `changes` step were modified
# * The PR is NOT a draft and is labeled "Ready to merge"
# * The PR is labeled "Full CI build" (draft or not)
# * The workflow is running from the merge queue
id: go
env:
FILES: ${{ steps.changes.outputs.any_changed }}
DRAFT: ${{ github.event.pull_request.draft }}
READY: ${{ contains(github.event.pull_request.labels.*.name, 'Ready to merge') }}
FULL: ${{ contains(github.event.pull_request.labels.*.name, 'Full CI build') }}
MERGE: ${{ github.event_name == 'merge_group' }}
run: |
echo "go=${{ (env.DRAFT != 'true' && env.READY == 'true') || env.FULL == 'true' || env.FILES == 'true' || env.MERGE == 'true' }}" >>"${GITHUB_OUTPUT}"
echo "go=${{ (env.DRAFT != 'true' && env.READY == 'true') || env.FILES == 'true' || env.MERGE == 'true' }}" >>"${GITHUB_OUTPUT}"
cat "${GITHUB_OUTPUT}"
outputs:
go: ${{ steps.go.outputs.go == 'true' }}
@@ -174,10 +142,7 @@ jobs:
package:
needs: [should-run, build-test]
# Packaging consumes the debian/rhel release binaries, which are only built
# by the full matrix. Skip it for pull requests that ran only the minimal
# matrix (i.e. not yet labeled "Ready to merge" or "Full CI build").
if: ${{ needs.should-run.outputs.go == 'true' && (github.event_name != 'pull_request' || contains(github.event.pull_request.labels.*.name, 'Ready to merge') || contains(github.event.pull_request.labels.*.name, 'Full CI build')) }}
if: ${{ needs.should-run.outputs.go == 'true' }}
uses: ./.github/workflows/reusable-package.yml
upload-recipe:

View File

@@ -124,7 +124,7 @@ jobs:
- name: Check tools
env:
CHECK_TOOLS_SKIP_CLONE: "1"
run: ./bin/check-tools.sh || true
run: ./bin/check-tools.sh
- name: Print build environment
uses: XRPLF/actions/print-build-env@59dec886e4afb05a1724443af08baccbc045b574

View File

@@ -35,8 +35,5 @@ jobs:
id: generate
env:
GENERATE_CONFIG: ${{ inputs.os != '' && format('--config={0}', inputs.os) || '' }}
# Run only the minimal matrix for pull requests that are not yet
# labeled "Ready to merge" or "Full CI build". Any other event (merge
# queue, push, schedule, manual dispatch) runs the full matrix.
GENERATE_MINIMAL: ${{ (github.event_name == 'pull_request' && !contains(github.event.pull_request.labels.*.name, 'Ready to merge') && !contains(github.event.pull_request.labels.*.name, 'Full CI build')) && '--minimal' || '' }}
run: ./generate.py ${GENERATE_CONFIG} ${GENERATE_MINIMAL} >>"${GITHUB_OUTPUT}"
GENERATE_EVENT: ${{ github.event_name }}
run: ./generate.py ${GENERATE_CONFIG} --event="${GENERATE_EVENT}" >>"${GITHUB_OUTPUT}"

View File

@@ -32,11 +32,6 @@ repos:
# as standalone translation units, so they have no compile_commands.json
# entry to lint (verify_headers checks them transitively).
exclude: '^include/xrpl/protocol_autogen|\.ipp$'
# run-clang-tidy --fix may edit headers included by files it is not run on,
# so pre-commit must not split the files across parallel hook invocations.
# The script determines the staged files itself and lets run-clang-tidy
# handle parallelism internally.
pass_filenames: false
- id: fix-include-style
name: fix include style
entry: ./bin/pre-commit/fix_include_style.py
@@ -48,11 +43,6 @@ repos:
language: python
entry: ./bin/pre-commit/fix_pragma_once.py
files: \.(h|hpp)$
- id: check-doxygen-style
name: check Doxygen comment style
entry: ./bin/pre-commit/check_doxygen_style.py
language: python
types_or: [c++, c]
- repo: https://github.com/pre-commit/mirrors-clang-format
rev: dd18dad857d6133e90bbe478f4f2f22ec0030269 # frozen: v22.1.5

View File

@@ -28,9 +28,6 @@ This section contains changes targeting a future version.
### Additions
- `account_tx`: Added an optional `delegate` request object to filter delegated transactions. The object requires `delegate_filter`, which must be either `actor` for transactions owned by the requested account but signed by another account, or `authorizer` for transactions signed by the requested account on behalf of another account. The optional `counter_party` account narrows the results to a specific signer/delegate for `actor` or a specific owner/delegator for `authorizer`. Malformed `delegate`, `delegate_filter`, and `counter_party` values return standard invalid field errors, and invalid account IDs return `actMalformed`.
When paginating delegate-filtered queries, a marker from a delegate-filtered query includes a `delegate` flag and is only valid for follow-up requests that also supply `delegate` (mixing marker conventions returns `invalidParams`). Because filtering is applied after the ledger scan, a page may contain fewer results than `limit` (possibly zero) while still returning a marker, so callers must continue until no marker is present.
- `ledger_entry`, `account_objects`: The `Delegate` ledger entry now includes an optional `DestinationNode` field, which stores the index into the authorized account's owner directory. This field is present on entries created after bidirectional directory tracking was introduced and may appear in RPC responses for those entries. ([#6681](https://github.com/XRPLF/rippled/pull/6681))
- `server_definitions`: Added the following new sections to the response ([#6321](https://github.com/XRPLF/rippled/pull/6321)):

View File

@@ -84,9 +84,7 @@ If you create new source files, they must be organized as follows:
- All other non-test files must go under `src/xrpld`.
- All test source files must go under `src/test`.
The source must be formatted according to the style guide below. The easiest
way to satisfy this is to install the [`pre-commit`](#pre-commit-hooks) hooks,
which format and lint your changes automatically on every commit.
The source must be formatted according to the style guide below.
Header includes must be [levelized](.github/scripts/levelization).
@@ -214,61 +212,13 @@ This is a non-exhaustive list of recommended style guidelines. These are
not always strictly enforced and serve as a way to keep the codebase
coherent rather than a set of _thou shalt not_ commandments.
## Pre-commit hooks
We use the [`pre-commit`](https://pre-commit.com/) framework to run the
formatting and linting tools that keep the codebase consistent. `pre-commit`
runs each tool configured in
[`.pre-commit-config.yaml`](./.pre-commit-config.yaml) in its own isolated
environment, so you don't need to install most of the individual tools
yourself. The version of each hook sourced from an external repository
(`clang-format`, `gersemi`, etc.) is pinned in that file, so running the hooks
locally uses exactly the same versions as CI. A few `local` hooks — most notably
`clang-tidy` — run tools from your own environment; see
[Installing clang-tidy](#installing-clang-tidy) for how to get those.
To get started, install `pre-commit` and enable the git hook scripts:
```bash
pip install pre-commit
pre-commit install
```
Once installed, the hooks run automatically on your staged files every time you
`git commit`. You can also run them on demand:
```bash
# Run all hooks against only the staged files
pre-commit run
# Run all hooks against every file in the repository
pre-commit run --all-files
# Run a single hook (e.g. clang-format) against all files
pre-commit run clang-format --all-files
```
The hooks configured in this repository include, among others:
- `clang-format` — C++/proto formatting (see [Formatting](#formatting))
- `clang-tidy` — C++ static analysis (see [Clang-tidy](#clang-tidy)); opt in with `TIDY=1`
- `fix-include-style`, `fix-pragma-once`, `check-doxygen-style` — C++ hygiene
- `gersemi` — CMake formatting
- `prettier`, `black`, `shfmt` — formatting for JavaScript/JSON/Markdown, Python, and shell
- `cspell` — spell checking
The same hooks run in CI on every pull request, so running them locally before
you push helps you avoid CI failures.
## Formatting
All code must conform to `clang-format`, according to the settings in
[`.clang-format`](./.clang-format), unless the result would be unreasonably
difficult to read or maintain. The `clang-format` version is pinned in
[`.pre-commit-config.yaml`](./.pre-commit-config.yaml), so the
[`pre-commit`](#pre-commit-hooks) hook always formats with the same version as
CI. To demarcate lines that should be left as-is, surround them with comments
like this:
All code must conform to `clang-format` version 22,
according to the settings in [`.clang-format`](./.clang-format),
unless the result would be unreasonably difficult to read or maintain.
To demarcate lines that should be left as-is, surround them with comments like
this:
```
// clang-format off
@@ -276,21 +226,9 @@ like this:
// clang-format on
```
The easiest way to format your changes is to let the `pre-commit` hook run
automatically on commit, or to run it manually:
```bash
pre-commit run clang-format --all-files
```
You can also format individual files in place by running `clang-format -i <file>...`
You can format individual files in place by running `clang-format -i <file>...`
from any directory within this project.
> [!NOTE]
> This uses whatever `clang-format` version is installed locally, which may
> differ from the pinned version used by `pre-commit` and CI, so the results
> can vary.
There is a Continuous Integration job that runs clang-format on pull requests. If the code doesn't comply, a patch file that corrects auto-fixable formatting issues is generated.
To download the patch file:
@@ -301,6 +239,13 @@ To download the patch file:
4. Download the zip file and extract it to your local git repository. Run `git apply [patch-file-name]`.
5. Commit and push.
You can install a pre-commit hook to automatically run `clang-format` before every commit:
```
pip3 install pre-commit
pre-commit install
```
## Clang-tidy
All code must pass `clang-tidy` checks according to the settings in [`.clang-tidy`](./.clang-tidy).
@@ -322,7 +267,7 @@ Before running clang-tidy, you must build the project to generate required files
#### Via pre-commit (recommended)
If you have already installed the [`pre-commit`](#pre-commit-hooks) hooks, you can run clang-tidy on your staged files using:
If you have already installed the pre-commit hooks (see above), you can run clang-tidy on your staged files using:
```
TIDY=1 pre-commit run clang-tidy

View File

@@ -110,23 +110,6 @@ if [ "${os}" = "linux" ] || [ "${os}" = "macos" ]; then
fi
fi
# Rust toolchain. Part of the Nix commonPackages, so available on both Linux
# and macOS. The cargo plugins are invoked through cargo (`cargo <sub>`), which
# resolves the matching `cargo-<sub>` binary on PATH; `--version` is offline and
# does not need a Cargo project.
if [ "${os}" = "linux" ] || [ "${os}" = "macos" ]; then
echo
echo "Rust toolchain:"
check cargo
check cargo-audit cargo audit --version
check cargo-llvm-cov cargo llvm-cov --version
check cargo-nextest cargo nextest --version
check clippy clippy-driver --version
check rust-analyzer
check rustc
check rustfmt
fi
# GCC is the default compiler on Linux. macOS uses the system Apple Clang
# instead, so GCC/g++/gcov are not expected there.
if [ "${os}" = "linux" ]; then

View File

@@ -1,440 +0,0 @@
#!/usr/bin/env python3
"""
Check C++ Doxygen comment style.
Enforces the house convention for documentation comments:
* Use ``/** ... */`` blocks, not ``///``, ``//!`` or ``/*! ... */``; a plain
``/* ... */`` that contains Doxygen commands is a doc comment missing its
second star. Trailing member-after comments use ``///<`` (not ``//!<``,
``/*!< ... */`` or ``/**< ... */`` -- the block forms get reflowed and
mis-attached by clang-format on packed enum values, the line form does not).
* ``/**`` sits alone on its line; the closing ``*/`` sits alone on its line.
* Every content line is prefixed with `` * `` (no bare-indented continuation).
* The first content line is flush (not over-indented).
* Doxygen commands use the ``@cmd`` form, not ``\\cmd``.
* Use ``@return`` / ``@throws`` rather than prose ``Returns:`` / ``Throws:``.
* A plain ``//`` comment carrying a block-level ``@command`` (``@param``,
``@return``, ``@see``, ...) is documentation and must be a ``/** ... */``
block (Doxygen ignores ``//``).
* Use canonical command spellings: ``@return`` (not ``@returns``),
``@throws`` (not ``@throw``), ``@see`` (not ``@sa``).
* Order block tags ``@tparam`` -> ``@param`` -> ``@return``. (Whether
``@param`` order matches the signature is not checked here -- too fragile to
parse; Doxygen's WARN_IF_DOC_ERROR covers name mismatches.)
* One-liners are expanded to three lines, EXCEPT bare markers ``@{`` / ``@}``
/ ``@cond [label]`` / ``@endcond`` / ``@file [name]`` which stay on one line.
Left intentionally alone (recognized, valid Doxygen that is not this style's
concern):
* ``///<`` trailing "member-after" comments (the house form).
* Divider lines made only of slashes (``//////////``).
* Plain ``/* ... */`` (non-Doxygen) comments.
Usage:
check_doxygen_style.py [FILE ...] # explicit files
check_doxygen_style.py # default: src/ and include/ trees
Exit status is non-zero if any violation is found.
"""
import argparse
import re
import sys
from collections.abc import Iterable, Iterator
from dataclasses import dataclass
from enum import Enum
from pathlib import Path
class Category(Enum):
"""A kind of style violation: a printed ``label`` and its ``description``.
The description is the default message; a few categories whose wording
depends on the offending text (see ``Finding.detail``) override it.
"""
def __init__(self, label: str, description: str) -> None:
self.label = label
self.description = description
BACKSLASH_COMMAND = ("backslash-command", "use the @cmd form, not \\cmd")
WRONG_COMMAND = ("wrong-command", "use the canonical command spelling")
TRIPLE_SLASH = ("triple-slash", "use a /** ... */ block instead of ///")
QT_MEMBER = ("qt-member", "use ///< instead of //!<")
QT_LINE = ("qt-line", "use a /** ... */ block instead of //!")
BLOCK_MEMBER = ("block-member", "use ///< instead of /**<")
QT_BLOCK_MEMBER = ("qt-block-member", "use ///< instead of /*!<")
DOC_IN_LINE_COMMENT = (
"doc-in-line-comment",
"use a /** ... */ block for documentation, not //",
)
QT_COMMENT = ("qt-comment", "use /** instead of /*!")
SINGLE_LINE_BLOCK = (
"single-line-block",
"expand one-line /** ... */ to a multi-line block "
"(markers @{ @} @cond @endcond @file may stay)",
)
TEXT_ON_OPENER = ("text-on-opener", "move text off the /** opener line")
BARE_CONTINUATION = ("bare-continuation", 'prefix continuation lines with " * "')
OVER_INDENTED = ("over-indented", "first content line is over-indented")
OVER_INDENTED_TAG = (
"over-indented-tag",
'Doxygen tag over-indented; use a single space after "*"',
)
COMBINED_MARKER = (
"combined-marker",
"scope marker @{ / @} should be its own single-line /** @{ */ block",
)
PROSE_LABEL = ("prose-label", "use a Doxygen tag instead of a prose label")
CONTENT_ON_CLOSER = ("content-on-closer", "move content off the closing */ line")
PLAIN_BLOCK_DOC = (
"plain-block-doc",
"documentation comment must open with /** not /*",
)
TAG_ORDER = (
"tag-order",
"block tags out of order; expected @tparam, then @param, then @return",
)
@dataclass(frozen=True)
class Finding:
"""A single style violation at a 1-based line number.
``detail`` overrides the category's default description when the message
depends on the offending text (e.g. which command was misspelled).
"""
line: int
category: Category
detail: str | None = None
@property
def message(self) -> str:
return self.detail if self.detail is not None else self.category.description
DEFAULT_ROOTS = ("src", "include")
EXTS = {".h", ".hpp", ".cpp", ".ipp", ".cxx", ".cc"}
# Every Doxygen command we recognize when written with a backslash (\cmd).
_ALL_COMMANDS = (
"brief|param|tparam|return|returns|retval|note|warning|pre|post|see|sa|ref|"
"throw|throws|exception|deprecated|details|code|endcode|verbatim|endverbatim|"
"li|arg|c|internal|since|todo|attention|remark|remarks|ingroup|defgroup"
)
# Block-level tags whose over-indentation we flag inside a block body.
_BLOCK_TAGS = (
"param|tparam|returns?|retval|brief|throws?|note|warning|"
"pre|post|see|sa|details|deprecated"
)
# Tags that, appearing anywhere in a comment, mark it as documentation.
_ANY_DOC_TAGS = (
"param|tparam|returns?|retval|brief|throws?|note|warning|pre|post|see|sa"
)
# Tags that make a plain // comment a mis-styled doc comment.
_LINE_DOC_TAGS = "brief|param|tparam|returns?|retval|throws?|note|see|pre|post"
# \cmd that should be @cmd.
RE_BACKSLASH_CMD = re.compile(r"\\(" + _ALL_COMMANDS + r")\b")
# Bare markers that may legitimately stay on a single line.
RE_MARKER = re.compile(r"^@(\{|\}|cond(\s.*)?|endcond|file(\s.*)?)$")
# Prose section labels that should be Doxygen tags.
RE_PROSE_LABEL = re.compile(r"^\*\s(Returns|Throws|Exceptions):\s*$")
# An over-indented block tag: "*" followed by 2+ spaces then the tag.
RE_OVERINDENTED_TAG = re.compile(r"^\*\s{2,}@(" + _BLOCK_TAGS + r")\b")
# Any documentation tag (used to spot a doc comment hiding in a plain /* */).
RE_ANY_DOC_TAG = re.compile(r"@(" + _ANY_DOC_TAGS + r")\b")
# A documentation tag inside a // comment.
RE_LINE_DOC_TAG = re.compile(r"@(" + _LINE_DOC_TAGS + r")\b")
# Order-relevant tags, for the @tparam -> @param -> @return ordering check.
RE_ORDER_TAG = re.compile(r"^\*\s*@(param|tparam|returns?|retval)\b")
# First content line indented by 2+ spaces after the "*".
RE_FIRST_OVERINDENT = re.compile(r"^\s*\*\s{2,}\S")
# A scope marker @{ / @} sharing a comment with other text.
RE_COMBINED_MARKER = re.compile(r"^\*\s*@[{}]\s*$")
# Non-canonical command spellings -> the house spelling (bare command names).
# Used both to flag a wrong @form and to suggest the right @form for a \wrong.
CANONICAL_COMMAND = {"returns": "return", "throw": "throws", "sa": "see"}
WRONG_SPELLINGS = [
(re.compile(rf"@{wrong}\b"), f"@{right}")
for wrong, right in CANONICAL_COMMAND.items()
]
# Order block tags should appear in; a body out of this order is a violation.
EXPECTED_TAG_ORDER = ("tparam", "param", "return")
def is_doxy_open(stripped: str) -> bool:
"""True for a line-start Doxygen block opener we should normalize."""
if stripped.startswith("/*!"): # Qt-style Doxygen
return not stripped.startswith("/*!<") # member-after, leave inline
return (
stripped.startswith("/**")
and not stripped.startswith("/***")
and not stripped.startswith("/**/")
and not stripped.startswith("/**<")
)
def _flag_commands(raw_line: str, stripped: str, index: int) -> list[Finding]:
"""Flag \\cmd and misspelled @cmd on a comment line (opener, body, or closer)."""
if not stripped.startswith(("*", "//", "/*")):
return []
findings: list[Finding] = []
backslash = RE_BACKSLASH_CMD.search(raw_line)
if backslash:
command = backslash.group(1)
canonical = CANONICAL_COMMAND.get(command, command)
findings.append(
Finding(
index + 1,
Category.BACKSLASH_COMMAND,
f"use @{canonical} instead of \\{command}",
)
)
for pattern, replacement in WRONG_SPELLINGS:
wrong = pattern.search(raw_line)
if wrong:
findings.append(
Finding(
index + 1,
Category.WRONG_COMMAND,
f"use {replacement} instead of {wrong.group(0)}",
)
)
return findings
def _flag_line_comment(raw_line: str, stripped: str, index: int) -> Finding | None:
"""Return the finding for a single-line comment form (///, //!, /**<, ...), else None."""
if stripped.startswith("///") and not stripped.startswith(("////", "///<")):
return Finding(index + 1, Category.TRIPLE_SLASH)
if "//!<" in raw_line:
return Finding(index + 1, Category.QT_MEMBER)
if stripped.startswith("//!"):
return Finding(index + 1, Category.QT_LINE)
if "/**<" in raw_line:
return Finding(index + 1, Category.BLOCK_MEMBER)
if "/*!<" in raw_line:
return Finding(index + 1, Category.QT_BLOCK_MEMBER)
if stripped.startswith("//") and RE_LINE_DOC_TAG.search(stripped):
return Finding(index + 1, Category.DOC_IN_LINE_COMMENT)
return None
def _flag_single_line_block(stripped: str, line_no: int, is_qt: bool) -> list[Finding]:
"""Findings for a whole /** ... */ or /*! ... */ block on one line."""
inner = re.sub(r"^/\*[*!]", "", stripped)
inner = re.sub(r"\*/\s*$", "", inner).strip()
findings: list[Finding] = []
if is_qt:
findings.append(Finding(line_no, Category.QT_COMMENT))
if inner and not RE_MARKER.match(inner):
findings.append(Finding(line_no, Category.SINGLE_LINE_BLOCK))
return findings
def _canonical_order_tag(body: str) -> str | None:
"""The order-relevant tag (tparam/param/return) a body line opens with, if any."""
match = RE_ORDER_TAG.match(body)
if match is None:
return None
command = match.group(1)
return "return" if command in ("return", "returns", "retval") else command
def _flag_body_line(
body_line: str, line_no: int, is_first_content: bool
) -> list[Finding]:
"""Findings for one interior line of a multi-line block."""
body = body_line.strip()
findings: list[Finding] = []
if body and not body.startswith("*"):
findings.append(Finding(line_no, Category.BARE_CONTINUATION))
if body.startswith("*"):
if is_first_content and RE_FIRST_OVERINDENT.match(body_line):
findings.append(Finding(line_no, Category.OVER_INDENTED))
if RE_OVERINDENTED_TAG.match(body):
findings.append(Finding(line_no, Category.OVER_INDENTED_TAG))
if RE_COMBINED_MARKER.match(body):
findings.append(Finding(line_no, Category.COMBINED_MARKER))
label = RE_PROSE_LABEL.match(body)
if label:
suggested_tag = "@return" if label.group(1) == "Returns" else "@throws"
findings.append(
Finding(
line_no,
Category.PROSE_LABEL,
f'use {suggested_tag} instead of prose "{label.group(1)}:"',
)
)
return findings
def _flag_closer(closer_line: str, line_no: int) -> list[Finding]:
"""Findings for content sharing the closing */ line."""
before = closer_line[: closer_line.index("*/")].strip()
if before and before != "*":
return [Finding(line_no, Category.CONTENT_ON_CLOSER)]
return []
def _flag_tag_order(first_tag_line: dict[str, int]) -> list[Finding]:
"""One finding if the present block tags are not in EXPECTED_TAG_ORDER."""
tag_lines = [
first_tag_line[tag] for tag in EXPECTED_TAG_ORDER if tag in first_tag_line
]
if tag_lines != sorted(tag_lines):
return [Finding(min(tag_lines), Category.TAG_ORDER)]
return []
def _flag_doxy_block(lines: list[str], start: int) -> tuple[int, list[Finding]]:
"""Handle a /** or /*! block opening at ``start``; return (next index, findings)."""
raw_line = lines[start]
stripped = raw_line.lstrip()
open_pos = raw_line.index("/*")
is_qt = stripped.startswith("/*!")
# A whole block on one line: /** ... */.
if "*/" in raw_line[open_pos + 2 :]:
return start + 1, _flag_single_line_block(stripped, start + 1, is_qt)
# Multi-line block: opener, then scan the body to the closer.
findings: list[Finding] = []
if is_qt:
findings.append(Finding(start + 1, Category.QT_COMMENT))
if raw_line[open_pos + 3 :].strip():
findings.append(Finding(start + 1, Category.TEXT_ON_OPENER))
line_count = len(lines)
cursor = start + 1
is_first_content = True
first_tag_line: dict[str, int] = {} # canonical tag -> 1-based first line
while cursor < line_count and "*/" not in lines[cursor]:
body_line = lines[cursor]
body = body_line.strip()
findings.extend(_flag_commands(body_line, body, cursor))
tag = _canonical_order_tag(body)
if tag is not None:
first_tag_line.setdefault(tag, cursor + 1)
findings.extend(_flag_body_line(body_line, cursor + 1, is_first_content))
if body.startswith("*"):
is_first_content = False
cursor += 1
if cursor < line_count:
closer_line = lines[cursor]
findings.extend(_flag_commands(closer_line, closer_line.strip(), cursor))
findings.extend(_flag_closer(closer_line, cursor + 1))
findings.extend(_flag_tag_order(first_tag_line))
return cursor + 1, findings
def _flag_plain_block(lines: list[str], start: int) -> tuple[int, list[Finding]]:
"""Handle a line-start plain /* ... */ block; return (next index, findings).
Only flagged when it hides a documentation command (a missing second star).
"""
line_count = len(lines)
cursor = start
while cursor < line_count and "*/" not in lines[cursor]:
cursor += 1
findings: list[Finding] = []
# The opener (start) is command-checked by check_file; check the rest here.
for i in range(start + 1, min(cursor + 1, line_count)):
findings.extend(_flag_commands(lines[i], lines[i].strip(), i))
block_text = "\n".join(
lines[start : cursor + 1] if cursor < line_count else lines[start:]
)
if RE_ANY_DOC_TAG.search(block_text):
findings.append(Finding(start + 1, Category.PLAIN_BLOCK_DOC))
next_index = cursor + 1 if cursor < line_count else line_count
return next_index, findings
def check_source(text: str) -> list[Finding]:
"""Return all style violations found in the given source text."""
lines = text.split("\n")
findings: list[Finding] = []
line_count = len(lines)
index = 0
in_plain_block = False # inside a mid-line, non-Doxygen /* ... */
while index < line_count:
raw_line = lines[index]
stripped = raw_line.lstrip()
# Skip the interior of a plain block opened on an earlier line.
if in_plain_block:
in_plain_block = "*/" not in raw_line
index += 1
continue
findings.extend(_flag_commands(raw_line, stripped, index))
line_finding = _flag_line_comment(raw_line, stripped, index)
if line_finding is not None:
findings.append(line_finding)
index += 1
elif is_doxy_open(stripped):
index, block_findings = _flag_doxy_block(lines, index)
findings.extend(block_findings)
elif stripped.startswith("/*"):
index, block_findings = _flag_plain_block(lines, index)
findings.extend(block_findings)
else:
# A /* that opens mid-line without closing starts a plain block.
if "/*" in raw_line and not stripped.startswith("//"):
if "*/" not in raw_line[raw_line.index("/*") + 2 :]:
in_plain_block = True
index += 1
return findings
def check_file(path: Path) -> list[Finding]:
"""Return all style violations found in one file."""
return check_source(path.read_text(encoding="utf-8"))
def iter_files(paths: Iterable[str]) -> Iterator[Path]:
"""Yield every C++ source file among the given files and directories."""
for raw_path in paths:
path = Path(raw_path)
if path.is_dir():
for candidate in path.rglob("*"):
if candidate.is_file() and candidate.suffix in EXTS:
yield candidate
elif path.suffix in EXTS:
yield path
def main() -> int:
parser = argparse.ArgumentParser(description="Check Doxygen comment style.")
parser.add_argument(
"files", nargs="*", help="files or directories (default: src/ include/)"
)
parser.add_argument(
"-q", "--quiet", action="store_true", help="only print the summary count"
)
args = parser.parse_args()
roots = args.files or [root for root in DEFAULT_ROOTS if Path(root).is_dir()]
total = 0
for path in sorted(set(iter_files(roots)), key=str):
for finding in check_file(path):
total += 1
if not args.quiet:
print(
f"{path}:{finding.line}: {finding.category.label}: {finding.message}"
)
print(f"\n{total} doxygen-style violation(s)", file=sys.stderr)
return 1 if total else 0
if __name__ == "__main__":
sys.exit(main())

View File

@@ -1,46 +1,27 @@
#!/usr/bin/env python3
"""Pre-commit hook that runs clang-tidy on staged files using run-clang-tidy.
"""Pre-commit hook that runs clang-tidy on changed files using run-clang-tidy.
The script determines the staged files itself (see `pass_filenames: false` in
.pre-commit-config.yaml) so run-clang-tidy is run once and handles parallelism
internally: pre-commit would otherwise split the files across parallel hook
invocations that race when fixes edit a shared header.
Fixes are collected with `-export-fixes` and applied by clang-apply-replacements
in a separate step rather than with run-clang-tidy's `-fix`. The `add_module`
build isolates each module's headers behind a per-module symlink directory
(build/modules/<module>/...), so a header reachable from several translation
units is referenced through different paths that all resolve to the same source
file. clang-apply-replacements deduplicates identical replacements by their
literal path, so those paths must be canonicalised to the real source path
first; otherwise the same fix is applied once per path and corrupts the header.
The set of files is chosen by pre-commit (see .pre-commit-config.yaml), which
filters to C/C++ sources and excludes `.ipp` fragments. Headers are linted
directly: the `verify_headers` build option (ON by default) compiles every
`.h`/`.hpp` on its own, so each header is the main file of its own
compile_commands.json entry and run-clang-tidy can analyse it just like a
`.cpp`.
"""
from __future__ import annotations
import os
import re
import shutil
import subprocess
import sys
import tempfile
from pathlib import Path
CLANG_TIDY_VERSION = 22
# Extensions run-clang-tidy can analyse: `.cpp` translation units and, thanks to
# the `verify_headers` build option, `.h`/`.hpp` headers (each has its own
# compile_commands.json entry). `.ipp` fragments have no entry and are skipped.
TIDY_EXTENSIONS = {".cpp", ".h", ".hpp"}
# A single-quoted `FilePath:` entry in an -export-fixes YAML file, allowing the
# `- ` marker that precedes it inside a `Replacements:` sequence. clang-tidy
# emits paths single-quoted and doubles any embedded quote per YAML rules.
FILEPATH_RE = re.compile(r"^(\s*(?:-\s+)?FilePath:\s*)'((?:[^']|'')*)'\s*$")
def find_tool(name: str) -> str | None:
for candidate in (f"{name}-{CLANG_TIDY_VERSION}", name):
def find_run_clang_tidy() -> str | None:
for candidate in (f"run-clang-tidy-{CLANG_TIDY_VERSION}", "run-clang-tidy"):
if path := shutil.which(candidate):
return path
return None
@@ -54,43 +35,23 @@ def find_build_dir(repo_root: Path) -> Path | None:
return None
def staged_files(repo_root: Path) -> list[Path]:
"""Return absolute paths of staged, lint-able C/C++ files.
`--diff-filter=d` excludes deletions so we never lint a removed file.
"""
output = subprocess.check_output(
["git", "diff", "--staged", "--name-only", "--diff-filter=d", "--"]
+ [f"*{ext}" for ext in TIDY_EXTENSIONS],
text=True,
cwd=repo_root,
)
return [repo_root / rel for rel in output.splitlines() if rel]
def canonicalize_fix_paths(fixes_dir: Path) -> None:
"""Rewrite every `FilePath` in the exported fixes to its real source path.
A header included through a module's isolation symlink is recorded under that
symlink's path; collapsing all paths to the same real file lets
clang-apply-replacements recognise the per-translation-unit duplicates and
apply each fix once.
"""
for yaml in fixes_dir.glob("*.yaml"):
lines = []
for line in yaml.read_text().splitlines():
if m := FILEPATH_RE.match(line):
path = m.group(2).replace("''", "'")
real = os.path.realpath(path).replace("'", "''")
line = f"{m.group(1)}'{real}'"
lines.append(line)
yaml.write_text("\n".join(lines) + "\n")
def main():
if not os.environ.get("TIDY"):
return 0
files = sys.argv[1:]
if not files:
return 0
run_clang_tidy = find_run_clang_tidy()
if not run_clang_tidy:
print(
f"clang-tidy check failed: TIDY is enabled but neither "
f"'run-clang-tidy-{CLANG_TIDY_VERSION}' nor 'run-clang-tidy' was found in PATH.",
file=sys.stderr,
)
return 1
repo_root = Path(
subprocess.check_output(
["git", "rev-parse", "--show-toplevel"],
@@ -98,29 +59,6 @@ def main():
text=True,
).strip()
)
files = staged_files(repo_root)
if not files:
return 0
run_clang_tidy = find_tool("run-clang-tidy")
clang_apply_replacements = find_tool("clang-apply-replacements")
missing = [
name
for name, path in (
("run-clang-tidy", run_clang_tidy),
("clang-apply-replacements", clang_apply_replacements),
)
if not path
]
if missing:
print(
f"clang-tidy check failed: TIDY is enabled but {' and '.join(missing)} "
f"was not found in PATH (tried the '-{CLANG_TIDY_VERSION}' suffix too).",
file=sys.stderr,
)
return 1
build_dir = find_build_dir(repo_root)
if not build_dir:
print(
@@ -130,23 +68,11 @@ def main():
)
return 1
with tempfile.TemporaryDirectory() as fixes_dir:
result = subprocess.run(
[
run_clang_tidy,
"-quiet",
"-p",
build_dir,
"-export-fixes",
fixes_dir,
"-allow-no-checks",
]
+ files
)
canonicalize_fix_paths(Path(fixes_dir))
applied = subprocess.run([clang_apply_replacements, fixes_dir])
return result.returncode or applied.returncode
result = subprocess.run(
[run_clang_tidy, "-quiet", "-p", str(build_dir), "-fix", "-allow-no-checks"]
+ files
)
return result.returncode
if __name__ == "__main__":

View File

@@ -1,406 +0,0 @@
#!/usr/bin/env python3
"""
Tests for check_doxygen_style.py.
Run directly (no test framework needed):
./bin/pre-commit/test_check_doxygen_style.py
or under pytest:
pytest bin/pre-commit/test_check_doxygen_style.py
"""
import sys
import textwrap
from check_doxygen_style import Finding, check_source
def findings_for(text: str) -> list[Finding]:
"""Return the style violations for the given source text.
The text is dedented and its leading newline stripped, so fixtures can be
written as indented triple-quoted here-docs while keeping honest 1-based
line numbers.
"""
text = textwrap.dedent(text).lstrip("\n")
return check_source(text)
def labels_for(text: str) -> list[str]:
return [f.category.label for f in findings_for(text)]
def messages_for(text: str) -> list[str]:
return [f.message for f in findings_for(text)]
# --- well-formed input produces nothing -------------------------------------
def test_clean_block_ok() -> None:
code = """
/**
* Brief.
*
* @tparam T a type
* @param x the x
* @return the result
*/
"""
assert findings_for(code) == []
def test_blank_lines_inside_block_ok() -> None:
code = """
/**
* a
*
* b
*/
"""
assert findings_for(code) == []
def test_member_and_divider_allowed() -> None:
assert findings_for("int x; ///< ok member\n") == []
assert findings_for("//////////\n") == []
assert findings_for("//// text\n") == []
# --- line-comment forms ------------------------------------------------------
def test_triple_slash() -> None:
code = "/// doc\n"
assert labels_for(code) == ["triple-slash"]
def test_qt_line() -> None:
code = "//! doc\n"
assert labels_for(code) == ["qt-line"]
def test_qt_member() -> None:
code = "int x; //!< doc\n"
assert labels_for(code) == ["qt-member"]
def test_block_member() -> None:
code = "int x; /**< doc */\n"
assert labels_for(code) == ["block-member"]
def test_qt_block_member() -> None:
code = "int x; /*!< doc */\n"
assert labels_for(code) == ["qt-block-member"]
def test_doc_in_line_comment() -> None:
code = "// @param x\n"
assert labels_for(code) == ["doc-in-line-comment"]
# --- block forms -------------------------------------------------------------
def test_qt_comment() -> None:
code = """
/*!
* brief
*/
"""
assert labels_for(code) == ["qt-comment"]
def test_qt_comment_single_line() -> None:
# /*! ... */ on one line -> qt-comment (plus single-line-block)
code = "/*! brief */\n"
assert labels_for(code) == ["qt-comment", "single-line-block"]
def test_single_line_block() -> None:
code = "/** brief */\n"
assert labels_for(code) == ["single-line-block"]
def test_single_line_markers_allowed() -> None:
for marker in ("@{", "@}", "@cond LABEL", "@endcond", "@file foo.h"):
code = f"/** {marker} */\n"
assert findings_for(code) == [], marker
def test_text_on_opener() -> None:
code = """
/** text here
* more
*/
"""
assert labels_for(code) == ["text-on-opener"]
def test_bare_continuation() -> None:
code = """
/**
* a
bare line
*/
"""
assert labels_for(code) == ["bare-continuation"]
def test_over_indented_first_line() -> None:
code = """
/**
* over
*/
"""
assert labels_for(code) == ["over-indented"]
def test_over_indented_tag() -> None:
# a flush first line consumes "first content", isolating the tag check
code = """
/**
* brief
* @param x
*/
"""
assert labels_for(code) == ["over-indented-tag"]
def test_combined_marker() -> None:
code = """
/**
* @{
*/
"""
assert labels_for(code) == ["combined-marker"]
def test_prose_label() -> None:
for word in ("Returns", "Throws", "Exceptions"):
code = f"""
/**
* {word}:
*/
"""
assert labels_for(code) == ["prose-label"], word
def test_content_on_closer() -> None:
code = """
/**
* a
* b */
"""
assert labels_for(code) == ["content-on-closer"]
def test_plain_block_doc() -> None:
assert labels_for("/* @param x */\n") == ["plain-block-doc"]
assert findings_for("/* just an ordinary note */\n") == []
def test_tag_order() -> None:
out_of_order = """
/**
* @param x
* @tparam T
*/
"""
assert labels_for(out_of_order) == ["tag-order"]
correct = """
/**
* @tparam T
* @param x
* @return r
*/
"""
assert findings_for(correct) == []
single = """
/**
* @param x
*/
"""
assert findings_for(single) == [] # single tag: never out of order
# --- command spelling (must work on body/closer lines, not just the opener) --
def test_backslash_command_on_body_line() -> None:
code = r"""
/**
* \brief x
*/
"""
assert labels_for(code) == ["backslash-command"]
def test_backslash_command_suggests_canonical_spelling() -> None:
# a backslash + non-canonical spelling is fixed in one pass, not two:
# \sa -> @see (not @sa), \returns -> @return (not @returns)
sa = r"""
/**
* \sa other
*/
"""
assert messages_for(sa) == [r"use @see instead of \sa"]
returns = r"""
/**
* \returns x
*/
"""
assert messages_for(returns) == [r"use @return instead of \returns"]
def test_wrong_command_on_body_line() -> None:
code = """
/**
* @returns x
*/
"""
assert labels_for(code) == ["wrong-command"]
def test_body_line_commands_regression() -> None:
# regression: these live on body lines of a multi-line block
code = r"""
/**
* @returns bad
* @throw ex
* @sa other
* \param y
*/
"""
assert labels_for(code) == [
"wrong-command",
"wrong-command",
"wrong-command",
"backslash-command",
]
def test_command_on_closer_line() -> None:
code = """
/**
* a
* @sa b */
"""
assert labels_for(code) == ["wrong-command", "content-on-closer"]
def test_no_double_count_across_opener_body_closer() -> None:
code = """
/** @returns opener
* @throw body
* @sa closer */
"""
assert labels_for(code).count("wrong-command") == 3
def test_code_with_word_allowed() -> None:
# @code{.cpp} is valid Doxygen and must not be flagged
code = """
/**
* @code{.cpp}
* int x;
* @endcode
*/
"""
assert findings_for(code) == []
# --- rendered message text ---------------------------------------------------
def test_message_uses_category_description() -> None:
# a static category renders its default description
code = "/// doc\n"
assert messages_for(code) == ["use a /** ... */ block instead of ///"]
def test_message_detail_overrides() -> None:
# dynamic categories render the offending text via Finding.detail
backslash = r"""
/**
* \param y
*/
"""
assert messages_for(backslash) == [r"use @param instead of \param"]
wrong = """
/**
* @returns x
*/
"""
assert messages_for(wrong) == ["use @return instead of @returns"]
prose = """
/**
* Throws:
*/
"""
assert messages_for(prose) == ['use @throws instead of prose "Throws:"']
# --- robustness --------------------------------------------------------------
def test_empty_file_no_crash() -> None:
assert findings_for("") == []
def test_mid_line_plain_block_skipped() -> None:
# a /* opened mid-line (after code) and spanning lines is skipped, so its
# comment-like contents are not analyzed
code = """
int x = 0; /* note: @returns is not a real tag here
* @param also not real
*/
int y = 0;
"""
assert findings_for(code) == []
def test_unclosed_block_scanned_to_eof() -> None:
# an unterminated /** block is still scanned to EOF (no crash, body checked)
code = """
/**
* @returns x
"""
assert labels_for(code) == ["wrong-command"]
def test_banner_and_empty_comment_not_flagged() -> None:
code = """
/***
* banner
***/
"""
assert findings_for(code) == []
assert findings_for("/**/\n") == []
def main() -> int:
tests = sorted(
(name, fn)
for name, fn in globals().items()
if name.startswith("test_") and callable(fn)
)
failed = 0
for name, fn in tests:
try:
fn()
print(f"PASS {name}")
except AssertionError as exc:
failed += 1
print(f"FAIL {name}: {exc!r}")
print(f"\n{len(tests) - failed}/{len(tests)} passed")
return 1 if failed else 0
if __name__ == "__main__":
sys.exit(main())

View File

@@ -177,9 +177,7 @@ ${field['typeData']['setter_type']} ${field['paramName']}${',' if i < len(requir
object_ = *sle;
}
/**
* @brief Ledger entry-specific field setters
*/
/** @brief Ledger entry-specific field setters */
% for field in fields:
/**

View File

@@ -185,9 +185,7 @@ public:
object_ = *tx;
}
/**
* @brief Transaction-specific field setters
*/
/** @brief Transaction-specific field setters */
% for field in fields:
/**

View File

@@ -4,14 +4,13 @@
namespace xrpl {
/**
* Extract a tar archive compressed with lz4
*
* @param src the path of the archive to be extracted
* @param dst the directory to extract to
*
* @throws runtime_error
*/
/** Extract a tar archive compressed with lz4
@param src the path of the archive to be extracted
@param dst the directory to extract to
@throws runtime_error
*/
void
extractTarLz4(boost::filesystem::path const& src, boost::filesystem::path const& dst);

View File

@@ -4,10 +4,9 @@
namespace xrpl {
/**
* Storage for linear binary data.
* Blocks of binary data appear often in various idioms and structures.
*/
/** Storage for linear binary data.
Blocks of binary data appear often in various idioms and structures.
*/
using Blob = std::vector<unsigned char>;
} // namespace xrpl

View File

@@ -10,10 +10,9 @@
namespace xrpl {
/**
* Like std::vector<char> but better.
* Meets the requirements of BufferFactory.
*/
/** Like std::vector<char> but better.
Meets the requirements of BufferFactory.
*/
class Buffer
{
private:
@@ -25,37 +24,30 @@ public:
Buffer() = default;
/**
* Create an uninitialized buffer with the given size.
*/
/** Create an uninitialized buffer with the given size. */
explicit Buffer(std::size_t size)
: p_((size != 0u) ? new std::uint8_t[size] : nullptr), size_(size)
{
}
/**
* Create a buffer as a copy of existing memory.
*
* @param data a pointer to the existing memory. If
* size is non-zero, it must not be null.
* @param size size of the existing memory block.
*/
/** Create a buffer as a copy of existing memory.
@param data a pointer to the existing memory. If
size is non-zero, it must not be null.
@param size size of the existing memory block.
*/
Buffer(void const* data, std::size_t size) : Buffer(size)
{
if (size != 0u)
std::memcpy(p_.get(), data, size);
}
/**
* Copy-construct
*/
/** Copy-construct */
Buffer(Buffer const& other) : Buffer(other.p_.get(), other.size_)
{
}
/**
* Copy assign
*/
/** Copy assign */
Buffer&
operator=(Buffer const& other)
{
@@ -67,19 +59,17 @@ public:
return *this;
}
/**
* Move-construct.
* The other buffer is reset.
*/
/** Move-construct.
The other buffer is reset.
*/
Buffer(Buffer&& other) noexcept : p_(std::move(other.p_)), size_(other.size_)
{
other.size_ = 0;
}
/**
* Move-assign.
* The other buffer is reset.
*/
/** Move-assign.
The other buffer is reset.
*/
Buffer&
operator=(Buffer&& other) noexcept
{
@@ -92,16 +82,12 @@ public:
return *this;
}
/**
* Construct from a slice
*/
/** Construct from a slice */
explicit Buffer(Slice s) : Buffer(s.data(), s.size())
{
}
/**
* Assign from slice
*/
/** Assign from slice */
Buffer&
operator=(Slice s)
{
@@ -115,9 +101,7 @@ public:
return *this;
}
/**
* Returns the number of bytes in the buffer.
*/
/** Returns the number of bytes in the buffer. */
[[nodiscard]] std::size_t
size() const noexcept
{
@@ -137,11 +121,10 @@ public:
return Slice{p_.get(), size_};
}
/**
* Return a pointer to beginning of the storage.
* @note The return type is guaranteed to be a pointer
* to a single byte, to facilitate pointer arithmetic.
*/
/** Return a pointer to beginning of the storage.
@note The return type is guaranteed to be a pointer
to a single byte, to facilitate pointer arithmetic.
*/
/** @{ */
[[nodiscard]] std::uint8_t const*
data() const noexcept
@@ -156,10 +139,9 @@ public:
}
/** @} */
/**
* Reset the buffer.
* All memory is deallocated. The resulting size is 0.
*/
/** Reset the buffer.
All memory is deallocated. The resulting size is 0.
*/
void
clear() noexcept
{
@@ -167,10 +149,9 @@ public:
size_ = 0;
}
/**
* Reallocate the storage.
* Existing data, if any, is discarded.
*/
/** Reallocate the storage.
Existing data, if any, is discarded.
*/
std::uint8_t*
alloc(std::size_t n)
{

View File

@@ -12,8 +12,7 @@
namespace xrpl::compression_algorithms {
/**
* LZ4 block compression.
/** LZ4 block compression.
* @tparam BufferFactory Callable object or lambda.
* Takes the requested buffer size and returns allocated buffer pointer.
* @param in Data to compress
@@ -81,8 +80,7 @@ lz4Decompress(
return decompressedSize;
}
/**
* LZ4 block decompression.
/** LZ4 block decompression.
* @tparam InputStream ZeroCopyInputStream
* @param in Input source stream
* @param inSize Size of compressed data

View File

@@ -9,9 +9,7 @@
namespace xrpl {
/**
* Manages all counted object types.
*/
/** Manages all counted object types. */
class CountedObjects
{
public:
@@ -25,11 +23,10 @@ public:
getCounts(int minimumThreshold) const;
public:
/**
* Implementation for @ref CountedObject.
*
* @internal
*/
/** Implementation for @ref CountedObject.
@internal
*/
class Counter
{
public:
@@ -97,14 +94,13 @@ private:
//------------------------------------------------------------------------------
/**
* Tracks the number of instances of an object.
*
* Derived classes have their instances counted automatically. This is used
* for reporting purposes.
*
* @ingroup basics
*/
/** Tracks the number of instances of an object.
Derived classes have their instances counted automatically. This is used
for reporting purposes.
@ingroup basics
*/
template <class Object>
class CountedObject
{

View File

@@ -6,10 +6,9 @@
namespace xrpl {
/**
* Sampling function using exponential decay to provide a continuous value.
* @tparam The number of seconds in the decay window.
*/
/** Sampling function using exponential decay to provide a continuous value.
@tparam The number of seconds in the decay window.
*/
template <int Window, typename Clock>
class DecayingSample
{
@@ -20,16 +19,15 @@ public:
DecayingSample() = delete;
/**
* @param now Start time of DecayingSample.
*/
@param now Start time of DecayingSample.
*/
explicit DecayingSample(time_point now) : value_(value_type()), when_(now)
{
}
/**
* Add a new sample.
* The value is first aged according to the specified time.
*/
/** Add a new sample.
The value is first aged according to the specified time.
*/
value_type
add(value_type value, time_point now)
{
@@ -38,10 +36,9 @@ public:
return value_ / Window;
}
/**
* Retrieve the current value in normalized units.
* The samples are first aged according to the specified time.
*/
/** Retrieve the current value in normalized units.
The samples are first aged according to the specified time.
*/
value_type
value(time_point now)
{
@@ -90,10 +87,9 @@ private:
//------------------------------------------------------------------------------
/**
* Sampling function using exponential decay to provide a continuous value.
* @tparam HalfLife The half life of a sample, in seconds.
*/
/** Sampling function using exponential decay to provide a continuous value.
@tparam HalfLife The half life of a sample, in seconds.
*/
template <int HalfLife, class Clock>
class DecayWindow
{

View File

@@ -10,37 +10,33 @@ namespace xrpl {
//------------------------------------------------------------------------------
/**
* Tag to create an intrusive pointer from another intrusive pointer by using a
* static cast. This is useful to create an intrusive pointer to a derived
* class from an intrusive pointer to a base class.
*/
/** Tag to create an intrusive pointer from another intrusive pointer by using a
static cast. This is useful to create an intrusive pointer to a derived
class from an intrusive pointer to a base class.
*/
struct StaticCastTagSharedIntrusive
{
};
/**
* Tag to create an intrusive pointer from another intrusive pointer by using a
* dynamic cast. This is useful to create an intrusive pointer to a derived
* class from an intrusive pointer to a base class. If the cast fails an empty
* (null) intrusive pointer is created.
*/
/** Tag to create an intrusive pointer from another intrusive pointer by using a
dynamic cast. This is useful to create an intrusive pointer to a derived
class from an intrusive pointer to a base class. If the cast fails an empty
(null) intrusive pointer is created.
*/
struct DynamicCastTagSharedIntrusive
{
};
/**
* When creating or adopting a raw pointer, controls whether the strong count
* is incremented or not. Use this tag to increment the strong count.
*/
/** When creating or adopting a raw pointer, controls whether the strong count
is incremented or not. Use this tag to increment the strong count.
*/
struct SharedIntrusiveAdoptIncrementStrongTag
{
};
/**
* When creating or adopting a raw pointer, controls whether the strong count
* is incremented or not. Use this tag to leave the strong count unchanged.
*/
/** When creating or adopting a raw pointer, controls whether the strong count
is incremented or not. Use this tag to leave the strong count unchanged.
*/
struct SharedIntrusiveAdoptNoIncrementTag
{
};
@@ -54,21 +50,20 @@ concept CAdoptTag = std::is_same_v<T, SharedIntrusiveAdoptIncrementStrongTag> ||
//------------------------------------------------------------------------------
/**
* A shared intrusive pointer class that supports weak pointers.
*
* This is meant to be used for SHAMapInnerNodes, but may be useful for other
* cases. Since the reference counts are stored on the pointee, the pointee is
* not destroyed until both the strong _and_ weak pointer counts go to zero.
* When the strong pointer count goes to zero, the "partialDestructor" is
* called. This can be used to destroy as much of the object as possible while
* still retaining the reference counts. For example, for SHAMapInnerNodes the
* children may be reset in that function. Note that std::shared_pointer WILL
* run the destructor when the strong count reaches zero, but may not free the
* memory used by the object until the weak count reaches zero. In xrpld, we
* typically allocate shared pointers with the `make_shared` function. When
* that is used, the memory is not reclaimed until the weak count reaches zero.
*/
/** A shared intrusive pointer class that supports weak pointers.
This is meant to be used for SHAMapInnerNodes, but may be useful for other
cases. Since the reference counts are stored on the pointee, the pointee is
not destroyed until both the strong _and_ weak pointer counts go to zero.
When the strong pointer count goes to zero, the "partialDestructor" is
called. This can be used to destroy as much of the object as possible while
still retaining the reference counts. For example, for SHAMapInnerNodes the
children may be reset in that function. Note that std::shared_pointer WILL
run the destructor when the strong count reaches zero, but may not free the
memory used by the object until the weak count reaches zero. In xrpld, we
typically allocate shared pointers with the `make_shared` function. When
that is used, the memory is not reclaimed until the weak count reaches zero.
*/
template <class T>
class SharedIntrusive
{
@@ -116,9 +111,8 @@ public:
operator=(
SharedIntrusive<TT>&& rhs); // NOLINT(cppcoreguidelines-rvalue-reference-param-not-moved)
/**
* Adopt the raw pointer. The strong reference may or may not be
* incremented, depending on the TAdoptTag
/** Adopt the raw pointer. The strong reference may or may not be
incremented, depending on the TAdoptTag
*/
template <CAdoptTag TAdoptTag = SharedIntrusiveAdoptIncrementStrongTag>
void
@@ -126,31 +120,27 @@ public:
~SharedIntrusive();
/**
* Create a new SharedIntrusive by statically casting the pointer
* controlled by the rhs param.
*/
/** Create a new SharedIntrusive by statically casting the pointer
controlled by the rhs param.
*/
template <class TT>
SharedIntrusive(StaticCastTagSharedIntrusive, SharedIntrusive<TT> const& rhs);
/**
* Create a new SharedIntrusive by statically casting the pointer
* controlled by the rhs param.
*/
/** Create a new SharedIntrusive by statically casting the pointer
controlled by the rhs param.
*/
template <class TT>
SharedIntrusive(StaticCastTagSharedIntrusive, SharedIntrusive<TT>&& rhs);
/**
* Create a new SharedIntrusive by dynamically casting the pointer
* controlled by the rhs param.
*/
/** Create a new SharedIntrusive by dynamically casting the pointer
controlled by the rhs param.
*/
template <class TT>
SharedIntrusive(DynamicCastTagSharedIntrusive, SharedIntrusive<TT> const& rhs);
/**
* Create a new SharedIntrusive by dynamically casting the pointer
* controlled by the rhs param.
*/
/** Create a new SharedIntrusive by dynamically casting the pointer
controlled by the rhs param.
*/
template <class TT>
SharedIntrusive(DynamicCastTagSharedIntrusive, SharedIntrusive<TT>&& rhs);
@@ -163,22 +153,17 @@ public:
explicit
operator bool() const noexcept;
/**
* Set the pointer to null, decrement the strong count, and run the
* appropriate release action.
*/
/** Set the pointer to null, decrement the strong count, and run the
appropriate release action.
*/
void
reset();
/**
* Get the raw pointer
*/
/** Get the raw pointer */
[[nodiscard]] T*
get() const;
/**
* Return the strong count
*/
/** Return the strong count */
[[nodiscard]] std::size_t
useCount() const;
@@ -196,51 +181,43 @@ public:
friend class WeakIntrusive;
private:
/**
* Return the raw pointer held by this object.
*/
/** Return the raw pointer held by this object. */
[[nodiscard]] T*
unsafeGetRawPtr() const;
/**
* Exchange the current raw pointer held by this object with the given
* pointer. Decrement the strong count of the raw pointer previously held
* by this object and run the appropriate release action.
/** Exchange the current raw pointer held by this object with the given
pointer. Decrement the strong count of the raw pointer previously held
by this object and run the appropriate release action.
*/
void
unsafeReleaseAndStore(T* next);
/**
* Set the raw pointer directly. This is wrapped in a function so the class
* can support both atomic and non-atomic pointers in a future patch.
/** Set the raw pointer directly. This is wrapped in a function so the class
can support both atomic and non-atomic pointers in a future patch.
*/
void
unsafeSetRawPtr(T* p);
/**
* Exchange the raw pointer directly.
* This sets the raw pointer to the given value and returns the previous
* value. This is wrapped in a function so the class can support both
* atomic and non-atomic pointers in a future patch.
/** Exchange the raw pointer directly.
This sets the raw pointer to the given value and returns the previous
value. This is wrapped in a function so the class can support both
atomic and non-atomic pointers in a future patch.
*/
T*
unsafeExchange(T* p);
/**
* pointer to the type with an intrusive count
*/
/** pointer to the type with an intrusive count */
T* ptr_{nullptr};
};
//------------------------------------------------------------------------------
/**
* A weak intrusive pointer class for the SharedIntrusive pointer class.
*
* Note that this weak pointer class asks differently from normal weak pointer
* classes. When the strong pointer count goes to zero, the "partialDestructor"
* is called. See the comment on SharedIntrusive for a fuller explanation.
*/
/** A weak intrusive pointer class for the SharedIntrusive pointer class.
Note that this weak pointer class asks differently from normal weak pointer
classes. When the strong pointer count goes to zero, the "partialDestructor"
is called. See the comment on SharedIntrusive for a fuller explanation.
*/
template <class T>
class WeakIntrusive
{
@@ -270,62 +247,54 @@ public:
WeakIntrusive&
operator=(SharedIntrusive<TT> const& rhs);
/**
* Adopt the raw pointer and increment the weak count.
*/
/** Adopt the raw pointer and increment the weak count. */
void
adopt(T* ptr);
~WeakIntrusive();
/**
* Get a strong pointer from the weak pointer, if possible. This will
* only return a seated pointer if the strong count on the raw pointer
* is non-zero before locking.
/** Get a strong pointer from the weak pointer, if possible. This will
only return a seated pointer if the strong count on the raw pointer
is non-zero before locking.
*/
SharedIntrusive<T>
lock() const;
/**
* Return true if the strong count is zero.
*/
/** Return true if the strong count is zero. */
[[nodiscard]] bool
expired() const;
/**
* Set the pointer to null and decrement the weak count.
*
* Note: This may run the destructor if the strong count is zero.
*/
/** Set the pointer to null and decrement the weak count.
Note: This may run the destructor if the strong count is zero.
*/
void
reset();
private:
T* ptr_ = nullptr;
/**
* Decrement the weak count. This does _not_ set the raw pointer to
* null.
*
* Note: This may run the destructor if the strong count is zero.
*/
/** Decrement the weak count. This does _not_ set the raw pointer to
null.
Note: This may run the destructor if the strong count is zero.
*/
void
unsafeReleaseNoStore();
};
//------------------------------------------------------------------------------
/**
* A combination of a strong and a weak intrusive pointer stored in the
* space of a single pointer.
*
* This class is similar to a `std::variant<SharedIntrusive,WeakIntrusive>`
* with some optimizations. In particular, it uses a low-order bit to
* determine if the raw pointer represents a strong pointer or a weak
* pointer. It can also be quickly switched between its strong pointer and
* weak pointer representations. This class is useful for storing intrusive
* pointers in tagged caches.
*/
/** A combination of a strong and a weak intrusive pointer stored in the
space of a single pointer.
This class is similar to a `std::variant<SharedIntrusive,WeakIntrusive>`
with some optimizations. In particular, it uses a low-order bit to
determine if the raw pointer represents a strong pointer or a weak
pointer. It can also be quickly switched between its strong pointer and
weak pointer representations. This class is useful for storing intrusive
pointers in tagged caches.
*/
template <class T>
class SharedWeakUnion
@@ -367,83 +336,69 @@ public:
~SharedWeakUnion();
/**
* Return a strong pointer if this is already a strong pointer (i.e.
* don't lock the weak pointer. Use the `lock` method if that's what's
* needed)
/** Return a strong pointer if this is already a strong pointer (i.e.
don't lock the weak pointer. Use the `lock` method if that's what's
needed)
*/
[[nodiscard]] SharedIntrusive<T>
getStrong() const;
/**
* Return true if this is a strong pointer and the strong pointer is
* seated.
/** Return true if this is a strong pointer and the strong pointer is
seated.
*/
explicit
operator bool() const noexcept;
/**
* Set the pointer to null, decrement the appropriate ref count, and
* run the appropriate release action.
/** Set the pointer to null, decrement the appropriate ref count, and
run the appropriate release action.
*/
void
reset();
/**
* If this is a strong pointer, return the raw pointer. Otherwise
* return null.
/** If this is a strong pointer, return the raw pointer. Otherwise
return null.
*/
[[nodiscard]] T*
get() const;
/**
* If this is a strong pointer, return the strong count. Otherwise
/** If this is a strong pointer, return the strong count. Otherwise
* return 0
*/
[[nodiscard]] std::size_t
useCount() const;
/**
* Return true if there is a non-zero strong count.
*/
/** Return true if there is a non-zero strong count. */
[[nodiscard]] bool
expired() const;
/**
* If this is a strong pointer, return the strong pointer. Otherwise
* attempt to lock the weak pointer.
/** If this is a strong pointer, return the strong pointer. Otherwise
attempt to lock the weak pointer.
*/
[[nodiscard]] SharedIntrusive<T>
lock() const;
/**
* Return true is this represents a strong pointer.
*/
/** Return true is this represents a strong pointer. */
[[nodiscard]] bool
isStrong() const;
/**
* Return true is this represents a weak pointer.
*/
/** Return true is this represents a weak pointer. */
[[nodiscard]] bool
isWeak() const;
/**
* If this is a weak pointer, attempt to convert it to a strong
* pointer.
*
* @return true if successfully converted to a strong pointer (or was
* already a strong pointer). Otherwise false.
*/
/** If this is a weak pointer, attempt to convert it to a strong
pointer.
@return true if successfully converted to a strong pointer (or was
already a strong pointer). Otherwise false.
*/
bool
convertToStrong();
/**
* If this is a strong pointer, attempt to convert it to a weak
* pointer.
*
* @return false if the pointer is null. Otherwise return true.
*/
/** If this is a strong pointer, attempt to convert it to a weak
pointer.
@return false if the pointer is null. Otherwise return true.
*/
bool
convertToWeak();
@@ -456,27 +411,23 @@ private:
static constexpr std::uintptr_t kPtrMask = ~kTagMask;
private:
/**
* Return the raw pointer held by this object.
/** Return the raw pointer held by this object.
*/
[[nodiscard]] T*
unsafeGetRawPtr() const;
enum class RefStrength { Strong, Weak };
/**
* Set the raw pointer and tag bit directly.
/** Set the raw pointer and tag bit directly.
*/
void
unsafeSetRawPtr(T* p, RefStrength rs);
/**
* Set the raw pointer and tag bit to all zeros (strong null pointer).
/** Set the raw pointer and tag bit to all zeros (strong null pointer).
*/
void unsafeSetRawPtr(std::nullptr_t);
/**
* Decrement the appropriate ref count, and run the appropriate release
* action. Note: this does _not_ set the raw pointer to null.
/** Decrement the appropriate ref count, and run the appropriate release
action. Note: this does _not_ set the raw pointer to null.
*/
void
unsafeReleaseNoStore();
@@ -484,13 +435,12 @@ private:
//------------------------------------------------------------------------------
/**
* Create a shared intrusive pointer.
*
* Note: unlike std::shared_ptr, where there is an advantage of allocating
* the pointer and control block together, there is no benefit for intrusive
* pointers.
*/
/** Create a shared intrusive pointer.
Note: unlike std::shared_ptr, where there is an advantage of allocating
the pointer and control block together, there is no benefit for intrusive
pointers.
*/
template <class TT, class... Args>
SharedIntrusive<TT>
makeSharedIntrusive(Args&&... args)

View File

@@ -8,38 +8,35 @@
namespace xrpl {
/**
* Action to perform when releasing a strong pointer.
*
* noop: Do nothing. For example, a `noop` action will occur when a count is
* decremented to a non-zero value.
*
* partialDestroy: Run the `partialDestructor`. This action will happen when a
* strong count is decremented to zero and the weak count is non-zero.
*
* destroy: Run the destructor. This action will occur when either the strong
* count or weak count is decremented and the other count is also zero.
/** Action to perform when releasing a strong pointer.
noop: Do nothing. For example, a `noop` action will occur when a count is
decremented to a non-zero value.
partialDestroy: Run the `partialDestructor`. This action will happen when a
strong count is decremented to zero and the weak count is non-zero.
destroy: Run the destructor. This action will occur when either the strong
count or weak count is decremented and the other count is also zero.
*/
enum class ReleaseStrongRefAction { NoOp, PartialDestroy, Destroy };
/**
* Action to perform when releasing a weak pointer.
*
* noop: Do nothing. For example, a `noop` action will occur when a count is
* decremented to a non-zero value.
*
* destroy: Run the destructor. This action will occur when either the strong
* count or weak count is decremented and the other count is also zero.
/** Action to perform when releasing a weak pointer.
noop: Do nothing. For example, a `noop` action will occur when a count is
decremented to a non-zero value.
destroy: Run the destructor. This action will occur when either the strong
count or weak count is decremented and the other count is also zero.
*/
enum class ReleaseWeakRefAction { NoOp, Destroy };
/**
* Implement the strong count, weak count, and bit flags for an intrusive
* pointer.
*
* A class can satisfy the requirements of an xrpl::IntrusivePointer by
* inheriting from this class.
*/
/** Implement the strong count, weak count, and bit flags for an intrusive
pointer.
A class can satisfy the requirements of an xrpl::IntrusivePointer by
inheriting from this class.
*/
struct IntrusiveRefCounts
{
virtual ~IntrusiveRefCounts() noexcept;
@@ -108,123 +105,109 @@ private:
static constexpr size_t kFieldTypeBits = sizeof(FieldType) * 8;
static constexpr FieldType kOne = 1;
/**
* `refCounts` consists of four fields that are treated atomically:
*
* 1. Strong count. This is a count of the number of shared pointers that
* hold a reference to this object. When the strong counts goes to zero,
* if the weak count is zero, the destructor is run. If the weak count is
* non-zero when the strong count goes to zero then the partialDestructor
* is run.
*
* 2. Weak count. This is a count of the number of weak pointer that hold
* a reference to this object. When the weak count goes to zero and the
* strong count is also zero, then the destructor is run.
*
* 3. Partial destroy started bit. This bit is set if the
* `partialDestructor` function has been started (or is about to be
* started). This is used to prevent the destructor from running
* concurrently with the partial destructor. This can easily happen when
* the last strong pointer release its reference in one thread and starts
* the partialDestructor, while in another thread the last weak pointer
* goes out of scope and starts the destructor while the partialDestructor
* is still running. Both a start and finished bit is needed to handle a
* corner-case where the last strong pointer goes out of scope, then then
* last `weakPointer` goes out of scope, but this happens before the
* `partialDestructor` bit is set. It would be possible to use a single
* bit if it could also be set atomically when the strong count goes to
* zero and the weak count is non-zero, but that would add complexity (and
* likely slow down common cases as well).
*
* 4. Partial destroy finished bit. This bit is set when the
* `partialDestructor` has finished running. See (3) above for more
* information.
*/
/** `refCounts` consists of four fields that are treated atomically:
1. Strong count. This is a count of the number of shared pointers that
hold a reference to this object. When the strong counts goes to zero,
if the weak count is zero, the destructor is run. If the weak count is
non-zero when the strong count goes to zero then the partialDestructor
is run.
2. Weak count. This is a count of the number of weak pointer that hold
a reference to this object. When the weak count goes to zero and the
strong count is also zero, then the destructor is run.
3. Partial destroy started bit. This bit is set if the
`partialDestructor` function has been started (or is about to be
started). This is used to prevent the destructor from running
concurrently with the partial destructor. This can easily happen when
the last strong pointer release its reference in one thread and starts
the partialDestructor, while in another thread the last weak pointer
goes out of scope and starts the destructor while the partialDestructor
is still running. Both a start and finished bit is needed to handle a
corner-case where the last strong pointer goes out of scope, then then
last `weakPointer` goes out of scope, but this happens before the
`partialDestructor` bit is set. It would be possible to use a single
bit if it could also be set atomically when the strong count goes to
zero and the weak count is non-zero, but that would add complexity (and
likely slow down common cases as well).
4. Partial destroy finished bit. This bit is set when the
`partialDestructor` has finished running. See (3) above for more
information.
*/
mutable std::atomic<FieldType> refCounts_{kStrongDelta};
/**
* Amount to change the strong count when adding or releasing a reference
*
* Note: The strong count is stored in the low `StrongCountNumBits` bits
* of refCounts
*/
/** Amount to change the strong count when adding or releasing a reference
Note: The strong count is stored in the low `StrongCountNumBits` bits
of refCounts
*/
static constexpr FieldType kStrongDelta = 1;
/**
* Amount to change the weak count when adding or releasing a reference
*
* Note: The weak count is stored in the high `WeakCountNumBits` bits of
* refCounts
*/
/** Amount to change the weak count when adding or releasing a reference
Note: The weak count is stored in the high `WeakCountNumBits` bits of
refCounts
*/
static constexpr FieldType kWeakDelta = (kOne << kStrongCountNumBits);
/**
* Flag that is set when the partialDestroy function has started running
* (or is about to start running).
*
* See description of the `refCounts` field for a fuller description of
* this field.
*/
/** Flag that is set when the partialDestroy function has started running
(or is about to start running).
See description of the `refCounts` field for a fuller description of
this field.
*/
static constexpr FieldType kPartialDestroyStartedMask = (kOne << (kFieldTypeBits - 1));
/**
* Flag that is set when the partialDestroy function has finished running
*
* See description of the `refCounts` field for a fuller description of
* this field.
*/
/** Flag that is set when the partialDestroy function has finished running
See description of the `refCounts` field for a fuller description of
this field.
*/
static constexpr FieldType kPartialDestroyFinishedMask = (kOne << (kFieldTypeBits - 2));
/**
* Mask that will zero out all the `count` bits and leave the tag bits
* unchanged.
*/
/** Mask that will zero out all the `count` bits and leave the tag bits
unchanged.
*/
static constexpr FieldType kTagMask = kPartialDestroyStartedMask | kPartialDestroyFinishedMask;
/**
* Mask that will zero out the `tag` bits and leave the count bits
* unchanged.
*/
/** Mask that will zero out the `tag` bits and leave the count bits
unchanged.
*/
static constexpr FieldType kValueMask = ~kTagMask;
/**
* Mask that will zero out everything except the strong count.
/** Mask that will zero out everything except the strong count.
*/
static constexpr FieldType kStrongMask = ((kOne << kStrongCountNumBits) - 1) & kValueMask;
/**
* Mask that will zero out everything except the weak count.
/** Mask that will zero out everything except the weak count.
*/
static constexpr FieldType kWeakMask =
(((kOne << kWeakCountNumBits) - 1) << kStrongCountNumBits) & kValueMask;
/**
* Unpack the count and tag fields from the packed atomic integer form.
*/
/** Unpack the count and tag fields from the packed atomic integer form. */
struct RefCountPair
{
CountType strong;
CountType weak;
/**
* The `partialDestroyStartedBit` is set to on when the partial
* destroy function is started. It is not a boolean; it is a uint32
* with all bits zero with the possible exception of the
* `partialDestroyStartedMask` bit. This is done so it can be directly
* masked into the `combinedValue`.
/** The `partialDestroyStartedBit` is set to on when the partial
destroy function is started. It is not a boolean; it is a uint32
with all bits zero with the possible exception of the
`partialDestroyStartedMask` bit. This is done so it can be directly
masked into the `combinedValue`.
*/
FieldType partialDestroyStartedBit{0};
/**
* The `partialDestroyFinishedBit` is set to on when the partial
* destroy function has finished.
/** The `partialDestroyFinishedBit` is set to on when the partial
destroy function has finished.
*/
FieldType partialDestroyFinishedBit{0};
RefCountPair(FieldType v) noexcept;
RefCountPair(CountType s, CountType w) noexcept;
/**
* Convert back to the packed integer form.
*/
/** Convert back to the packed integer form. */
[[nodiscard]] FieldType
combinedValue() const noexcept;
@@ -232,10 +215,9 @@ private:
static_cast<CountType>((kOne << kStrongCountNumBits) - 1);
static constexpr CountType kMaxWeakValue =
static_cast<CountType>((kOne << kWeakCountNumBits) - 1);
/**
* Put an extra margin to detect when running up against limits.
* This is only used in debug code, and is useful if we reduce the
* number of bits in the strong and weak counts (to 16 and 14 bits).
/** Put an extra margin to detect when running up against limits.
This is only used in debug code, and is useful if we reduce the
number of bits in the strong and weak counts (to 16 and 14 bits).
*/
static constexpr CountType kCheckStrongMaxValue = kMaxStrongValue - 32;
static constexpr CountType kCheckWeakMaxValue = kMaxWeakValue - 32;

View File

@@ -70,15 +70,11 @@ public:
{
}
/**
* Stores instance of T specific to the calling coroutine or thread.
*/
/** Stores instance of T specific to the calling coroutine or thread. */
T&
operator*();
/**
* Stores instance of T specific to the calling coroutine or thread.
*/
/** Stores instance of T specific to the calling coroutine or thread. */
T*
operator->()
{

View File

@@ -16,9 +16,7 @@
namespace xrpl {
/**
* Manages partitions for logging.
*/
/** Manages partitions for logging. */
class Logs
{
private:
@@ -42,81 +40,69 @@ private:
writeAlways(beast::Severity level, std::string const& text) override;
};
/**
* Manages a system file containing logged output.
* The system file remains open during program execution. Interfaces
* are provided for interoperating with standard log management
* tools like logrotate(8):
* http://linuxcommand.org/man_pages/logrotate8.html
* @note None of the listed interfaces are thread-safe.
*/
/** Manages a system file containing logged output.
The system file remains open during program execution. Interfaces
are provided for interoperating with standard log management
tools like logrotate(8):
http://linuxcommand.org/man_pages/logrotate8.html
@note None of the listed interfaces are thread-safe.
*/
class File
{
public:
/**
* Construct with no associated system file.
* A system file may be associated later with @ref open.
* @see open
*/
/** Construct with no associated system file.
A system file may be associated later with @ref open.
@see open
*/
File();
/**
* Destroy the object.
* If a system file is associated, it will be flushed and closed.
*/
/** Destroy the object.
If a system file is associated, it will be flushed and closed.
*/
~File() = default;
/**
* Determine if a system file is associated with the log.
* @return `true` if a system file is associated and opened for
* writing.
*/
/** Determine if a system file is associated with the log.
@return `true` if a system file is associated and opened for
writing.
*/
[[nodiscard]] bool
isOpen() const noexcept;
/**
* Associate a system file with the log.
* If the file does not exist an attempt is made to create it
* and open it for writing. If the file already exists an attempt is
* made to open it for appending.
* If a system file is already associated with the log, it is closed
* first.
* @return `true` if the file was opened.
*/
/** Associate a system file with the log.
If the file does not exist an attempt is made to create it
and open it for writing. If the file already exists an attempt is
made to open it for appending.
If a system file is already associated with the log, it is closed
first.
@return `true` if the file was opened.
*/
bool
open(boost::filesystem::path const& path);
/**
* Close and re-open the system file associated with the log
* This assists in interoperating with external log management tools.
* @return `true` if the file was opened.
*/
/** Close and re-open the system file associated with the log
This assists in interoperating with external log management tools.
@return `true` if the file was opened.
*/
bool
closeAndReopen();
/**
* Close the system file if it is open.
*/
/** Close the system file if it is open. */
void
close();
/**
* write to the log file.
* Does nothing if there is no associated system file.
*/
/** write to the log file.
Does nothing if there is no associated system file.
*/
void
write(char const* text);
/**
* write to the log file and append an end of line marker.
* Does nothing if there is no associated system file.
*/
/** write to the log file and append an end of line marker.
Does nothing if there is no associated system file.
*/
void
writeln(char const* text);
/**
* Write to the log file using std::string.
*/
/** Write to the log file using std::string. */
/** @{ */
void
write(std::string const& str)
@@ -237,21 +223,19 @@ private:
//------------------------------------------------------------------------------
// Debug logging:
/**
* Set the sink for the debug journal.
*
* @param sink unique_ptr to new debug Sink.
* @return unique_ptr to the previous Sink. nullptr if there was no Sink.
*/
/** Set the sink for the debug journal.
@param sink unique_ptr to new debug Sink.
@return unique_ptr to the previous Sink. nullptr if there was no Sink.
*/
std::unique_ptr<beast::Journal::Sink>
setDebugLogSink(std::unique_ptr<beast::Journal::Sink> sink);
/**
* Returns a debug journal.
* The journal may drain to a null sink, so its output
* may never be seen. Never use it for critical
* information.
*/
/** Returns a debug journal.
The journal may drain to a null sink, so its output
may never be seen. Never use it for critical
information.
*/
beast::Journal
debugLog();

View File

@@ -6,8 +6,7 @@
namespace xrpl {
/**
* Calculate one number divided by another number in percentage.
/** Calculate one number divided by another number in percentage.
* The result is rounded up to the next integer, and capped in the range [0,100]
* E.g. calculatePercent(1, 100) = 1 because 1/100 = 0.010000
* calculatePercent(1, 99) = 2 because 1/99 = 0.010101
@@ -20,7 +19,7 @@ namespace xrpl {
* @return the percentage, in [0, 100]
*
* @note total cannot be zero.
*/
* */
constexpr std::size_t
calculatePercent(std::size_t count, std::size_t total)
{

View File

@@ -2,8 +2,8 @@
#include <xrpl/beast/utility/instrumentation.h>
#include <algorithm>
#include <array>
#include <concepts>
#include <cstddef>
#include <cstdint>
#include <functional>
@@ -13,9 +13,15 @@
#include <set>
#include <stdexcept>
#include <string>
#include <tuple>
#include <type_traits>
#include <unordered_map>
#include <utility>
#ifdef _MSC_VER
#include <boost/multiprecision/cpp_int.hpp>
#endif // !defined(_MSC_VER)
namespace xrpl {
class Number;
@@ -23,18 +29,39 @@ class Number;
std::string
to_string(Number const& amount);
/** Returns a rough estimate of log10(value).
*
* The return value is a pair (log, rem), where log is the estimated
* base-10 logarithm (roughly floor(log10(value))), and rem is value with
* all trailing 0s removed (i.e., divided by the largest power of 10 that
* evenly divides value). If rem is 1, then value is an exact power of ten, and
* log is the exact log10(value).
*
* This function only works for positive values.
*/
template <std::unsigned_integral T>
constexpr std::pair<int, T>
logTenEstimate(T value)
{
int log = 0;
T remainder = value;
while (value >= 10)
{
if (value % 10 == 0)
remainder = remainder / 10;
value /= 10;
++log;
}
return {log, remainder};
}
template <typename T>
constexpr std::optional<int>
logTen(T value)
{
int log = 0;
while (value >= 10 && value % 10 == 0)
{
value /= 10;
++log;
}
if (value == 1)
return log;
auto const est = logTenEstimate(value);
if (est.second == 1)
return est.first;
return std::nullopt;
}
@@ -47,62 +74,51 @@ isPowerOfTen(T value)
namespace detail {
/**
* Builds a table of the powers of 10
/** Builds a table of the powers of 10
*
* This function is marked consteval, so it can only be run in
* a constexpr context. This assures that it is and can only be run at
* compile time. Doing it at runtime would be pretty wasteful and
* inefficient.
*/
constexpr std::size_t kUint64Digits = 20;
[[maybe_unused]] constexpr std::size_t kUint128Digits = 39;
template <typename T, std::size_t Digits>
consteval std::array<T, Digits>
constexpr std::size_t kInt64Digits = 20;
consteval std::array<std::uint64_t, kInt64Digits>
buildPowersOfTen()
{
std::array<T, Digits> result{};
std::array<std::uint64_t, kInt64Digits> result{};
T power = 1;
std::uint64_t power = 1;
std::size_t exponent = 0;
// end the loop early so it doesn't overflow;
for (; exponent < result.size() - 1; ++exponent, power *= 10)
{
result[exponent] = power;
if (power > std::numeric_limits<T>::max() / 10)
if (power > std::numeric_limits<std::uint64_t>::max() / 10)
throw std::logic_error("Power of 10 table is too big");
}
result[exponent] = power;
if (power < std::numeric_limits<T>::max() / 10)
throw std::logic_error("Power of 10 table is not big enough for the given type");
if (power < std::numeric_limits<std::uint64_t>::max() / 10)
throw std::logic_error("Power of 10 table is not big enough for the uint64_t type");
return result;
}
} // namespace detail
template <typename T = std::uint64_t, std::size_t Digits = detail::kUint64Digits>
constexpr std::array<T, Digits> kPowerOfTenImpl = detail::buildPowersOfTen<T, Digits>();
constexpr auto kPowerOfTen = kPowerOfTenImpl<std::uint64_t, detail::kUint64Digits>;
constexpr std::array<std::uint64_t, detail::kInt64Digits> kPowerOfTen = detail::buildPowersOfTen();
static_assert(kPowerOfTen[0] == 1);
static_assert(kPowerOfTen[1] == 10);
static_assert(kPowerOfTen[10] == 10'000'000'000);
static_assert(
isPowerOfTen(kPowerOfTen.back()) && *logTen(kPowerOfTen.back()) == detail::kUint64Digits - 1);
isPowerOfTen(kPowerOfTen.back()) && *logTen(kPowerOfTen.back()) == detail::kInt64Digits - 1);
/**
* MantissaRange defines a range for the mantissa of a normalized Number.
/** MantissaRange defines a range for the mantissa of a normalized Number.
*
* The mantissa is in the range [min, max], where
* * min is a power of 10, and
* * max = min * 10 - 1.
*
* The MantissaScale enum indicates properties of the range: size, and some behavioral
* options. This intentionally restricts the number of unique MantissaRanges that can
* be instantiated: one for each scale.
* The MantissaScale enum indicates properties of the range: size, and some behavioral options.
* This intentionally prevents the creation of any MantissaRanges representing other values.
*
* The "Small" scale is based on the behavior of STAmount for IOUs. It has a min
* value of 10^15, and a max value of 10^16-1. This was sufficient for
@@ -116,12 +132,14 @@ static_assert(
* "large" scale.
*
* The "Large" scales are intended to represent all values that can be represented
* by an STAmount - IOUs, XRP, and MPTs. It has a min value of 10^18, and a max
* value of 10^19-1. "LargeLegacy" is like "Large", but preserves
* a rounding error when a computation results in a mantissa of
* Number::kMaxRep that needs to be rounded up, but rounds down
* instead. It will maintain consistent behavior until the fixCleanup3_2_0
* amendment is enabled.
* by an STAmount - IOUs, XRP, and MPTs.
*
* They have a min value of 2^63/10+1 (truncated), and a max value of 2^63-1.
*
* "LargeLegacy" is like "Large", but preserves a rounding error when
* a computation results in a mantissa of Number::kLargestMantissa that needs to
* be rounded up, but rounds down instead. It will maintain consistent
* behavior until the fixCleanup3_2_0 amendment is enabled.
*
* Note that if the mentioned amendments are eventually retired, this class
* should be left in place, but the "Small" scale option should be removed. This
@@ -131,68 +149,61 @@ struct MantissaRange final
{
using rep = std::uint64_t;
// NOLINTBEGIN(readability-enum-initial-value)
// The values don't matter, except for Large
enum class MantissaScale {
// Small can be removed when either featureSingleAssetVault or featureLendingProtocol are
// retired
Small,
// LargeLegacy can be removed when fixCleanup3_2_0 is retired
LargeLegacy,
// Large320 can be removed when fixCleanup3_3_0 is retired
Large320,
// If Large330 is ever the only remaining "Large*" entry, it can be renamed to just "Large".
Large330,
// Large is a de-facto alias for "the latest", and is only here for backward compatibility
// in the extremely unlikely case that a downstream project made use of it. Note that
// because the behavior changed, this may still be a breaking change.
Large = Large330,
Large,
};
// NOLINTEND(readability-enum-initial-value)
// This entire enum can be removed when the last relevant amendment is retired
enum class CuspRoundingFix : std::uint8_t {
// Disabled can be removed when fixCleanup3_2_0 is retired
Disabled = 0,
// Enabled320 can be removed when fixCleanup3_3_0 is retired
Enabled320 = 1,
// If we ever get to the point that there's only one entry, remove the entire enum
Enabled330 = 2,
// Enabled is a de-facto alias for "the latest", and is only here for backward compatibility
// in the extremely unlikely case that a downstream project made use of it. Note that
// because the behavior changed, this may still be a breaking change.
Enabled = Enabled330,
// This entire enum can be removed when fixCleanup3_2_0 is retired
enum class CuspRoundingFix : bool {
Disabled = false,
Enabled = true,
};
explicit constexpr MantissaRange(MantissaScale sc) : scale(sc)
{
// Keep the error messages terse. Since this is constexpr, if any of these throw, it won't
// compile, so there's no real need to worry about runtime exceptions here.
if (min * 10 <= max)
throw std::out_of_range("Invalid mantissa range: min * 10 <= max");
if (max / 10 >= min)
throw std::out_of_range("Invalid mantissa range: max / 10 >= min");
if ((min - 1) * 10 > max)
throw std::out_of_range("Invalid mantissa range: (min - 1) * 10 > max");
// This is a little hacky
if ((max + 10) / 10 < min)
throw std::out_of_range("Invalid mantissa range: (max + 10) / 10 < min");
if (internalMin != kPowerOfTen[log])
throw std::out_of_range("Invalid mantissa range: internalMin != kPowersOfTen[log]");
}
// Explicitly delete copy and move operations
MantissaRange(MantissaRange const&) = delete;
MantissaRange(MantissaRange&&) = delete;
MantissaRange&
operator=(MantissaRange const&) = delete;
MantissaRange&
operator=(MantissaRange&&) = delete;
MantissaScale const scale;
int const log{getExponent(scale)};
rep const min{getMin(scale, log)};
rep const max{(min * 10) - 1};
CuspRoundingFix const cuspRoundingFix{isCuspFixEnabled(scale)};
rep const max{getMax(scale, log)};
rep const min{computeMin(max)};
/* Used to determine if mantissas are in range, but have fewer digits than max.
*
* Unlike min, internalMin is always an exact power of 10, so a mantissa in the internal
* representation will always have a consistent number of digits.
*/
rep const internalMin{getInternalMin(scale, log)};
CuspRoundingFix const cuspRoundingFixEnabled{isCuspFixEnabled(scale)};
static constexpr MantissaRange const&
getMantissaRange(MantissaScale scale);
static std::set<MantissaScale> const&
getAllScales()
{
static std::set<MantissaRange::MantissaScale> const kScales = {
MantissaRange::MantissaScale::Small,
MantissaRange::MantissaScale::LargeLegacy,
MantissaRange::MantissaScale::Large320,
MantissaRange::MantissaScale::Large330,
};
return kScales;
}
class Access
{
static constexpr MantissaRange const&
mantissaRange(MantissaScale scale);
friend Number;
};
getAllScales();
private:
static constexpr int
@@ -203,8 +214,7 @@ private:
case MantissaScale::Small:
return 15;
case MantissaScale::LargeLegacy:
case MantissaScale::Large320:
case MantissaScale::Large330:
case MantissaScale::Large:
return 18;
// LCOV_EXCL_START
default:
@@ -215,13 +225,39 @@ private:
}
}
// Keep this function for future use with different ways to compute
// the ranges.
static constexpr rep
getMin(MantissaScale scale, int exponent)
getMax(MantissaScale scale, int log)
{
switch (scale)
{
case MantissaScale::Small:
return kPowerOfTen[log + 1] - 1;
case MantissaScale::LargeLegacy:
case MantissaScale::Large:
return std::numeric_limits<std::int64_t>::max();
default:
// If called in a constexpr context, this throw assures that the build fails if an
// invalid scale is used.
throw std::runtime_error("Unknown mantissa scale");
// LCOV_EXCL_STOP
}
}
static constexpr rep
computeMin(rep max)
{
return (max / 10) + 1;
}
static constexpr rep
getInternalMin(MantissaScale scale, int exponent)
{
if (exponent < 0 || exponent >= kPowerOfTen.size())
{
// If called in a constexpr context, this throw assures that the build fails if an
// invalid exponent is used.
throw std::runtime_error("Invalid exponent"); // LCOV_EXCL_LINE
}
return kPowerOfTen[exponent];
}
@@ -233,30 +269,43 @@ private:
case MantissaScale::Small:
case MantissaScale::LargeLegacy:
return CuspRoundingFix::Disabled;
case MantissaScale::Large320:
return CuspRoundingFix::Enabled320;
case MantissaScale::Large330:
return CuspRoundingFix::Enabled330;
case MantissaScale::Large:
return CuspRoundingFix::Enabled;
default:
// If called in a constexpr context, this throw assures that the build fails if an
// invalid scale is used.
throw std::runtime_error("Unknown mantissa scale"); // LCOV_EXCL_LINE
}
}
static std::unordered_map<MantissaScale, MantissaRange> const&
getRanges();
};
// Like std::integral, but only 64-bit integral types.
template <class T>
concept Integral64 = std::is_same_v<T, std::int64_t> || std::is_same_v<T, std::uint64_t>;
/**
* Number is a floating point type that can represent a wide range of values.
namespace detail {
#ifdef _MSC_VER
using uint128_t = boost::multiprecision::uint128_t;
using int128_t = boost::multiprecision::int128_t;
#else // !defined(_MSC_VER)
using uint128_t = __uint128_t;
using int128_t = __int128_t;
#endif // !defined(_MSC_VER)
template <class T>
concept UnsignedMantissa = std::is_unsigned_v<T> || std::is_same_v<T, uint128_t>;
} // namespace detail
/** Number is a floating point type that can represent a wide range of values.
*
* It can represent all values that can be represented by an STAmount -
* regardless of asset type - XRPAmount, MPTAmount, and IOUAmount, with at least
* as much precision as those types require.
*
* ---- Internal Representation ----
* ---- Internal Operational Representation ----
*
* Internally, Number is represented with three values:
* 1. a bool sign flag,
@@ -265,40 +314,45 @@ concept Integral64 = std::is_same_v<T, std::int64_t> || std::is_same_v<T, std::u
*
* The internal mantissa is an unsigned integer in the range defined by the
* current MantissaRange. The exponent is an integer in the range
* [minExponent, maxExponent].
* [kMinExponent, kMaxExponent].
*
* See the description of MantissaRange for more details on the ranges.
*
* A non-zero mantissa is (almost) always normalized, meaning it and the
* exponent are grown or shrunk until the mantissa is in the range
* [MantissaRange.min, MantissaRange.max].
* [MantissaRange.internalMin, MantissaRange.internalMin * 10 - 1].
*
* This internal representation is only used during some operations to ensure
* that the mantissa is a known, predictable size. The class itself stores the
* values using the external representation described below.
*
* Note:
* 1. Normalization can be disabled by using the "unchecked" ctor tag. This
* should only be used at specific conversion points, some constexpr
* values, and in unit tests.
* 2. The max of the "large" range, 10^19-1, is the largest 10^X-1 value that
* fits in an unsigned 64-bit number. (10^19-1 < 2^64-1 and
* 10^20-1 > 2^64-1). This avoids under- and overflows.
* 2. Unlike MantissaRange.min, internalMin is always an exact power of 10,
* so a mantissa in the internal representation will always have a
* consistent number of digits.
* 3. The functions toInternal() and fromInternal() are used to convert
* between the two representations.
*
* ---- External Interface ----
*
* The external interface of Number consists of a std::int64_t mantissa, which
* is restricted to 63-bits, and an int exponent, which must be in the range
* [minExponent, maxExponent]. The range of the mantissa depends on which
* [kMinExponent, kMaxExponent]. The range of the mantissa depends on which
* MantissaRange is currently active. For the "short" range, the mantissa will
* be between 10^15 and 10^16-1. For the "large" range, the mantissa will be
* between -(2^63-1) and 2^63-1. As noted above, the "large" range is needed to
* represent the full range of valid XRP and MPT integer values accurately.
*
* Note:
* 1. 2^63-1 is between 10^18 and 10^19-1, which are the limits of the "large"
* mantissa range.
* 1. The "large" mantissa range is (2^63/10+1) to 2^63-1. 2^63-1 is between
* 10^18 and 10^19-1, and (2^63/10+1) is between 10^17 and 10^18-1. Thus,
* the mantissa may have 18 or 19 digits. This value will be modified to
* always have 19 digits before some operations to ensure consistency.
* 2. The functions mantissa() and exponent() return the external view of the
* Number value, specifically using a signed 63-bit mantissa. This may
* require altering the internal representation to fit into that range
* before the value is returned. The interface guarantees consistency of
* the two values.
* Number value, specifically using a signed 63-bit mantissa.
* 3. Number cannot represent -2^63 (std::numeric_limits<std::int64_t>::min())
* as an exact integer, but it doesn't need to, because all asset values
* on-ledger are non-negative. This is due to implementation details of
@@ -346,14 +400,14 @@ concept Integral64 = std::is_same_v<T, std::int64_t> || std::is_same_v<T, std::u
* disable the amendments that control the mantissa range choice
* (SingleAssetVault and LendingProtocol), and/or check if either of those
* amendments are enabled to determine which result to expect.
*
*/
class Number final
{
using rep = std::int64_t;
using internalrep = MantissaRange::rep;
bool negative_{false};
internalrep mantissa_{0};
rep mantissa_{0};
int exponent_{std::numeric_limits<int>::lowest()};
public:
@@ -361,10 +415,6 @@ public:
static constexpr int kMinExponent = -32768;
static constexpr int kMaxExponent = 32768;
static constexpr internalrep kMaxRep = std::numeric_limits<rep>::max();
static_assert(kMaxRep == 9'223'372'036'854'775'807);
static_assert(-kMaxRep == std::numeric_limits<rep>::min() + 1);
// May need to make unchecked private
struct Unchecked
{
@@ -431,11 +481,10 @@ public:
static Number
lowest() noexcept;
/**
* Conversions to Number are implicit and conversions away from Number
* are explicit. This design encourages and facilitates the use of Number
* as the preferred type for floating point arithmetic as it makes
* "mixed mode" more convenient, e.g. MPTAmount + Number.
/** Conversions to Number are implicit and conversions away from Number
* are explicit. This design encourages and facilitates the use of Number
* as the preferred type for floating point arithmetic as it makes
* "mixed mode" more convenient, e.g. MPTAmount + Number.
*/
explicit
operator rep() const; // round to nearest, even on tie
@@ -443,8 +492,7 @@ public:
friend constexpr bool
operator==(Number const& x, Number const& y) noexcept
{
return x.negative_ == y.negative_ && x.mantissa_ == y.mantissa_ &&
x.exponent_ == y.exponent_;
return x.mantissa_ == y.mantissa_ && x.exponent_ == y.exponent_;
}
friend constexpr bool
@@ -456,8 +504,8 @@ public:
friend constexpr bool
operator<(Number const& l, Number const& r) noexcept
{
bool const lneg = l.negative_;
bool const rneg = r.negative_;
bool const lneg = l.mantissa_ < 0;
bool const rneg = r.mantissa_ < 0;
// If the two amounts have different signs (zero is treated as positive)
// then the comparison is true iff the left is negative.
@@ -481,24 +529,27 @@ public:
return !lneg;
// If equal signs and exponents, compare mantissas.
if (lneg)
if constexpr (std::is_unsigned_v<decltype(l.mantissa_)>)
{
// If negative, the operator is reversed.
return l.mantissa_ > r.mantissa_;
if (lneg)
{
// If negative, the operator is reversed.
return l.mantissa_ < r.mantissa_;
}
}
return l.mantissa_ < r.mantissa_;
}
/**
* Return the sign of the amount
*/
/** Return the sign of the amount */
[[nodiscard]] constexpr int
signum() const noexcept
{
if (negative_)
if (mantissa_ < 0)
{
return -1;
return (mantissa_ != 0u) ? 1 : 0;
}
return (mantissa_ != 0 ? 1 : 0);
}
[[nodiscard]] Number
@@ -537,6 +588,9 @@ public:
friend Number
root2(Number f);
friend Number
power(Number const& f, unsigned n, unsigned d);
// Thread local rounding control. Default is to_nearest
enum class RoundingMode { ToNearest, TowardsZero, Downward, Upward };
@@ -546,16 +600,14 @@ public:
static RoundingMode
setround(RoundingMode inMode);
/**
* Returns which mantissa scale is currently in use for normalization.
/** Returns which mantissa scale is currently in use for normalization.
*
* If you think you need to call this outside of unit tests, no you don't.
*/
static MantissaRange::MantissaScale
getMantissaScale();
/**
* Changes which mantissa scale is used for normalization.
/** Changes which mantissa scale is used for normalization.
*
* If you think you need to call this outside of unit tests, no you don't.
*/
@@ -591,6 +643,25 @@ public:
std::pair<T, int>
normalizeToRange() const;
class Access
{
/** May use ranges that don't fit the restrictions of the "real"
* normalizeToRange().
*
*/
template <Integral64 T>
[[nodiscard]]
static std::pair<T, int>
normalizeToRangeImpl(
Number const& n,
T minMantissa,
T maxMantissa,
MantissaRange::CuspRoundingFix fix);
friend class Number;
friend class NumberTest;
};
private:
static thread_local RoundingMode mode;
// The available ranges for mantissa
@@ -600,17 +671,18 @@ private:
// changing the values inside the range.
static thread_local std::reference_wrapper<MantissaRange const> kRange;
class Guard;
// And one is needed because it needs to choose between oneSmall and
// oneLarge based on the current range
static Number
one(MantissaRange const& range);
static Number
root(MantissaRange const& range, Number f, unsigned d);
void
normalize(MantissaRange const& range);
// Guard has the fields that we need, as well as MantissaRange, so if we have a guard, use that
void
normalize(Guard const& guard);
/**
* Normalize Number components to an arbitrary range.
/** Normalize Number components to an arbitrary range.
*
* min/maxMantissa are parameters because this function is used by both
* normalize(), which reads from kRange, and by normalizeToRange,
@@ -624,7 +696,7 @@ private:
int& exponent,
internalrep const& minMantissa,
internalrep const& maxMantissa,
MantissaRange::CuspRoundingFix cuspRoundingFix);
MantissaRange::CuspRoundingFix cuspRoundingFixEnabled);
template <class T>
friend void
@@ -634,9 +706,13 @@ private:
int& exponent,
MantissaRange::rep const& minMantissa,
MantissaRange::rep const& maxMantissa,
MantissaRange::CuspRoundingFix cuspRoundingFix,
MantissaRange::CuspRoundingFix cuspRoundingFixEnabled,
bool dropped);
[[nodiscard]]
bool
isnormal(MantissaRange const& range) const noexcept;
[[nodiscard]] bool
isnormal() const noexcept;
@@ -646,16 +722,66 @@ private:
[[nodiscard]] Number
shiftExponent(int exponentDelta) const;
// Safely convert rep (int64) mantissa to internalrep (uint64). If the rep
// is negative, returns the positive value. This takes a little extra work
// because converting std::numeric_limits<std::int64_t>::min() flirts with
// UB, and can vary across compilers.
// Safely return the absolute value of a rep (int64) mantissa as an internalrep (uint64).
static internalrep
externalToInternal(rep mantissa);
/** Breaks down the number into components, potentially de-normalizing it.
*
* Ensures that the mantissa always has kRange.log + 1 digits.
*
*/
template <detail::UnsignedMantissa Rep = internalrep>
std::tuple<bool, Rep, int>
toInternal(MantissaRange const& range) const;
/** Breaks down the number into components, potentially de-normalizing it.
*
* Ensures that the mantissa always has kRange.log + 1 digits.
*
*/
template <detail::UnsignedMantissa Rep = internalrep>
std::tuple<bool, Rep, int>
toInternal() const;
/** Rebuilds the number from components.
*
* If "expectNormal" is true, the values are expected to be normalized - all
* in their valid ranges.
*
* If "expectNormal" is false, the values are expected to be "near
* normalized", meaning that the mantissa has to be modified at most once to
* bring it back into range.
*
*/
template <bool ExpectNormal = true, detail::UnsignedMantissa Rep = internalrep>
void
fromInternal(bool negative, Rep mantissa, int exponent, MantissaRange const* pRange);
/** Rebuilds the number from components.
*
* If "expectNormal" is true, the values are expected to be normalized - all
* in their valid ranges.
*
* If "expectNormal" is false, the values are expected to be "near
* normalized", meaning that the mantissa has to be modified at most once to
* bring it back into range.
*
*/
template <bool ExpectNormal = true, detail::UnsignedMantissa Rep = internalrep>
void
fromInternal(bool negative, Rep mantissa, int exponent);
class Guard;
public:
constexpr static internalrep kLargestMantissa =
MantissaRange{MantissaRange::MantissaScale::Large}.max;
};
constexpr Number::Number(bool negative, internalrep mantissa, int exponent, Unchecked) noexcept
: negative_(negative), mantissa_{mantissa}, exponent_{exponent}
: mantissa_{negative ? -static_cast<rep>(mantissa) : static_cast<rep>(mantissa)}
, exponent_{exponent}
{
}
@@ -666,12 +792,6 @@ constexpr Number::Number(internalrep mantissa, int exponent, Unchecked) noexcept
static constexpr Number kNumZero{};
inline Number::Number(bool negative, internalrep mantissa, int exponent, Normalized)
: Number(negative, mantissa, exponent, Unchecked{})
{
normalize(kRange);
}
inline Number::Number(internalrep mantissa, int exponent, Normalized)
: Number(false, mantissa, exponent, Normalized{})
{
@@ -686,8 +806,7 @@ inline Number::Number(rep mantissa) : Number{mantissa, 0}
{
}
/**
* Returns the mantissa of the external view of the Number.
/** Returns the mantissa of the external view of the Number.
*
* Please see the "---- External Interface ----" section of the class
* documentation for an explanation of why the internal value may be modified.
@@ -695,21 +814,10 @@ inline Number::Number(rep mantissa) : Number{mantissa, 0}
constexpr Number::rep
Number::mantissa() const noexcept
{
auto m = mantissa_;
if (m > kMaxRep)
{
XRPL_ASSERT_PARTS(
!isnormal() || (m % 10 == 0 && m / 10 <= kMaxRep),
"xrpl::Number::mantissa",
"large normalized mantissa has no remainder");
m /= 10;
}
auto const sign = negative_ ? -1 : 1;
return sign * static_cast<Number::rep>(m);
return mantissa_;
}
/**
* Returns the exponent of the external view of the Number.
/** Returns the exponent of the external view of the Number.
*
* Please see the "---- External Interface ----" section of the class
* documentation for an explanation of why the internal value may be modified.
@@ -717,16 +825,7 @@ Number::mantissa() const noexcept
constexpr int
Number::exponent() const noexcept
{
auto e = exponent_;
if (mantissa_ > kMaxRep)
{
XRPL_ASSERT_PARTS(
!isnormal() || (mantissa_ % 10 == 0 && mantissa_ / 10 <= kMaxRep),
"xrpl::Number::exponent",
"large normalized mantissa has no remainder");
++e;
}
return e;
return exponent_;
}
constexpr Number
@@ -741,7 +840,7 @@ Number::operator-() const noexcept
if (mantissa_ == 0)
return Number{};
auto x = *this;
x.negative_ = !x.negative_;
x.mantissa_ = -x.mantissa_;
return x;
}
@@ -822,23 +921,29 @@ Number::min() noexcept
inline Number
Number::max() noexcept
{
return Number{false, std::min(kRange.get().max, kMaxRep), kMaxExponent, Unchecked{}};
return Number{false, kRange.get().max, kMaxExponent, Unchecked{}};
}
inline Number
Number::lowest() noexcept
{
return Number{true, std::min(kRange.get().max, kMaxRep), kMaxExponent, Unchecked{}};
return Number{true, kRange.get().max, kMaxExponent, Unchecked{}};
}
inline bool
Number::isnormal(MantissaRange const& range) const noexcept
{
auto const absM = externalToInternal(mantissa_);
return *this == Number{} ||
(range.min <= absM && absM <= range.max && //
kMinExponent <= exponent_ && exponent_ <= kMaxExponent);
}
inline bool
Number::isnormal() const noexcept
{
MantissaRange const& range = kRange;
auto const absM = mantissa_;
return *this == Number{} ||
(range.min <= absM && absM <= range.max && (absM <= kMaxRep || absM % 10 == 0) &&
kMinExponent <= exponent_ && exponent_ <= kMaxExponent);
return isnormal(kRange);
}
template <auto MinMantissa, auto MaxMantissa, Integral64 T>
@@ -852,13 +957,34 @@ Number::normalizeToRange() const
auto constexpr kMAX = static_cast<T>(MaxMantissa);
static_assert(kMIN > 0);
static_assert(kMIN % 10 == 0);
static_assert(isPowerOfTen(kMIN));
static_assert(isPowerOfTen(static_cast<std::make_unsigned_t<T>>(kMIN)));
static_assert(kMAX % 10 == 9);
static_assert((kMAX + 1) / 10 == kMIN);
bool negative = negative_;
internalrep mantissa = mantissa_;
int exponent = exponent_;
// Don't need to worry about the cuspRounding fix because rounding up will never take the
// mantissa over maxMantissa with a ones digit value other than 0. 0 can safely be truncated.
return Access::normalizeToRangeImpl(
*this, kMIN, kMAX, MantissaRange::CuspRoundingFix::Disabled);
}
/** Only intended to be used in tests
*
* May use ranges that don't fit the restrictions of the "real"
* normalizeToRange().
*
*/
template <Integral64 T>
[[nodiscard]]
std::pair<T, int>
Number::Access::normalizeToRangeImpl(
Number const& n,
T minMantissa,
T maxMantissa,
MantissaRange::CuspRoundingFix fix)
{
bool negative = n.mantissa_ < 0;
internalrep mantissa = externalToInternal(n.mantissa_);
int exponent = n.exponent_;
if constexpr (std::is_unsigned_v<T>)
{
@@ -866,14 +992,21 @@ Number::normalizeToRange() const
!negative,
"xrpl::Number::normalizeToRange",
"Number is non-negative for unsigned range.");
// To avoid logical errors in release builds, throw if the Number is
// negative for an unsigned range.
if (negative)
{
throw std::runtime_error(
"Number::normalizeToRange: Number is negative for "
"unsigned range.");
}
}
// Don't need to worry about the cuspRounding fix because rounding up will never take the
// mantissa over maxMantissa with a ones digit value other than 0. 0 can safely be truncated.
Number::normalize(
negative, mantissa, exponent, kMIN, kMAX, MantissaRange::CuspRoundingFix::Disabled);
Number::normalize(negative, mantissa, exponent, minMantissa, maxMantissa, fix);
auto const sign = negative ? -1 : 1;
return std::make_pair(static_cast<T>(sign * mantissa), exponent);
// Cast mantissa to signed type first (if T is a signed type) to avoid
// unsigned integer overflow when multiplying by negative sign
T signedMantissa = negative ? -static_cast<T>(mantissa) : static_cast<T>(mantissa);
return std::make_pair(signedMantissa, exponent);
}
constexpr Number
@@ -915,11 +1048,21 @@ squelch(Number const& x, Number const& limit) noexcept
return x;
}
std::string
to_string(MantissaRange::MantissaScale const& scale);
std::string
to_string(Number::RoundingMode const& round);
inline std::string
to_string(MantissaRange::MantissaScale const& scale)
{
switch (scale)
{
case MantissaRange::MantissaScale::Small:
return "small";
case MantissaRange::MantissaScale::LargeLegacy:
return "largeLegacy";
case MantissaRange::MantissaScale::Large:
return "large";
default:
throw std::runtime_error("Bad scale");
}
}
class SaveNumberRoundMode
{
@@ -958,10 +1101,10 @@ public:
operator=(NumberRoundModeGuard const&) = delete;
};
/**
* Sets the new scale and restores the old scale when it leaves scope.
/** Sets the new scale and restores the old scale when it leaves scope.
*
* If you think you need to use this class outside of unit tests, no you don't.
*
*/
class NumberMantissaScaleGuard
{

View File

@@ -13,25 +13,23 @@
namespace xrpl {
/**
* A closed interval over the domain T.
*
* For an instance ClosedInterval c, this represents the closed interval
* (c.first(), c.last()). A single element interval has c.first() == c.last().
*
* This is simply a type-alias for boost interval container library interval
* set, so users should consult that documentation for available supporting
* member and free functions.
*/
/** A closed interval over the domain T.
For an instance ClosedInterval c, this represents the closed interval
(c.first(), c.last()). A single element interval has c.first() == c.last().
This is simply a type-alias for boost interval container library interval
set, so users should consult that documentation for available supporting
member and free functions.
*/
template <class T>
using ClosedInterval = boost::icl::closed_interval<T>;
/**
* Create a closed range interval
*
* Helper function to create a closed range interval without having to qualify
* the template argument.
*/
/** Create a closed range interval
Helper function to create a closed range interval without having to qualify
the template argument.
*/
template <class T>
ClosedInterval<T>
range(T low, T high)
@@ -39,30 +37,28 @@ range(T low, T high)
return ClosedInterval<T>(low, high);
}
/**
* A set of closed intervals over the domain T.
*
* Represents a set of values of the domain T using the minimum number
* of disjoint ClosedInterval<T>. This is useful to represent ranges of
* T where a few instances are missing, e.g. the set 1-5,8-9,11-14.
*
* This is simply a type-alias for boost interval container library interval
* set, so users should consult that documentation for available supporting
* member and free functions.
*/
/** A set of closed intervals over the domain T.
Represents a set of values of the domain T using the minimum number
of disjoint ClosedInterval<T>. This is useful to represent ranges of
T where a few instances are missing, e.g. the set 1-5,8-9,11-14.
This is simply a type-alias for boost interval container library interval
set, so users should consult that documentation for available supporting
member and free functions.
*/
template <class T>
using RangeSet = boost::icl::interval_set<T, std::less, ClosedInterval<T>>;
/**
* Convert a ClosedInterval to a styled string
*
* The styled string is
* "c.first()-c.last()" if c.first() != c.last()
* "c.first()" if c.first() == c.last()
*
* @param ci The closed interval to convert
* @return The style string
*/
/** Convert a ClosedInterval to a styled string
The styled string is
"c.first()-c.last()" if c.first() != c.last()
"c.first()" if c.first() == c.last()
@param ci The closed interval to convert
@return The style string
*/
template <class T>
std::string
to_string(ClosedInterval<T> const& ci)
@@ -72,15 +68,14 @@ to_string(ClosedInterval<T> const& ci)
return std::to_string(ci.first()) + "-" + std::to_string(ci.last());
}
/**
* Convert the given RangeSet to a styled string.
*
* The styled string representation is the set of disjoint intervals joined
* by commas. The string "empty" is returned if the set is empty.
*
* @param rs The rangeset to convert
* @return The styled string
*/
/** Convert the given RangeSet to a styled string.
The styled string representation is the set of disjoint intervals joined
by commas. The string "empty" is returned if the set is empty.
@param rs The rangeset to convert
@return The styled string
*/
template <class T>
std::string
to_string(RangeSet<T> const& rs)
@@ -96,16 +91,15 @@ to_string(RangeSet<T> const& rs)
return s;
}
/**
* Convert the given styled string to a RangeSet.
*
* The styled string representation is the set
* of disjoint intervals joined by commas.
*
* @param rs The set to be populated
* @param s The styled string to convert
* @return True on successfully converting styled string
*/
/** Convert the given styled string to a RangeSet.
The styled string representation is the set
of disjoint intervals joined by commas.
@param rs The set to be populated
@param s The styled string to convert
@return True on successfully converting styled string
*/
template <class T>
[[nodiscard]] bool
fromString(RangeSet<T>& rs, std::string const& s)
@@ -167,15 +161,14 @@ fromString(RangeSet<T>& rs, std::string const& s)
return result;
}
/**
* Find the largest value not in the set that is less than a given value.
*
* @param rs The set of interest
* @param t The value that must be larger than the result
* @param minVal (Default is 0) The smallest allowed value
* @return The largest v such that minV <= v < t and !contains(rs, v) or
* std::nullopt if no such v exists.
*/
/** Find the largest value not in the set that is less than a given value.
@param rs The set of interest
@param t The value that must be larger than the result
@param minVal (Default is 0) The smallest allowed value
@return The largest v such that minV <= v < t and !contains(rs, v) or
std::nullopt if no such v exists.
*/
template <class T>
std::optional<T>
prevMissing(RangeSet<T> const& rs, T t, T minVal = 0)

View File

@@ -15,29 +15,22 @@ public:
virtual ~Resolver() = 0;
/**
* Issue an asynchronous stop request.
*/
/** Issue an asynchronous stop request. */
virtual void
stopAsync() = 0;
/**
* Issue a synchronous stop request.
*/
/** Issue a synchronous stop request. */
virtual void
stop() = 0;
/**
* Issue a synchronous start request.
*/
/** Issue a synchronous start request. */
virtual void
start() = 0;
/**
* resolve all hostnames on the list
* @param names the names to be resolved
* @param handler the handler to call
*/
/** resolve all hostnames on the list
@param names the names to be resolved
@param handler the handler to call
*/
/** @{ */
template <class Handler>
void

View File

@@ -7,14 +7,13 @@
namespace xrpl {
/**
* A combination of a std::shared_ptr and a std::weak_pointer.
*
*
* This class is a wrapper to a `std::variant<std::shared_ptr,std::weak_ptr>`
* This class is useful for storing intrusive pointers in tagged caches using less
* memory than storing both pointers directly.
*/
/** A combination of a std::shared_ptr and a std::weak_pointer.
This class is a wrapper to a `std::variant<std::shared_ptr,std::weak_ptr>`
This class is useful for storing intrusive pointers in tagged caches using less
memory than storing both pointers directly.
*/
template <class T>
class SharedWeakCachePointer
@@ -49,79 +48,65 @@ public:
~SharedWeakCachePointer();
/**
* Return a strong pointer if this is already a strong pointer (i.e. don't
* lock the weak pointer. Use the `lock` method if that's what's needed)
/** Return a strong pointer if this is already a strong pointer (i.e. don't
lock the weak pointer. Use the `lock` method if that's what's needed)
*/
[[nodiscard]] std::shared_ptr<T> const&
getStrong() const;
/**
* Return true if this is a strong pointer and the strong pointer is
* seated.
/** Return true if this is a strong pointer and the strong pointer is
seated.
*/
explicit
operator bool() const noexcept;
/**
* Set the pointer to null, decrement the appropriate ref count, and run
* the appropriate release action.
/** Set the pointer to null, decrement the appropriate ref count, and run
the appropriate release action.
*/
void
reset();
/**
* If this is a strong pointer, return the raw pointer. Otherwise return
* null.
/** If this is a strong pointer, return the raw pointer. Otherwise return
null.
*/
[[nodiscard]] T*
get() const;
/**
* If this is a strong pointer, return the strong count. Otherwise return 0
/** If this is a strong pointer, return the strong count. Otherwise return 0
*/
[[nodiscard]] std::size_t
useCount() const;
/**
* Return true if there is a non-zero strong count.
*/
/** Return true if there is a non-zero strong count. */
[[nodiscard]] bool
expired() const;
/**
* If this is a strong pointer, return the strong pointer. Otherwise
* attempt to lock the weak pointer.
/** If this is a strong pointer, return the strong pointer. Otherwise
attempt to lock the weak pointer.
*/
[[nodiscard]] std::shared_ptr<T>
lock() const;
/**
* Return true is this represents a strong pointer.
*/
/** Return true is this represents a strong pointer. */
[[nodiscard]] bool
isStrong() const;
/**
* Return true is this represents a weak pointer.
*/
/** Return true is this represents a weak pointer. */
[[nodiscard]] bool
isWeak() const;
/**
* If this is a weak pointer, attempt to convert it to a strong pointer.
*
* @return true if successfully converted to a strong pointer (or was
* already a strong pointer). Otherwise false.
*/
/** If this is a weak pointer, attempt to convert it to a strong pointer.
@return true if successfully converted to a strong pointer (or was
already a strong pointer). Otherwise false.
*/
bool
convertToStrong();
/**
* If this is a strong pointer, attempt to convert it to a weak pointer.
*
* @return false if the pointer is null. Otherwise return true.
*/
/** If this is a strong pointer, attempt to convert it to a weak pointer.
@return false if the pointer is null. Otherwise return true.
*/
bool
convertToWeak();

View File

@@ -33,9 +33,7 @@ class SlabAllocator
static_assert(alignof(Type) == 8 || alignof(Type) == 4);
/**
* A block of memory that is owned by a slab allocator
*/
/** A block of memory that is owned by a slab allocator */
struct SlabBlock
{
// A mutex to protect the freelist for this block:
@@ -82,9 +80,7 @@ class SlabAllocator
SlabBlock&
operator=(SlabBlock&& other) = delete;
/**
* Determines whether the given pointer belongs to this allocator
*/
/** Determines whether the given pointer belongs to this allocator */
bool
own(std::uint8_t const* pIn) const noexcept
{
@@ -111,15 +107,14 @@ class SlabAllocator
return ret;
}
/**
* Return an item to this allocator's freelist.
*
* @param ptr The pointer to the chunk of memory being deallocated.
*
* @note This is a dangerous, private interface; the item being
* returned should belong to this allocator. Debug builds
* will check and assert if this is not the case. Release
* builds will not.
/** Return an item to this allocator's freelist.
@param ptr The pointer to the chunk of memory being deallocated.
@note This is a dangerous, private interface; the item being
returned should belong to this allocator. Debug builds
will check and assert if this is not the case. Release
builds will not.
*/
void
deallocate(std::uint8_t* ptr) noexcept
@@ -150,14 +145,13 @@ private:
std::size_t const slabSize_;
public:
/**
* Constructs a slab allocator able to allocate objects of a fixed size
*
* @param count the number of items the slab allocator can allocate; note
* that a count of 0 is valid and means that the allocator
* is, effectively, disabled. This can be very useful in some
* contexts (e.g. when minimal memory usage is needed) and
* allows for graceful failure.
/** Constructs a slab allocator able to allocate objects of a fixed size
@param count the number of items the slab allocator can allocate; note
that a count of 0 is valid and means that the allocator
is, effectively, disabled. This can be very useful in some
contexts (e.g. when minimal memory usage is needed) and
allows for graceful failure.
*/
constexpr explicit SlabAllocator(
std::size_t extra,
@@ -185,20 +179,17 @@ public:
// shutdown process up could make this possible.
~SlabAllocator() = default;
/**
* Returns the size of the memory block this allocator returns.
*/
/** Returns the size of the memory block this allocator returns. */
[[nodiscard]] constexpr std::size_t
size() const noexcept
{
return itemSize_;
}
/**
* Returns a suitably aligned pointer, if one is available.
*
* @return a pointer to a block of memory from the allocator, or
* nullptr if the allocator can't satisfy this request.
/** Returns a suitably aligned pointer, if one is available.
@return a pointer to a block of memory from the allocator, or
nullptr if the allocator can't satisfy this request.
*/
std::uint8_t*
allocate() noexcept
@@ -259,13 +250,12 @@ public:
return slab->allocate();
}
/**
* Returns the memory block to the allocator.
*
* @param ptr A pointer to a memory block.
* @param size If non-zero, a hint as to the size of the block.
* @return true if this memory block belonged to the allocator and has
* been released; false otherwise.
/** Returns the memory block to the allocator.
@param ptr A pointer to a memory block.
@param size If non-zero, a hint as to the size of the block.
@return true if this memory block belonged to the allocator and has
been released; false otherwise.
*/
bool
deallocate(std::uint8_t* ptr) noexcept
@@ -288,9 +278,7 @@ public:
}
};
/**
* A collection of slab allocators of various sizes for a given type.
*/
/** A collection of slab allocators of various sizes for a given type. */
template <typename Type>
class SlabAllocatorSet
{
@@ -357,14 +345,13 @@ public:
~SlabAllocatorSet() = default;
/**
* Returns a suitably aligned pointer, if one is available.
*
* @param extra The number of extra bytes, above and beyond the size of
* the object, that should be returned by the allocator.
*
* @return a pointer to a block of memory, or nullptr if the allocator
* can't satisfy this request.
/** Returns a suitably aligned pointer, if one is available.
@param extra The number of extra bytes, above and beyond the size of
the object, that should be returned by the allocator.
@return a pointer to a block of memory, or nullptr if the allocator
can't satisfy this request.
*/
std::uint8_t*
allocate(std::size_t extra) noexcept
@@ -381,13 +368,12 @@ public:
return nullptr;
}
/**
* Returns the memory block to the allocator.
*
* @param ptr A pointer to a memory block.
*
* @return true if this memory block belonged to one of the allocators
* in this set and has been released; false otherwise.
/** Returns the memory block to the allocator.
@param ptr A pointer to a memory block.
@return true if this memory block belonged to one of the allocators
in this set and has been released; false otherwise.
*/
bool
deallocate(std::uint8_t* ptr) noexcept

View File

@@ -16,13 +16,12 @@
namespace xrpl {
/**
* An immutable linear range of bytes.
*
* A fully constructed Slice is guaranteed to be in a valid state.
* A Slice is lightweight and copyable, it retains no ownership
* of the underlying memory.
*/
/** An immutable linear range of bytes.
A fully constructed Slice is guaranteed to be in a valid state.
A Slice is lightweight and copyable, it retains no ownership
of the underlying memory.
*/
class Slice
{
private:
@@ -33,37 +32,30 @@ public:
using value_type = std::uint8_t;
using const_iterator = value_type const*;
/**
* Default constructed Slice has length 0.
*/
/** Default constructed Slice has length 0. */
Slice() noexcept = default;
Slice(Slice const&) noexcept = default;
Slice&
operator=(Slice const&) noexcept = default;
/**
* Create a slice pointing to existing memory.
*/
/** Create a slice pointing to existing memory. */
Slice(void const* data, std::size_t size) noexcept
: data_(reinterpret_cast<std::uint8_t const*>(data)), size_(size)
{
}
/**
* Return `true` if the byte range is empty.
*/
/** Return `true` if the byte range is empty. */
[[nodiscard]] bool
empty() const noexcept
{
return size_ == 0;
}
/**
* Returns the number of bytes in the storage.
*
* This may be zero for an empty range.
*/
/** Returns the number of bytes in the storage.
This may be zero for an empty range.
*/
/** @{ */
[[nodiscard]] std::size_t
size() const noexcept
@@ -78,20 +70,17 @@ public:
}
/** @} */
/**
* Return a pointer to beginning of the storage.
* @note The return type is guaranteed to be a pointer
* to a single byte, to facilitate pointer arithmetic.
*/
/** Return a pointer to beginning of the storage.
@note The return type is guaranteed to be a pointer
to a single byte, to facilitate pointer arithmetic.
*/
[[nodiscard]] std::uint8_t const*
data() const noexcept
{
return data_;
}
/**
* Access raw bytes.
*/
/** Access raw bytes. */
std::uint8_t
operator[](std::size_t i) const noexcept
{
@@ -99,9 +88,7 @@ public:
return data_[i];
}
/**
* Advance the buffer.
*/
/** Advance the buffer. */
/** @{ */
Slice&
operator+=(std::size_t n)
@@ -121,9 +108,7 @@ public:
}
/** @} */
/**
* Shrinks the slice by moving its start forward by n characters.
*/
/** Shrinks the slice by moving its start forward by n characters. */
void
removePrefix(std::size_t n)
{
@@ -131,9 +116,7 @@ public:
size_ -= n;
}
/**
* Shrinks the slice by moving its end backward by n characters.
*/
/** Shrinks the slice by moving its end backward by n characters. */
void
removeSuffix(std::size_t n)
{
@@ -164,17 +147,16 @@ public:
return data_ + size_;
}
/**
* Return a "sub slice" of given length starting at the given position
*
* Note that the subslice encompasses the range [pos, pos + rCount),
* where rCount is the smaller of count and size() - pos.
*
* @param pos position of the first character
* @count requested length
*
* @return The requested subslice, if the request is valid.
* @throws std::out_of_range if pos > size()
/** Return a "sub slice" of given length starting at the given position
Note that the subslice encompasses the range [pos, pos + rCount),
where rCount is the smaller of count and size() - pos.
@param pos position of the first character
@count requested length
@returns The requested subslice, if the request is valid.
@throws std::out_of_range if pos > size()
*/
[[nodiscard]] Slice
substr(std::size_t pos, std::size_t count = std::numeric_limits<std::size_t>::max()) const

View File

@@ -17,16 +17,15 @@
namespace xrpl {
/**
* Format arbitrary binary data as an SQLite "blob literal".
*
* In SQLite, blob literals must be encoded when used in a query. Per
* https://sqlite.org/lang_expr.html#literal_values_constants_ they are
* encoded as string literals containing hexadecimal data and preceded
* by a single 'X' character.
*
* @param blob An arbitrary blob of binary data
* @return The input, encoded as a blob literal.
/** Format arbitrary binary data as an SQLite "blob literal".
In SQLite, blob literals must be encoded when used in a query. Per
https://sqlite.org/lang_expr.html#literal_values_constants_ they are
encoded as string literals containing hexadecimal data and preceded
by a single 'X' character.
@param blob An arbitrary blob of binary data
@return The input, encoded as a blob literal.
*/
std::string
sqlBlobLiteral(Blob const& blob);
@@ -131,12 +130,11 @@ trimWhitespace(std::string str);
std::optional<std::uint64_t>
toUInt64(std::string const& s);
/**
* Determines if the given string looks like a TOML-file hosting domain.
*
* Do not use this function to determine if a particular string is a valid
* domain, as this function may reject domains that are otherwise valid and
* doesn't check whether the TLD is valid.
/** Determines if the given string looks like a TOML-file hosting domain.
Do not use this function to determine if a particular string is a valid
domain, as this function may reject domains that are otherwise valid and
doesn't check whether the TLD is valid.
*/
bool
isProperlyFormedTomlDomain(std::string_view domain);

View File

@@ -41,19 +41,18 @@ struct ReplaceDynamically;
} // namespace detail
/**
* Map/cache combination.
* This class implements a cache and a map. The cache keeps objects alive
* in the map. The map allows multiple code paths that reference objects
* with the same tag to get the same actual object.
*
* So long as data is in the cache, it will stay in memory.
* If it stays in memory even after it is ejected from the cache,
* the map will track it.
*
* @note Callers must not modify data objects that are stored in the cache
* unless they hold their own lock over all cache operations.
*/
/** Map/cache combination.
This class implements a cache and a map. The cache keeps objects alive
in the map. The map allows multiple code paths that reference objects
with the same tag to get the same actual object.
So long as data is in the cache, it will stay in memory.
If it stays in memory even after it is ejected from the cache,
the map will track it.
@note Callers must not modify data objects that are stored in the cache
unless they hold their own lock over all cache operations.
*/
template <
class Key,
class T,
@@ -83,15 +82,11 @@ public:
beast::insight::Collector::ptr const& collector = beast::insight::NullCollector::make());
public:
/**
* Return the clock associated with the cache.
*/
/** Return the clock associated with the cache. */
clock_type&
clock();
/**
* Returns the number of items in the container.
*/
/** Returns the number of items in the container. */
std::size_t
size() const;
@@ -110,10 +105,9 @@ public:
void
reset();
/**
* Refresh the last access time on a key if present.
* @return `true` If the key was found.
*/
/** Refresh the last access time on a key if present.
@return `true` If the key was found.
*/
template <class KeyComparable>
bool
touchIfExists(KeyComparable const& key);
@@ -136,15 +130,14 @@ private:
SharedPointerType const&,
SharedPointerType&>;
/**
* Shared implementation of the canonicalize family.
*
* `policy` selects how a collision is resolved when `key` already exists:
* detail::ReplaceCached, detail::ReplaceClient or
* detail::ReplaceDynamically. For ReplaceDynamically `replaceCallback` is
* invoked with the existing strong pointer and returns whether to replace
* the cached value with `data`; for the tag policies it is unused.
*/
/** Shared implementation of the canonicalize family.
`policy` selects how a collision is resolved when `key` already exists:
detail::ReplaceCached, detail::ReplaceClient or
detail::ReplaceDynamically. For ReplaceDynamically `replaceCallback` is
invoked with the existing strong pointer and returns whether to replace
the cached value with `data`; for the tag policies it is unused.
*/
template <class Policy, class Callback = std::nullptr_t>
bool
canonicalizeImpl(
@@ -154,73 +147,69 @@ private:
Callback&& replaceCallback = nullptr);
public:
/**
* Replace aliased objects with originals.
*
* Due to concurrency it is possible for two separate objects with
* the same content and referring to the same unique "thing" to exist.
* This routine eliminates the duplicate and performs a replacement
* on the callers shared pointer if needed.
*
* `replaceCallback` is a callable taking the existing strong pointer and
* returning whether to replace the cached value with `data` (true) or to
* keep the cached value and write it back into `data` (false). Because the
* write-back case mutates `data`, `data` must be writable.
*
* @param key The key corresponding to the object
* @param data A shared pointer to the data corresponding to the object.
* @param replaceCallback A callable (existing strong pointer -> bool).
*
* @return `true` if an existing live entry was found and used; `false` if a new entry was
* inserted or an expired tracked entry was re-cached.
*/
/** Replace aliased objects with originals.
Due to concurrency it is possible for two separate objects with
the same content and referring to the same unique "thing" to exist.
This routine eliminates the duplicate and performs a replacement
on the callers shared pointer if needed.
`replaceCallback` is a callable taking the existing strong pointer and
returning whether to replace the cached value with `data` (true) or to
keep the cached value and write it back into `data` (false). Because the
write-back case mutates `data`, `data` must be writable.
@param key The key corresponding to the object
@param data A shared pointer to the data corresponding to the object.
@param replaceCallback A callable (existing strong pointer -> bool).
@return `true` if an existing live entry was found and used; `false` if a new entry was
inserted or an expired tracked entry was re-cached.
**/
template <class Callback>
bool
canonicalize(key_type const& key, SharedPointerType& data, Callback&& replaceCallback);
/**
* Insert/update the canonical entry for `key`, always replacing the
* cached value with `data`.
*
* If an entry already exists for `key`, the cached value is unconditionally
* replaced with `data`; otherwise `data` is inserted. `data` is never
* written back, so it may be const.
*
* @param key The key corresponding to the object.
* @param data A shared pointer to the data corresponding to the object.
*
* @return `true` if an existing live entry was found and used; `false` if a new entry was
* inserted or an expired tracked entry was re-cached.
*/
/** Insert/update the canonical entry for `key`, always replacing the
cached value with `data`.
If an entry already exists for `key`, the cached value is unconditionally
replaced with `data`; otherwise `data` is inserted. `data` is never
written back, so it may be const.
@param key The key corresponding to the object.
@param data A shared pointer to the data corresponding to the object.
@return `true` if an existing live entry was found and used; `false` if a new entry was
inserted or an expired tracked entry was re-cached.
**/
bool
canonicalizeReplaceCache(key_type const& key, SharedPointerType const& data);
/**
* Insert the canonical entry for `key`, keeping any existing cached value.
*
* If an entry already exists for `key`, the cached value is kept and
* written back into `data` so the caller ends up with the canonical
* object; otherwise `data` is inserted. Because `data` may be overwritten
* it must be writable.
*
* @param key The key corresponding to the object.
* @param data A shared pointer to the data corresponding to the object;
* updated to the canonical value when one already exists.
*
* @return `true` if an existing live entry was found and used; `false` if a new entry was
* inserted or an expired tracked entry was re-cached.
*/
/** Insert the canonical entry for `key`, keeping any existing cached value.
If an entry already exists for `key`, the cached value is kept and
written back into `data` so the caller ends up with the canonical
object; otherwise `data` is inserted. Because `data` may be overwritten
it must be writable.
@param key The key corresponding to the object.
@param data A shared pointer to the data corresponding to the object;
updated to the canonical value when one already exists.
@return `true` if an existing live entry was found and used; `false` if a new entry was
inserted or an expired tracked entry was re-cached.
**/
bool
canonicalizeReplaceClient(key_type const& key, SharedPointerType& data);
SharedPointerType
fetch(key_type const& key);
/**
* Insert the element into the container.
* If the key already exists, nothing happens.
* @return `true` If the element was inserted
*/
/** Insert the element into the container.
If the key already exists, nothing happens.
@return `true` If the element was inserted
*/
template <class ReturnType = bool>
auto
insert(key_type const& key, T const& value) -> ReturnType
@@ -246,18 +235,15 @@ public:
getKeys() const;
// CachedSLEs functions.
/**
* Returns the fraction of cache hits.
*/
/** Returns the fraction of cache hits. */
double
rate() const;
/**
* Fetch an item from the cache.
* If the digest was not found, Handler
* will be called with this signature:
* SLE::const_pointer(void)
*/
/** Fetch an item from the cache.
If the digest was not found, Handler
will be called with this signature:
SLE::const_pointer(void)
*/
template <class Handler>
SharedPointerType
fetch(key_type const& digest, Handler const& h);

View File

@@ -5,11 +5,10 @@
namespace xrpl {
/**
* to_string() generalizes std::to_string to handle bools, chars, and strings.
*
* It's also possible to provide implementation of to_string for a class
* which needs a string implementation.
/** to_string() generalizes std::to_string to handle bools, chars, and strings.
It's also possible to provide implementation of to_string for a class
which needs a string implementation.
*/
template <class T>

View File

@@ -7,13 +7,12 @@
namespace xrpl {
/**
* Tracks program uptime to seconds precision.
*
* The timer caches the current time as a performance optimization.
* This allows clients to query the current time thousands of times
* per second.
*/
/** Tracks program uptime to seconds precision.
The timer caches the current time as a performance optimization.
This allows clients to query the current time thousands of times
per second.
*/
class UptimeClock
{

View File

@@ -63,19 +63,18 @@ struct AlwaysFalseT : std::bool_constant<false>
} // namespace detail
/**
* Integers of any length that is a multiple of 32-bits
*
* @note This class stores its values internally in big-endian
* form and that internal representation is part of the
* binary protocol of the XRP Ledger and cannot be changed
* arbitrarily without causing breakage.
*
* @tparam Bits The number of bits this integer should have; must
* be at least 64 and a multiple of 32.
* @tparam Tag An arbitrary type that functions as a tag and allows
* the instantiation of "distinct" types that the same
* number of bits.
/** Integers of any length that is a multiple of 32-bits
@note This class stores its values internally in big-endian
form and that internal representation is part of the
binary protocol of the XRP Ledger and cannot be changed
arbitrarily without causing breakage.
@tparam Bits The number of bits this integer should have; must
be at least 64 and a multiple of 32.
@tparam Tag An arbitrary type that functions as a tag and allows
the instantiation of "distinct" types that the same
number of bits.
*/
template <std::size_t Bits, class Tag = void>
class BaseUInt
@@ -155,23 +154,21 @@ public:
return data() + kBytes;
}
/**
* Value hashing function.
* The seed prevents crafted inputs from causing degenerate parent
* containers.
*/
/** Value hashing function.
The seed prevents crafted inputs from causing degenerate parent
containers.
*/
using hasher = HardenedHash<>;
//--------------------------------------------------------------------------
private:
/**
* Construct from a raw pointer.
* The buffer pointed to by `data` must be at least Bits/8 bytes.
*
* @note the structure is used to disambiguate this from the std::uint64_t
* constructor: something like base_uint(0) is ambiguous.
*/
/** Construct from a raw pointer.
The buffer pointed to by `data` must be at least Bits/8 bytes.
@note the structure is used to disambiguate this from the std::uint64_t
constructor: something like base_uint(0) is ambiguous.
*/
// NIKB TODO Remove the need for this constructor.
struct VoidHelper
{
@@ -506,14 +503,13 @@ public:
h(a.data_.data(), sizeof(a.data_));
}
/**
* Parse a hex string into a base_uint
*
* The input must be precisely `2 * bytes` hexadecimal characters
* long, with one exception: the value '0'.
*
* @param sv A null-terminated string of hexadecimal characters
* @return true if the input was parsed properly; false otherwise.
/** Parse a hex string into a base_uint
The input must be precisely `2 * bytes` hexadecimal characters
long, with one exception: the value '0'.
@param sv A null-terminated string of hexadecimal characters
@return true if the input was parsed properly; false otherwise.
*/
[[nodiscard]] constexpr bool
parseHex(std::string_view sv)
@@ -599,7 +595,7 @@ template <std::size_t Bits, typename Tag>
[[nodiscard]] constexpr bool
operator==(BaseUInt<Bits, Tag> const& lhs, BaseUInt<Bits, Tag> const& rhs)
{
return (lhs <=> rhs) == 0; // NOLINT(modernize-use-nullptr)
return (lhs <=> rhs) == 0;
}
//------------------------------------------------------------------------------

View File

@@ -21,16 +21,15 @@ using days =
using weeks = std::chrono::duration<int, std::ratio_multiply<days::period, std::ratio<7>>>;
/**
* Clock for measuring the network time.
*
* The epoch is January 1, 2000
*
* epoch_offset
* = date(2000-01-01) - date(1970-0-01)
* = days(10957)
* = seconds(946684800)
*/
/** Clock for measuring the network time.
The epoch is January 1, 2000
epoch_offset
= date(2000-01-01) - date(1970-0-01)
= days(10957)
= seconds(946684800)
*/
static constexpr std::chrono::seconds kEpochOffset =
date::sys_days{date::year{2000} / 1 / 1} - date::sys_days{date::year{1970} / 1 / 1};
@@ -82,21 +81,16 @@ toStringIso(NetClock::time_point tp)
return toStringIso(date::sys_time<NetClock::duration>{tp.time_since_epoch() + kEpochOffset});
}
/**
* A clock for measuring elapsed time.
*
* The epoch is unspecified.
*/
/** A clock for measuring elapsed time.
The epoch is unspecified.
*/
using Stopwatch = beast::AbstractClock<std::chrono::steady_clock>;
/**
* A manual Stopwatch for unit tests.
*/
/** A manual Stopwatch for unit tests. */
using TestStopwatch = beast::ManualClock<std::chrono::steady_clock>;
/**
* Returns an instance of a wall clock.
*/
/** Returns an instance of a wall clock. */
inline Stopwatch&
stopwatch()
{

View File

@@ -15,23 +15,20 @@ namespace xrpl {
preconditions, postconditions, and invariants.
*/
/**
* Generates and logs a call stack
*/
/** Generates and logs a call stack */
void
logThrow(std::string const& title);
/**
* Rethrow the exception currently being handled.
*
* When called from within a catch block, it will pass
* control to the next matching exception handler, if any.
* Otherwise, std::terminate will be called.
*
* ASAN can't handle sudden jumps in control flow very well. This
* function is marked as XRPL_NO_SANITIZE_ADDRESS to prevent it from
* triggering false positives, since it throws.
*/
/** Rethrow the exception currently being handled.
When called from within a catch block, it will pass
control to the next matching exception handler, if any.
Otherwise, std::terminate will be called.
ASAN can't handle sudden jumps in control flow very well. This
function is marked as XRPL_NO_SANITIZE_ADDRESS to prevent it from
triggering false positives, since it throws.
*/
[[noreturn]] XRPL_NO_SANITIZE_ADDRESS inline void
rethrow()
{
@@ -59,9 +56,7 @@ Throw(Args&&... args)
throw std::move(e);
}
/**
* Called when faulty logic causes a broken invariant.
*/
/** Called when faulty logic causes a broken invariant. */
[[noreturn]] void
logicError(std::string const& how) noexcept;

View File

@@ -39,33 +39,33 @@ makeSeedPair() noexcept
/**
* Seed functor once per construction
*
* A std compatible hash adapter that resists adversarial inputs.
* For this to work, T must implement in its own namespace:
*
* @code
*
* template <class Hasher>
* void
* hash_append (Hasher& h, T const& t) noexcept
* {
* // hash_append each base and member that should
* // participate in forming the hash
* using beast::hash_append;
* hash_append (h, static_cast<T::base1 const&>(t));
* hash_append (h, static_cast<T::base2 const&>(t));
* // ...
* hash_append (h, t.member1);
* hash_append (h, t.member2);
* // ...
* }
*
* @endcode
*
* Do not use any version of Murmur or CityHash for the Hasher
* template parameter (the hashing algorithm). For details
* see https://131002.net/siphash/#at
*/
A std compatible hash adapter that resists adversarial inputs.
For this to work, T must implement in its own namespace:
@code
template <class Hasher>
void
hash_append (Hasher& h, T const& t) noexcept
{
// hash_append each base and member that should
// participate in forming the hash
using beast::hash_append;
hash_append (h, static_cast<T::base1 const&>(t));
hash_append (h, static_cast<T::base2 const&>(t));
// ...
hash_append (h, t.member1);
hash_append (h, t.member2);
// ...
}
@endcode
Do not use any version of Murmur or CityHash for the Hasher
template parameter (the hashing algorithm). For details
see https://131002.net/siphash/#at
*/
template <class HashAlgorithm = beast::Xxhasher>
class HardenedHash

View File

@@ -7,15 +7,11 @@
namespace xrpl {
/**
* Create a self-signed SSL context that allows anonymous Diffie Hellman.
*/
/** Create a self-signed SSL context that allows anonymous Diffie Hellman. */
std::shared_ptr<boost::asio::ssl::context>
makeSslContext(std::string const& cipherList);
/**
* Create an authenticated SSL context using the specified files.
*/
/** Create an authenticated SSL context using the specified files. */
std::shared_ptr<boost::asio::ssl::context>
makeSslContextAuthed(
std::string const& keyFile,

View File

@@ -7,16 +7,16 @@
namespace xrpl {
constexpr auto kMuldivMax = std::numeric_limits<std::uint64_t>::max();
/**
* Return value*mul/div accurately.
*
* Computes the result of the multiplication and division in
* a single step, avoiding overflow and retaining precision.
*
* @throws None
* @return `std::nullopt` if the calculation overflows. Otherwise,
* `value * mul / div`.
*/
/** Return value*mul/div accurately.
Computes the result of the multiplication and division in
a single step, avoiding overflow and retaining precision.
Throws:
None
Returns:
`std::optional`:
`std::nullopt` if the calculation overflows. Otherwise, `value * mul
/ div`.
*/
std::optional<std::uint64_t>
mulDiv(std::uint64_t value, std::uint64_t mul, std::uint64_t div);

View File

@@ -33,17 +33,16 @@ template <class Engine, class Result = typename Engine::result_type>
using is_engine = std::is_invocable_r<Result, Engine>;
} // namespace detail
/**
* Return the default random engine.
*
* This engine is guaranteed to be deterministic, but by
* default will be randomly seeded. It is NOT cryptographically
* secure and MUST NOT be used to generate randomness that
* will be used for keys, secure cookies, IVs, padding, etc.
*
* Each thread gets its own instance of the engine which
* will be randomly seeded.
*/
/** Return the default random engine.
This engine is guaranteed to be deterministic, but by
default will be randomly seeded. It is NOT cryptographically
secure and MUST NOT be used to generate randomness that
will be used for keys, secure cookies, IVs, padding, etc.
Each thread gets its own instance of the engine which
will be randomly seeded.
*/
inline beast::xor_shift_engine&
defaultPrng()
{
@@ -71,26 +70,25 @@ defaultPrng()
return kEngine;
}
/**
* Return a uniformly distributed random integer.
*
* @param min The smallest value to return. If not specified
* the value defaults to 0.
* @param max The largest value to return. If not specified
* the value defaults to the largest value that
* can be represented.
*
* The randomness is generated by the specified engine (or
* the default engine if one is not specified). The result
* is cryptographically secure only when the engine passed
* into the function is cryptographically secure.
*
* @note The range is always a closed interval, so calling
* rand_int(-5, 15) can return any integer in the
* closed interval [-5, 15]; similarly, calling
* rand_int(7) can return any integer in the closed
* interval [0, 7].
*/
/** Return a uniformly distributed random integer.
@param min The smallest value to return. If not specified
the value defaults to 0.
@param max The largest value to return. If not specified
the value defaults to the largest value that
can be represented.
The randomness is generated by the specified engine (or
the default engine if one is not specified). The result
is cryptographically secure only when the engine passed
into the function is cryptographically secure.
@note The range is always a closed interval, so calling
rand_int(-5, 15) can return any integer in the
closed interval [-5, 15]; similarly, calling
rand_int(7) can return any integer in the closed
interval [0, 7].
*/
/** @{ */
template <class Engine, class Integral>
Integral
@@ -146,9 +144,7 @@ randInt()
}
/** @} */
/**
* Return a random byte
*/
/** Return a random byte */
/** @{ */
template <class Byte, class Engine>
Byte
@@ -170,9 +166,7 @@ randByte()
}
/** @} */
/**
* Return a random boolean value
*/
/** Return a random boolean value */
/** @{ */
template <class Engine>
inline bool

View File

@@ -156,41 +156,41 @@ template <class EF>
ScopeSuccess(EF) -> ScopeSuccess<EF>;
/**
* Automatically unlocks and re-locks a unique_lock object.
*
* This is the reverse of a std::unique_lock object - instead of locking the
* mutex for the lifetime of this object, it unlocks it.
*
* Make sure you don't try to unlock mutexes that aren't actually locked!
*
* This is essentially a less-versatile boost::reverse_lock.
*
* e.g. @code
*
* std::mutex mut;
*
* for (;;)
* {
* std::unique_lock myScopedLock{mut};
* // mut is now locked
*
* ... do some stuff with it locked ..
*
* while (xyz)
* {
* ... do some stuff with it locked ..
*
* scope_unlock unlocker{myScopedLock};
*
* // mut is now unlocked for the remainder of this block,
* // and re-locked at the end.
*
* ...do some stuff with it unlocked ...
* } // mut gets locked here.
*
* } // mut gets unlocked here
* @endcode
*/
Automatically unlocks and re-locks a unique_lock object.
This is the reverse of a std::unique_lock object - instead of locking the
mutex for the lifetime of this object, it unlocks it.
Make sure you don't try to unlock mutexes that aren't actually locked!
This is essentially a less-versatile boost::reverse_lock.
e.g. @code
std::mutex mut;
for (;;)
{
std::unique_lock myScopedLock{mut};
// mut is now locked
... do some stuff with it locked ..
while (xyz)
{
... do some stuff with it locked ..
scope_unlock unlocker{myScopedLock};
// mut is now unlocked for the remainder of this block,
// and re-locked at the end.
...do some stuff with it unlocked ...
} // mut gets locked here.
} // mut gets unlocked here
@endcode
*/
template <class Mutex>
class ScopeUnlock

View File

@@ -15,16 +15,15 @@
namespace xrpl {
namespace detail {
/**
* Inform the processor that we are in a tight spin-wait loop.
*
* Spinlocks caught in tight loops can result in the processor's pipeline
* filling up with comparison operations, resulting in a misprediction at
* the time the lock is finally acquired, necessitating pipeline flushing
* which is ridiculously expensive and results in very high latency.
*
* This function instructs the processor to "pause" for some architecture
* specific amount of time, to prevent this.
/** Inform the processor that we are in a tight spin-wait loop.
Spinlocks caught in tight loops can result in the processor's pipeline
filling up with comparison operations, resulting in a misprediction at
the time the lock is finally acquired, necessitating pipeline flushing
which is ridiculously expensive and results in very high latency.
This function instructs the processor to "pause" for some architecture
specific amount of time, to prevent this.
*/
inline void
spinPause() noexcept
@@ -39,39 +38,37 @@ spinPause() noexcept
} // namespace detail
/** @{ */
/**
* Classes to handle arrays of spinlocks packed into a single atomic integer:
*
* Packed spinlocks allow for tremendously space-efficient lock-sharding
* but they come at a cost.
*
* First, the implementation is necessarily low-level and uses advanced
* features like memory ordering and highly platform-specific tricks to
* maximize performance. This imposes a significant and ongoing cost to
* developers.
*
* Second, and perhaps most important, is that the packing of multiple
* locks into a single integer which, albeit space-efficient, also has
* performance implications stemming from data dependencies, increased
* cache-coherency traffic between processors and heavier loads on the
* processor's load/store units.
*
* To be sure, these locks can have advantages but they are definitely
* not general purpose locks and should not be thought of or used that
* way. The use cases for them are likely few and far between; without
* a compelling reason to use them, backed by profiling data, it might
* be best to use one of the standard locking primitives instead. Note
* that in most common platforms, `std::mutex` is so heavily optimized
* that it can, usually, outperform spinlocks.
*
* @tparam T An unsigned integral type (e.g. std::uint16_t)
/** Classes to handle arrays of spinlocks packed into a single atomic integer:
Packed spinlocks allow for tremendously space-efficient lock-sharding
but they come at a cost.
First, the implementation is necessarily low-level and uses advanced
features like memory ordering and highly platform-specific tricks to
maximize performance. This imposes a significant and ongoing cost to
developers.
Second, and perhaps most important, is that the packing of multiple
locks into a single integer which, albeit space-efficient, also has
performance implications stemming from data dependencies, increased
cache-coherency traffic between processors and heavier loads on the
processor's load/store units.
To be sure, these locks can have advantages but they are definitely
not general purpose locks and should not be thought of or used that
way. The use cases for them are likely few and far between; without
a compelling reason to use them, backed by profiling data, it might
be best to use one of the standard locking primitives instead. Note
that in most common platforms, `std::mutex` is so heavily optimized
that it can, usually, outperform spinlocks.
@tparam T An unsigned integral type (e.g. std::uint16_t)
*/
/**
* A class that grabs a single packed spinlock from an atomic integer.
*
* This class meets the requirements of Lockable:
* https://en.cppreference.com/w/cpp/named_req/Lockable
/** A class that grabs a single packed spinlock from an atomic integer.
This class meets the requirements of Lockable:
https://en.cppreference.com/w/cpp/named_req/Lockable
*/
template <class T>
class PackedSpinlock
@@ -94,14 +91,13 @@ public:
PackedSpinlock&
operator=(PackedSpinlock const&) = delete;
/**
* A single spinlock packed inside the specified atomic
*
* @param lock The atomic integer inside which the spinlock is packed.
* @param index The index of the spinlock this object acquires.
*
* @note For performance reasons, you should strive to have `lock` be
* on a cacheline by itself.
/** A single spinlock packed inside the specified atomic
@param lock The atomic integer inside which the spinlock is packed.
@param index The index of the spinlock this object acquires.
@note For performance reasons, you should strive to have `lock` be
on a cacheline by itself.
*/
PackedSpinlock(std::atomic<T>& lock, int index) : bits_(lock), mask_(static_cast<T>(1) << index)
{
@@ -137,18 +133,17 @@ public:
}
};
/**
* A spinlock implemented on top of an atomic integer.
*
* @note Using `packed_spinlock` and `spinlock` against the same underlying
* atomic integer can result in `spinlock` not being able to actually
* acquire the lock during periods of high contention, because of how
* the two locks operate: `spinlock` will spin trying to grab all the
* bits at once, whereas any given `packed_spinlock` will only try to
* grab one bit at a time. Caveat emptor.
*
* This class meets the requirements of Lockable:
* https://en.cppreference.com/w/cpp/named_req/Lockable
/** A spinlock implemented on top of an atomic integer.
@note Using `packed_spinlock` and `spinlock` against the same underlying
atomic integer can result in `spinlock` not being able to actually
acquire the lock during periods of high contention, because of how
the two locks operate: `spinlock` will spin trying to grab all the
bits at once, whereas any given `packed_spinlock` will only try to
grab one bit at a time. Caveat emptor.
This class meets the requirements of Lockable:
https://en.cppreference.com/w/cpp/named_req/Lockable
*/
template <class T>
class Spinlock
@@ -164,13 +159,12 @@ public:
Spinlock&
operator=(Spinlock const&) = delete;
/**
* Grabs the
*
* @param lock The atomic integer to spin against.
*
* @note For performance reasons, you should strive to have `lock` be
* on a cacheline by itself.
/** Grabs the
@param lock The atomic integer to spin against.
@note For performance reasons, you should strive to have `lock` be
on a cacheline by itself.
*/
Spinlock(std::atomic<T>& lock) : lock_(lock)
{

View File

@@ -12,18 +12,17 @@
namespace xrpl {
/**
* A type-safe wrap around standard integral types
*
* The tag is used to implement type safety, catching mismatched types at
* compile time. Multiple instantiations wrapping the same underlying integral
* type are distinct types (distinguished by tag) and will not interoperate. A
* tagged_integer supports all the usual assignment, arithmetic, comparison and
* shifting operations defined for the underlying type
*
* The tag is not meant as a unit, which would require restricting the set of
* allowed arithmetic operations.
*/
/** A type-safe wrap around standard integral types
The tag is used to implement type safety, catching mismatched types at
compile time. Multiple instantiations wrapping the same underlying integral
type are distinct types (distinguished by tag) and will not interoperate. A
tagged_integer supports all the usual assignment, arithmetic, comparison and
shifting operations defined for the underlying type
The tag is not meant as a unit, which would require restricting the set of
allowed arithmetic operations.
*/
template <class Int, class Tag>
class TaggedInteger : boost::totally_ordered<
TaggedInteger<Int, Tag>,

View File

@@ -14,9 +14,7 @@
namespace beast {
/**
* Measures handler latency on an io_context queue.
*/
/** Measures handler latency on an io_context queue. */
template <class Clock>
class IOLatencyProbe
{
@@ -44,9 +42,7 @@ public:
cancel(lock, true);
}
/**
* Return the io_context associated with the latency probe.
*/
/** Return the io_context associated with the latency probe. */
/** @{ */
boost::asio::io_context&
getIoContext()
@@ -61,10 +57,9 @@ public:
}
/** @} */
/**
* Cancel all pending i/o.
* Any handlers which have already been queued will still be called.
*/
/** Cancel all pending i/o.
Any handlers which have already been queued will still be called.
*/
/** @{ */
void
cancel()
@@ -81,11 +76,10 @@ public:
}
/** @} */
/**
* Measure one sample of i/o latency.
* Handler will be called with this signature:
* void Handler (Duration d);
*/
/** Measure one sample of i/o latency.
Handler will be called with this signature:
void Handler (Duration d);
*/
template <class Handler>
void
sampleOne(Handler&& handler)
@@ -97,11 +91,10 @@ public:
ios_, SampleOp<Handler>(std::forward<Handler>(handler), Clock::now(), false, this));
}
/**
* Initiate continuous i/o latency sampling.
* Handler will be called with this signature:
* void Handler (std::chrono::milliseconds);
*/
/** Initiate continuous i/o latency sampling.
Handler will be called with this signature:
void Handler (std::chrono::milliseconds);
*/
template <class Handler>
void
sample(Handler&& handler)

View File

@@ -2,35 +2,34 @@
namespace beast {
/**
* Abstract interface to a clock.
*
* This makes now() a member function instead of a static member, so
* an instance of the class can be dependency injected, facilitating
* unit tests where time may be controlled.
*
* An abstract_clock inherits all the nested types of the Clock
* template parameter.
*
* Example:
*
* @code
*
* struct Implementation
* {
* using clock_type = abstract_clock <std::chrono::steady_clock>;
* clock_type& clock_;
* explicit Implementation (clock_type& clock)
* : clock_(clock)
* {
* }
* };
*
* @endcode
*
* @tparam Clock A type meeting these requirements:
* http://en.cppreference.com/w/cpp/concept/Clock
*/
/** Abstract interface to a clock.
This makes now() a member function instead of a static member, so
an instance of the class can be dependency injected, facilitating
unit tests where time may be controlled.
An abstract_clock inherits all the nested types of the Clock
template parameter.
Example:
@code
struct Implementation
{
using clock_type = abstract_clock <std::chrono::steady_clock>;
clock_type& clock_;
explicit Implementation (clock_type& clock)
: clock_(clock)
{
}
};
@endcode
@tparam Clock A type meeting these requirements:
http://en.cppreference.com/w/cpp/concept/Clock
*/
template <class Clock>
class AbstractClock
{
@@ -47,9 +46,7 @@ public:
AbstractClock() = default;
AbstractClock(AbstractClock const&) = default;
/**
* Returns the current time.
*/
/** Returns the current time. */
[[nodiscard]] virtual time_point
now() const = 0;
};
@@ -77,12 +74,11 @@ struct AbstractClockWrapper : public AbstractClock<Facade>
//------------------------------------------------------------------------------
/**
* Returns a global instance of an abstract clock.
* @tparam Facade A type meeting these requirements:
* http://en.cppreference.com/w/cpp/concept/Clock
* @tparam Clock The actual concrete clock to use.
*/
/** Returns a global instance of an abstract clock.
@tparam Facade A type meeting these requirements:
http://en.cppreference.com/w/cpp/concept/Clock
@tparam Clock The actual concrete clock to use.
*/
template <class Facade, class Clock = Facade>
AbstractClock<Facade>&
getAbstractClock()

View File

@@ -4,16 +4,15 @@
namespace beast {
/**
* A clock whose minimum resolution is one second.
*
* The purpose of this class is to optimize the performance of the now()
* member function call. It uses a dedicated thread that wakes up at least
* once per second to sample the requested trivial clock.
*
* @tparam Clock A type meeting these requirements:
* http://en.cppreference.com/w/cpp/concept/Clock
*/
/** A clock whose minimum resolution is one second.
The purpose of this class is to optimize the performance of the now()
member function call. It uses a dedicated thread that wakes up at least
once per second to sample the requested trivial clock.
@tparam Clock A type meeting these requirements:
http://en.cppreference.com/w/cpp/concept/Clock
*/
class BasicSecondsClock
{
public:

View File

@@ -7,16 +7,15 @@
namespace beast {
/**
* Manual clock implementation.
*
* This concrete class implements the @ref abstract_clock interface and
* allows the time to be advanced manually, mainly for the purpose of
* providing a clock in unit tests.
*
* @tparam Clock A type meeting these requirements:
* http://en.cppreference.com/w/cpp/concept/Clock
*/
/** Manual clock implementation.
This concrete class implements the @ref abstract_clock interface and
allows the time to be advanced manually, mainly for the purpose of
providing a clock in unit tests.
@tparam Clock A type meeting these requirements:
http://en.cppreference.com/w/cpp/concept/Clock
*/
template <class Clock>
class ManualClock : public AbstractClock<Clock>
{
@@ -39,9 +38,7 @@ public:
return now_;
}
/**
* Set the current time of the manual clock.
*/
/** Set the current time of the manual clock. */
void
set(time_point const& when)
{
@@ -51,9 +48,7 @@ public:
now_ = when;
}
/**
* Convenience for setting the time in seconds from epoch.
*/
/** Convenience for setting the time in seconds from epoch. */
template <class Integer>
void
set(Integer secondsFromEpoch)
@@ -61,9 +56,7 @@ public:
set(time_point(duration(std::chrono::seconds(secondsFromEpoch))));
}
/**
* Advance the clock by a duration.
*/
/** Advance the clock by a duration. */
template <class Rep, class Period>
void
advance(std::chrono::duration<Rep, Period> const& elapsed)
@@ -74,9 +67,7 @@ public:
now_ += elapsed;
}
/**
* Convenience for advancing the clock by one second.
*/
/** Convenience for advancing the clock by one second. */
ManualClock&
operator++()
{

View File

@@ -7,9 +7,7 @@
namespace beast {
/**
* Expire aged container items past the specified age.
*/
/** Expire aged container items past the specified age. */
template <class AgedContainer, class Rep, class Period>
std::size_t
expire(AgedContainer& c, std::chrono::duration<Rep, Period> const& age)

View File

@@ -39,23 +39,22 @@ struct IsBoostReverseIterator<boost::intrusive::reverse_iterator<It>> : std::tru
explicit IsBoostReverseIterator() = default;
};
/**
* Associative container where each element is also indexed by time.
*
* This container mirrors the interface of the standard library ordered
* associative containers, with the addition that each element is associated
* with a `when` `time_point` which is obtained from the value of the clock's
* `now`. The function `touch` updates the time for an element to the current
* time as reported by the clock.
*
* An extra set of iterator types and member functions are provided in the
* `chronological` memberspace that allow traversal in temporal or reverse
* temporal order. This container is useful as a building block for caches
* whose items expire after a certain amount of time. The chronological
* iterators allow for fully customizable expiration strategies.
*
* @see aged_set, aged_multiset, aged_map, aged_multimap
*/
/** Associative container where each element is also indexed by time.
This container mirrors the interface of the standard library ordered
associative containers, with the addition that each element is associated
with a `when` `time_point` which is obtained from the value of the clock's
`now`. The function `touch` updates the time for an element to the current
time as reported by the clock.
An extra set of iterator types and member functions are provided in the
`chronological` memberspace that allow traversal in temporal or reverse
temporal order. This container is useful as a building block for caches
whose items expire after a certain amount of time. The chronological
iterators allow for fully customizable expiration strategies.
@see aged_set, aged_multiset, aged_map, aged_multimap
*/
template <
bool IsMulti,
bool IsMap,
@@ -1796,9 +1795,7 @@ swap(
lhs.swap(rhs);
}
/**
* Expire aged container items past the specified age.
*/
/** Expire aged container items past the specified age. */
template <
bool IsMulti,
bool IsMap,

View File

@@ -43,24 +43,23 @@ TODO
namespace beast {
namespace detail {
/**
* Associative container where each element is also indexed by time.
*
* This container mirrors the interface of the standard library unordered
* associative containers, with the addition that each element is associated
* with a `when` `time_point` which is obtained from the value of the clock's
* `now`. The function `touch` updates the time for an element to the current
* time as reported by the clock.
*
* An extra set of iterator types and member functions are provided in the
* `chronological` memberspace that allow traversal in temporal or reverse
* temporal order. This container is useful as a building block for caches
* whose items expire after a certain amount of time. The chronological
* iterators allow for fully customizable expiration strategies.
*
* @see aged_unordered_set, aged_unordered_multiset
* @see aged_unordered_map, aged_unordered_multimap
*/
/** Associative container where each element is also indexed by time.
This container mirrors the interface of the standard library unordered
associative containers, with the addition that each element is associated
with a `when` `time_point` which is obtained from the value of the clock's
`now`. The function `touch` updates the time for an element to the current
time as reported by the clock.
An extra set of iterator types and member functions are provided in the
`chronological` memberspace that allow traversal in temporal or reverse
temporal order. This container is useful as a building block for caches
whose items expire after a certain amount of time. The chronological
iterators allow for fully customizable expiration strategies.
@see aged_unordered_set, aged_unordered_multiset
@see aged_unordered_map, aged_unordered_multimap
*/
template <
bool IsMulti,
bool IsMap,
@@ -2710,9 +2709,7 @@ swap(
lhs.swap(rhs);
}
/**
* Expire aged container items past the specified age.
*/
/** Expire aged container items past the specified age. */
template <
bool IsMulti,
bool IsMap,

View File

@@ -12,10 +12,9 @@
namespace beast {
/**
* Changes the name of the caller thread.
* Different OSes may place different length or content limits on this name.
*/
/** Changes the name of the caller thread.
Different OSes may place different length or content limits on this name.
*/
void
setCurrentThreadName(std::string_view newThreadName);
@@ -25,14 +24,13 @@ setCurrentThreadName(std::string_view newThreadName);
// Maximum number of characters is therefore 15.
constexpr std::size_t kMaxThreadNameLength = 15;
/**
* Sets the name of the caller thread with compile-time size checking.
* @tparam N The size of the string literal including null terminator
* @param newThreadName A string literal to set as the thread name
*
* This template overload enforces that thread names are at most 16 characters
* (including null terminator) at compile time, matching Linux's limit.
*/
/** Sets the name of the caller thread with compile-time size checking.
@tparam N The size of the string literal including null terminator
@param newThreadName A string literal to set as the thread name
This template overload enforces that thread names are at most 16 characters
(including null terminator) at compile time, matching Linux's limit.
*/
template <std::size_t N>
void
setCurrentThreadName(char const (&newThreadName)[N])
@@ -43,15 +41,14 @@ setCurrentThreadName(char const (&newThreadName)[N])
}
#endif
/**
* Returns the name of the caller thread.
*
* The name returned is the name as set by a call to setCurrentThreadName().
* If the thread name is set by an external force, then that name change
* will not be reported.
*
* If no name has ever been set, then the empty string is returned.
*/
/** Returns the name of the caller thread.
The name returned is the name as set by a call to setCurrentThreadName().
If the thread name is set by an external force, then that name change
will not be reported.
If no name has ever been set, then the empty string is returned.
*/
std::string
getCurrentThreadName();

View File

@@ -163,19 +163,17 @@ struct LexicalCast<Out, char*>
//------------------------------------------------------------------------------
/**
* Thrown when a conversion is not possible with LexicalCast.
* Only used in the throw variants of lexicalCast.
*/
/** Thrown when a conversion is not possible with LexicalCast.
Only used in the throw variants of lexicalCast.
*/
struct BadLexicalCast : public std::bad_cast
{
explicit BadLexicalCast() = default;
};
/**
* Intelligently convert from one type to another.
* @return `false` if there was a parsing or range error
*/
/** Intelligently convert from one type to another.
@return `false` if there was a parsing or range error
*/
template <class Out, class In>
bool
lexicalCastChecked(Out& out, In in)
@@ -183,13 +181,12 @@ lexicalCastChecked(Out& out, In in)
return detail::LexicalCast<Out, In>()(out, in);
}
/**
* Convert from one type to another, throw on error
*
* An exception of type BadLexicalCast is thrown if the conversion fails.
*
* @return The new type.
*/
/** Convert from one type to another, throw on error
An exception of type BadLexicalCast is thrown if the conversion fails.
@return The new type.
*/
template <class Out, class In>
Out
lexicalCastThrow(In in)
@@ -200,12 +197,11 @@ lexicalCastThrow(In in)
throw BadLexicalCast();
}
/**
* Convert from one type to another.
*
* @param defaultValue The value returned if parsing fails
* @return The new type.
*/
/** Convert from one type to another.
@param defaultValue The value returned if parsing fails
@return The new type.
*/
template <class Out, class In>
Out
lexicalCast(In in, Out defaultValue = Out())

View File

@@ -11,9 +11,7 @@ class List;
namespace detail {
/**
* Copy `const` attribute from T to U if present.
*/
/** Copy `const` attribute from T to U if present. */
/** @{ */
template <typename T, typename U>
struct CopyConst
@@ -155,111 +153,110 @@ private:
} // namespace detail
/**
* Intrusive doubly linked list.
*
* This intrusive List is a container similar in operation to std::list in the
* Standard Template Library (STL). Like all @ref intrusive containers, List
* requires you to first derive your class from List<>::Node:
*
* @code
*
* struct Object : List <Object>::Node
* {
* explicit Object (int value) : value_ (value)
* {
* }
*
* int value_;
* };
*
* @endcode
*
* Now we define the list, and add a couple of items.
*
* @code
*
* List <Object> list;
*
* list.push_back (* (new Object (1)));
* list.push_back (* (new Object (2)));
*
* @endcode
*
* For compatibility with the standard containers, push_back() expects a
* reference to the object. Unlike the standard container, however, push_back()
* places the actual object in the list and not a copy-constructed duplicate.
*
* Iterating over the list follows the same idiom as the STL:
*
* @code
*
* for (List <Object>::iterator iter = list.begin(); iter != list.end; ++iter)
* std::cout << iter->value_;
*
* @endcode
*
* You can even use BOOST_FOREACH, or range based for loops:
*
* @code
*
* BOOST_FOREACH (Object& object, list) // boost only
* std::cout << object.value_;
*
* for (Object& object : list) // C++11 only
* std::cout << object.value_;
*
* @endcode
*
* Because List is mostly STL compliant, it can be passed into STL algorithms:
* e.g. `std::for_each()` or `std::find_first_of()`.
*
* In general, objects placed into a List should be dynamically allocated
* although this cannot be enforced at compile time. Since the caller provides
* the storage for the object, the caller is also responsible for deleting the
* object. An object still exists after being removed from a List, until the
* caller deletes it. This means an element can be moved from one List to
* another with practically no overhead.
*
* Unlike the standard containers, an object may only exist in one list at a
* time, unless special preparations are made. The Tag template parameter is
* used to distinguish between different list types for the same object,
* allowing the object to exist in more than one list simultaneously.
*
* For example, consider an actor system where a global list of actors is
* maintained, so that they can each be periodically receive processing
* time. We wish to also maintain a list of the subset of actors that require
* a domain-dependent update. To achieve this, we declare two tags, the
* associated list types, and the list element thusly:
*
* @code
*
* struct Actor; // Forward declaration required
*
* struct ProcessTag { };
* struct UpdateTag { };
*
* using ProcessList = List <Actor, ProcessTag>;
* using UpdateList = List <Actor, UpdateTag>;
*
* // Derive from both node types so we can be in each list at once.
* //
* struct Actor : ProcessList::Node, UpdateList::Node
* {
* bool process (); // returns true if we need an update
* void update ();
* };
*
* @endcode
*
* @tparam T The base type of element which the list will store
* pointers to.
*
* @tparam Tag An optional unique type name used to distinguish lists and
* nodes, when the object can exist in multiple lists simultaneously.
*
* @ingroup beast_core intrusive
*/
/** Intrusive doubly linked list.
This intrusive List is a container similar in operation to std::list in the
Standard Template Library (STL). Like all @ref intrusive containers, List
requires you to first derive your class from List<>::Node:
@code
struct Object : List <Object>::Node
{
explicit Object (int value) : value_ (value)
{
}
int value_;
};
@endcode
Now we define the list, and add a couple of items.
@code
List <Object> list;
list.push_back (* (new Object (1)));
list.push_back (* (new Object (2)));
@endcode
For compatibility with the standard containers, push_back() expects a
reference to the object. Unlike the standard container, however, push_back()
places the actual object in the list and not a copy-constructed duplicate.
Iterating over the list follows the same idiom as the STL:
@code
for (List <Object>::iterator iter = list.begin(); iter != list.end; ++iter)
std::cout << iter->value_;
@endcode
You can even use BOOST_FOREACH, or range based for loops:
@code
BOOST_FOREACH (Object& object, list) // boost only
std::cout << object.value_;
for (Object& object : list) // C++11 only
std::cout << object.value_;
@endcode
Because List is mostly STL compliant, it can be passed into STL algorithms:
e.g. `std::for_each()` or `std::find_first_of()`.
In general, objects placed into a List should be dynamically allocated
although this cannot be enforced at compile time. Since the caller provides
the storage for the object, the caller is also responsible for deleting the
object. An object still exists after being removed from a List, until the
caller deletes it. This means an element can be moved from one List to
another with practically no overhead.
Unlike the standard containers, an object may only exist in one list at a
time, unless special preparations are made. The Tag template parameter is
used to distinguish between different list types for the same object,
allowing the object to exist in more than one list simultaneously.
For example, consider an actor system where a global list of actors is
maintained, so that they can each be periodically receive processing
time. We wish to also maintain a list of the subset of actors that require
a domain-dependent update. To achieve this, we declare two tags, the
associated list types, and the list element thusly:
@code
struct Actor; // Forward declaration required
struct ProcessTag { };
struct UpdateTag { };
using ProcessList = List <Actor, ProcessTag>;
using UpdateList = List <Actor, UpdateTag>;
// Derive from both node types so we can be in each list at once.
//
struct Actor : ProcessList::Node, UpdateList::Node
{
bool process (); // returns true if we need an update
void update ();
};
@endcode
@tparam T The base type of element which the list will store
pointers to.
@tparam Tag An optional unique type name used to distinguish lists and
nodes, when the object can exist in multiple lists simultaneously.
@ingroup beast_core intrusive
*/
template <typename T, typename Tag = void>
class List
{
@@ -277,9 +274,7 @@ public:
using iterator = detail::ListIterator<Node>;
using const_iterator = detail::ListIterator<Node const>;
/**
* Create an empty list.
*/
/** Create an empty list. */
List()
{
head_.prev_ = nullptr; // identifies the head
@@ -291,133 +286,119 @@ public:
List&
operator=(List const&) = delete;
/**
* Determine if the list is empty.
* @return `true` if the list is empty.
*/
/** Determine if the list is empty.
@return `true` if the list is empty.
*/
[[nodiscard]] bool
empty() const noexcept
{
return size() == 0;
}
/**
* Returns the number of elements in the list.
*/
/** Returns the number of elements in the list. */
[[nodiscard]] size_type
size() const noexcept
{
return size_;
}
/**
* Obtain a reference to the first element.
* @invariant The list may not be empty.
* @return A reference to the first element.
*/
/** Obtain a reference to the first element.
@invariant The list may not be empty.
@return A reference to the first element.
*/
reference
front() noexcept
{
return element_from(head_.next_);
}
/**
* Obtain a const reference to the first element.
* @invariant The list may not be empty.
* @return A const reference to the first element.
*/
/** Obtain a const reference to the first element.
@invariant The list may not be empty.
@return A const reference to the first element.
*/
[[nodiscard]] const_reference
front() const noexcept
{
return element_from(head_.next_);
}
/**
* Obtain a reference to the last element.
* @invariant The list may not be empty.
* @return A reference to the last element.
*/
/** Obtain a reference to the last element.
@invariant The list may not be empty.
@return A reference to the last element.
*/
reference
back() noexcept
{
return element_from(tail_.prev_);
}
/**
* Obtain a const reference to the last element.
* @invariant The list may not be empty.
* @return A const reference to the last element.
*/
/** Obtain a const reference to the last element.
@invariant The list may not be empty.
@return A const reference to the last element.
*/
[[nodiscard]] const_reference
back() const noexcept
{
return element_from(tail_.prev_);
}
/**
* Obtain an iterator to the beginning of the list.
* @return An iterator pointing to the beginning of the list.
*/
/** Obtain an iterator to the beginning of the list.
@return An iterator pointing to the beginning of the list.
*/
iterator
begin() noexcept
{
return iterator(head_.next_);
}
/**
* Obtain a const iterator to the beginning of the list.
* @return A const iterator pointing to the beginning of the list.
*/
/** Obtain a const iterator to the beginning of the list.
@return A const iterator pointing to the beginning of the list.
*/
[[nodiscard]] const_iterator
begin() const noexcept
{
return const_iterator(head_.next_);
}
/**
* Obtain a const iterator to the beginning of the list.
* @return A const iterator pointing to the beginning of the list.
*/
/** Obtain a const iterator to the beginning of the list.
@return A const iterator pointing to the beginning of the list.
*/
[[nodiscard]] const_iterator
cbegin() const noexcept
{
return const_iterator(head_.next_);
}
/**
* Obtain a iterator to the end of the list.
* @return An iterator pointing to the end of the list.
*/
/** Obtain a iterator to the end of the list.
@return An iterator pointing to the end of the list.
*/
iterator
end() noexcept
{
return iterator(&tail_);
}
/**
* Obtain a const iterator to the end of the list.
* @return A constiterator pointing to the end of the list.
*/
/** Obtain a const iterator to the end of the list.
@return A constiterator pointing to the end of the list.
*/
[[nodiscard]] const_iterator
end() const noexcept
{
return const_iterator(&tail_);
}
/**
* Obtain a const iterator to the end of the list
* @return A constiterator pointing to the end of the list.
*/
/** Obtain a const iterator to the end of the list
@return A constiterator pointing to the end of the list.
*/
[[nodiscard]] const_iterator
cend() const noexcept
{
return const_iterator(&tail_);
}
/**
* Clear the list.
* @note This does not free the elements.
*/
/** Clear the list.
@note This does not free the elements.
*/
void
clear() noexcept
{
@@ -426,13 +407,12 @@ public:
size_ = 0;
}
/**
* Insert an element.
* @invariant The element must not already be in the list.
* @param pos The location to insert after.
* @param element The element to insert.
* @return An iterator pointing to the newly inserted element.
*/
/** Insert an element.
@invariant The element must not already be in the list.
@param pos The location to insert after.
@param element The element to insert.
@return An iterator pointing to the newly inserted element.
*/
iterator
insert(iterator pos, T& element) noexcept
{
@@ -445,12 +425,11 @@ public:
return iterator(node);
}
/**
* Insert another list into this one.
* The other list is cleared.
* @param pos The location to insert after.
* @param other The list to insert.
*/
/** Insert another list into this one.
The other list is cleared.
@param pos The location to insert after.
@param other The list to insert.
*/
void
insert(iterator pos, List& other) noexcept
{
@@ -466,12 +445,11 @@ public:
}
}
/**
* Remove an element.
* @invariant The element must exist in the list.
* @param pos An iterator pointing to the element to remove.
* @return An iterator pointing to the next element after the one removed.
*/
/** Remove an element.
@invariant The element must exist in the list.
@param pos An iterator pointing to the element to remove.
@return An iterator pointing to the next element after the one removed.
*/
iterator
erase(iterator pos) noexcept
{
@@ -483,22 +461,20 @@ public:
return pos;
}
/**
* Insert an element at the beginning of the list.
* @invariant The element must not exist in the list.
* @param element The element to insert.
*/
/** Insert an element at the beginning of the list.
@invariant The element must not exist in the list.
@param element The element to insert.
*/
iterator
pushFront(T& element) noexcept
{
return insert(begin(), element);
}
/**
* Remove the element at the beginning of the list.
* @invariant The list must not be empty.
* @return A reference to the popped element.
*/
/** Remove the element at the beginning of the list.
@invariant The list must not be empty.
@return A reference to the popped element.
*/
T&
popFront() noexcept
{
@@ -507,22 +483,20 @@ public:
return element;
}
/**
* Append an element at the end of the list.
* @invariant The element must not exist in the list.
* @param element The element to append.
*/
/** Append an element at the end of the list.
@invariant The element must not exist in the list.
@param element The element to append.
*/
iterator
pushBack(T& element) noexcept
{
return insert(end(), element);
}
/**
* Remove the element at the end of the list.
* @invariant The list must not be empty.
* @return A reference to the popped element.
*/
/** Remove the element at the end of the list.
@invariant The list must not be empty.
@return A reference to the popped element.
*/
T&
popBack() noexcept
{
@@ -531,9 +505,7 @@ public:
return element;
}
/**
* Swap contents with another list.
*/
/** Swap contents with another list. */
void
swap(List& other) noexcept
{
@@ -543,46 +515,42 @@ public:
append(temp);
}
/**
* Insert another list at the beginning of this list.
* The other list is cleared.
* @param list The other list to insert.
*/
/** Insert another list at the beginning of this list.
The other list is cleared.
@param list The other list to insert.
*/
iterator
prepend(List& list) noexcept
{
return insert(begin(), list);
}
/**
* Append another list at the end of this list.
* The other list is cleared.
* @param list the other list to append.
*/
/** Append another list at the end of this list.
The other list is cleared.
@param list the other list to append.
*/
iterator
append(List& list) noexcept
{
return insert(end(), list);
}
/**
* Obtain an iterator from an element.
* @invariant The element must exist in the list.
* @param element The element to obtain an iterator for.
* @return An iterator to the element.
*/
/** Obtain an iterator from an element.
@invariant The element must exist in the list.
@param element The element to obtain an iterator for.
@return An iterator to the element.
*/
iterator
iteratorTo(T& element) const noexcept
{
return iterator(static_cast<Node*>(&element));
}
/**
* Obtain a const iterator from an element.
* @invariant The element must exist in the list.
* @param element The element to obtain an iterator for.
* @return A const iterator to the element.
*/
/** Obtain a const iterator from an element.
@invariant The element must exist in the list.
@param element The element to obtain an iterator for.
@return A const iterator to the element.
*/
[[nodiscard]] const_iterator
constIteratorTo(T const& element) const noexcept
{

View File

@@ -103,19 +103,18 @@ operator!=(
//------------------------------------------------------------------------------
/**
* Multiple Producer, Multiple Consumer (MPMC) intrusive stack.
*
* This stack is implemented using the same intrusive interface as List.
* All mutations are lock-free.
*
* The caller is responsible for preventing the "ABA" problem:
* http://en.wikipedia.org/wiki/ABA_problem
*
* @param Tag A type name used to distinguish lists and nodes, for
* putting objects in multiple lists. If this parameter is
* omitted, the default tag is used.
*/
/** Multiple Producer, Multiple Consumer (MPMC) intrusive stack.
This stack is implemented using the same intrusive interface as List.
All mutations are lock-free.
The caller is responsible for preventing the "ABA" problem:
http://en.wikipedia.org/wiki/ABA_problem
@param Tag A type name used to distinguish lists and nodes, for
putting objects in multiple lists. If this parameter is
omitted, the default tag is used.
*/
template <class Element, class Tag = void>
class LockFreeStack
{
@@ -163,27 +162,24 @@ public:
LockFreeStack&
operator=(LockFreeStack const&) = delete;
/**
* Returns true if the stack is empty.
*/
/** Returns true if the stack is empty. */
[[nodiscard]] bool
empty() const
{
return head_.load() == &end_;
}
/**
* Push a node onto the stack.
* The caller is responsible for preventing the ABA problem.
* This operation is lock-free.
* Thread safety:
* Safe to call from any thread.
*
* @param node The node to push.
*
* @return `true` if the stack was previously empty. If multiple threads
* are attempting to push, only one will receive `true`.
*/
/** Push a node onto the stack.
The caller is responsible for preventing the ABA problem.
This operation is lock-free.
Thread safety:
Safe to call from any thread.
@param node The node to push.
@return `true` if the stack was previously empty. If multiple threads
are attempting to push, only one will receive `true`.
*/
// VFALCO NOTE Fix this, shouldn't it be a reference like intrusive list?
bool
pushFront(Node* node)
@@ -199,16 +195,15 @@ public:
return first;
}
/**
* Pop an element off the stack.
* The caller is responsible for preventing the ABA problem.
* This operation is lock-free.
* Thread safety:
* Safe to call from any thread.
*
* @return The element that was popped, or `nullptr` if the stack
* was empty.
*/
/** Pop an element off the stack.
The caller is responsible for preventing the ABA problem.
This operation is lock-free.
Thread safety:
Safe to call from any thread.
@return The element that was popped, or `nullptr` if the stack
was empty.
*/
Element*
popFront()
{
@@ -224,13 +219,12 @@ public:
return static_cast<Element*>(node);
}
/**
* Return a forward iterator to the beginning or end of the stack.
* Undefined behavior results if push_front or pop_front is called
* while an iteration is in progress.
* Thread safety:
* Caller is responsible for synchronization.
*/
/** Return a forward iterator to the beginning or end of the stack.
Undefined behavior results if push_front or pop_front is called
while an iteration is in progress.
Thread safety:
Caller is responsible for synchronization.
*/
/** @{ */
iterator
begin()

View File

@@ -6,14 +6,13 @@
namespace beast {
/**
* A Semantic Version number.
*
* Identifies the build of a particular version of software using
* the Semantic Versioning Specification described here:
*
* http://semver.org/
*/
/** A Semantic Version number.
Identifies the build of a particular version of software using
the Semantic Versioning Specification described here:
http://semver.org/
*/
class SemanticVersion
{
public:
@@ -30,17 +29,14 @@ public:
SemanticVersion(std::string_view version);
/**
* Parse a semantic version string.
* The parsing is as strict as possible.
* @return `true` if the string was parsed.
*/
/** Parse a semantic version string.
The parsing is as strict as possible.
@return `true` if the string was parsed.
*/
bool
parse(std::string_view input);
/**
* Produce a string from semantic version components.
*/
/** Produce a string from semantic version components. */
[[nodiscard]] std::string
print() const;
@@ -56,10 +52,9 @@ public:
}
};
/**
* Compare two SemanticVersions against each other.
* The comparison follows the rules as per the specification.
*/
/** Compare two SemanticVersions against each other.
The comparison follows the rules as per the specification.
*/
int
compare(SemanticVersion const& lhs, SemanticVersion const& rhs);

View File

@@ -135,20 +135,19 @@ struct IsUniquelyRepresented<std::array<T, N>>
explicit IsUniquelyRepresented() = default;
};
/**
* Metafunction returning `true` if the type can be hashed in one call.
*
* For `IsContiguouslyHashable<T>::value` to be true, then for every
* combination of possible values of `T` held in `x` and `y`,
* if `x == y`, then it must be true that `memcmp(&x, &y, sizeof(T))`
* return 0; i.e. that `x` and `y` are represented by the same bit pattern.
*
* For example: A two's complement `int` should be contiguously hashable.
* Every bit pattern produces a unique value that does not compare equal to
* any other bit pattern's value. A IEEE floating point should not be
* contiguously hashable because -0. and 0. have different bit patterns,
* though they compare equal.
*/
/** Metafunction returning `true` if the type can be hashed in one call.
For `IsContiguouslyHashable<T>::value` to be true, then for every
combination of possible values of `T` held in `x` and `y`,
if `x == y`, then it must be true that `memcmp(&x, &y, sizeof(T))`
return 0; i.e. that `x` and `y` are represented by the same bit pattern.
For example: A two's complement `int` should be contiguously hashable.
Every bit pattern produces a unique value that does not compare equal to
any other bit pattern's value. A IEEE floating point should not be
contiguously hashable because -0. and 0. have different bit patterns,
though they compare equal.
*/
/** @{ */
template <class T, class HashAlgorithm>
struct IsContiguouslyHashable
@@ -173,30 +172,29 @@ struct IsContiguouslyHashable<T[N], HashAlgorithm>
//------------------------------------------------------------------------------
/**
* Logically concatenate input data to a `Hasher`.
*
* Hasher requirements:
*
* `X` is the type `Hasher`
* `h` is a value of type `x`
* `p` is a value convertible to `void const*`
* `n` is a value of type `std::size_t`, greater than zero
*
* Expression:
* `h.append (p, n);`
* Throws:
* Never
* Effect:
* Adds the input data to the hasher state.
*
* Expression:
* `static_cast<std::size_t>(j)`
* Throws:
* Never
* Effect:
* Returns the resulting hash of all the input data.
*/
/** Logically concatenate input data to a `Hasher`.
Hasher requirements:
`X` is the type `Hasher`
`h` is a value of type `x`
`p` is a value convertible to `void const*`
`n` is a value of type `std::size_t`, greater than zero
Expression:
`h.append (p, n);`
Throws:
Never
Effect:
Adds the input data to the hasher state.
Expression:
`static_cast<std::size_t>(j)`
Throws:
Never
Effect:
Returns the resulting hash of all the input data.
*/
/** @{ */
// scalars

View File

@@ -12,17 +12,16 @@
namespace beast::insight {
/**
* Interface for a manager that allows collection of metrics.
*
* To export metrics from a class, pass and save a shared_ptr to this
* interface in the class constructor. Create the metric objects
* as desired (counters, events, gauges, meters, and an optional hook)
* using the interface.
*
* @see Counter, Event, Gauge, Hook, Meter
* @see NullCollector, StatsDCollector
*/
/** Interface for a manager that allows collection of metrics.
To export metrics from a class, pass and save a shared_ptr to this
interface in the class constructor. Create the metric objects
as desired (counters, events, gauges, meters, and an optional hook)
using the interface.
@see Counter, Event, Gauge, Hook, Meter
@see NullCollector, StatsDCollector
*/
class Collector
{
public:
@@ -30,19 +29,18 @@ public:
virtual ~Collector() = 0;
/**
* Create a hook.
*
* A hook is called at each collection interval, on an implementation
* defined thread. This is a convenience facility for gathering metrics
* in the polling style. The typical usage is to update all the metrics
* of interest in the handler.
*
* Handler will be called with this signature:
* void handler (void)
*
* @see Hook
*/
/** Create a hook.
A hook is called at each collection interval, on an implementation
defined thread. This is a convenience facility for gathering metrics
in the polling style. The typical usage is to update all the metrics
of interest in the handler.
Handler will be called with this signature:
void handler (void)
@see Hook
*/
/** @{ */
template <class Handler>
Hook
@@ -55,10 +53,9 @@ public:
makeHook(HookImpl::HandlerType const& handler) = 0;
/** @} */
/**
* Create a counter with the specified name.
* @see Counter
*/
/** Create a counter with the specified name.
@see Counter
*/
/** @{ */
virtual Counter
makeCounter(std::string const& name) = 0;
@@ -72,10 +69,9 @@ public:
}
/** @} */
/**
* Create an event with the specified name.
* @see Event
*/
/** Create an event with the specified name.
@see Event
*/
/** @{ */
virtual Event
makeEvent(std::string const& name) = 0;
@@ -89,10 +85,9 @@ public:
}
/** @} */
/**
* Create a gauge with the specified name.
* @see Gauge
*/
/** Create a gauge with the specified name.
@see Gauge
*/
/** @{ */
virtual Gauge
makeGauge(std::string const& name) = 0;
@@ -106,10 +101,9 @@ public:
}
/** @} */
/**
* Create a meter with the specified name.
* @see Meter
*/
/** Create a meter with the specified name.
@see Meter
*/
/** @{ */
virtual Meter
makeMeter(std::string const& name) = 0;

View File

@@ -7,39 +7,34 @@
namespace beast::insight {
/**
* A metric for measuring an integral value.
*
* A counter is a gauge calculated at the server. The owner of the counter
* may increment and decrement the value by an amount.
*
* This is a lightweight reference wrapper which is cheap to copy and assign.
* When the last reference goes away, the metric is no longer collected.
*/
/** A metric for measuring an integral value.
A counter is a gauge calculated at the server. The owner of the counter
may increment and decrement the value by an amount.
This is a lightweight reference wrapper which is cheap to copy and assign.
When the last reference goes away, the metric is no longer collected.
*/
class Counter final
{
public:
using value_type = CounterImpl::value_type;
/**
* Create a null metric.
* A null metric reports no information.
*/
/** Create a null metric.
A null metric reports no information.
*/
Counter() = default;
/**
* Create the metric reference the specified implementation.
* Normally this won't be called directly. Instead, call the appropriate
* factory function in the Collector interface.
* @see Collector.
*/
/** Create the metric reference the specified implementation.
Normally this won't be called directly. Instead, call the appropriate
factory function in the Collector interface.
@see Collector.
*/
explicit Counter(std::shared_ptr<CounterImpl> impl) : impl_(std::move(impl))
{
}
/**
* Increment the counter.
*/
/** Increment the counter. */
/** @{ */
void
increment(value_type amount) const

View File

@@ -8,40 +8,35 @@
namespace beast::insight {
/**
* A metric for reporting event timing.
*
* An event is an operation that has an associated millisecond time, or
* other integral value. Because events happen at a specific moment, the
* metric only supports a push-style interface.
*
* This is a lightweight reference wrapper which is cheap to copy and assign.
* When the last reference goes away, the metric is no longer collected.
*/
/** A metric for reporting event timing.
An event is an operation that has an associated millisecond time, or
other integral value. Because events happen at a specific moment, the
metric only supports a push-style interface.
This is a lightweight reference wrapper which is cheap to copy and assign.
When the last reference goes away, the metric is no longer collected.
*/
class Event final
{
public:
using value_type = EventImpl::value_type;
/**
* Create a null metric.
* A null metric reports no information.
*/
/** Create a null metric.
A null metric reports no information.
*/
Event() = default;
/**
* Create the metric reference the specified implementation.
* Normally this won't be called directly. Instead, call the appropriate
* factory function in the Collector interface.
* @see Collector.
*/
/** Create the metric reference the specified implementation.
Normally this won't be called directly. Instead, call the appropriate
factory function in the Collector interface.
@see Collector.
*/
explicit Event(std::shared_ptr<EventImpl> impl) : impl_(std::move(impl))
{
}
/**
* Push an event notification.
*/
/** Push an event notification. */
template <class Rep, class Period>
void
notify(std::chrono::duration<Rep, Period> const& value) const

View File

@@ -7,44 +7,40 @@
namespace beast::insight {
/**
* A metric for measuring an integral value.
*
* A gauge is an instantaneous measurement of a value, like the gas gauge
* in a car. The caller directly sets the value, or adjusts it by a
* specified amount. The value is kept in the client rather than the collector.
*
* This is a lightweight reference wrapper which is cheap to copy and assign.
* When the last reference goes away, the metric is no longer collected.
*/
/** A metric for measuring an integral value.
A gauge is an instantaneous measurement of a value, like the gas gauge
in a car. The caller directly sets the value, or adjusts it by a
specified amount. The value is kept in the client rather than the collector.
This is a lightweight reference wrapper which is cheap to copy and assign.
When the last reference goes away, the metric is no longer collected.
*/
class Gauge final
{
public:
using value_type = GaugeImpl::value_type;
using difference_type = GaugeImpl::difference_type;
/**
* Create a null metric.
* A null metric reports no information.
*/
/** Create a null metric.
A null metric reports no information.
*/
Gauge() = default;
/**
* Create the metric reference the specified implementation.
* Normally this won't be called directly. Instead, call the appropriate
* factory function in the Collector interface.
* @see Collector.
*/
/** Create the metric reference the specified implementation.
Normally this won't be called directly. Instead, call the appropriate
factory function in the Collector interface.
@see Collector.
*/
explicit Gauge(std::shared_ptr<GaugeImpl> impl) : impl_(std::move(impl))
{
}
/**
* Set the value on the gauge.
* A Collector implementation should combine multiple calls to value
* changes into a single change if the calls occur within a single
* collection interval.
*/
/** Set the value on the gauge.
A Collector implementation should combine multiple calls to value
changes into a single change if the calls occur within a single
collection interval.
*/
/** @{ */
void
set(value_type value) const
@@ -66,9 +62,7 @@ public:
}
/** @} */
/**
* Adjust the value of the gauge.
*/
/** Adjust the value of the gauge. */
/** @{ */
void
increment(difference_type amount) const

View File

@@ -7,17 +7,13 @@
namespace beast::insight {
/**
* A collector front-end that manages a group of metrics.
*/
/** A collector front-end that manages a group of metrics. */
class Group : public Collector
{
public:
using ptr = std::shared_ptr<Group>;
/**
* Returns the name of this group, for diagnostics.
*/
/** Returns the name of this group, for diagnostics. */
[[nodiscard]] virtual std::string const&
name() const = 0;
};

View File

@@ -8,17 +8,13 @@
namespace beast::insight {
/**
* A container for managing a set of metric groups.
*/
/** A container for managing a set of metric groups. */
class Groups
{
public:
virtual ~Groups() = 0;
/**
* Find or create a new collector with a given name.
*/
/** Find or create a new collector with a given name. */
/** @{ */
virtual Group::ptr const&
get(std::string const& name) = 0;
@@ -31,9 +27,7 @@ public:
/** @} */
};
/**
* Create a group container that uses the specified collector.
*/
/** Create a group container that uses the specified collector. */
std::unique_ptr<Groups>
makeGroups(Collector::ptr const& collector);

View File

@@ -7,24 +7,20 @@
namespace beast::insight {
/**
* A reference to a handler for performing polled collection.
*/
/** A reference to a handler for performing polled collection. */
class Hook final
{
public:
/**
* Create a null hook.
* A null hook has no associated handler.
*/
/** Create a null hook.
A null hook has no associated handler.
*/
Hook() = default;
/**
* Create a hook referencing the specified implementation.
* Normally this won't be called directly. Instead, call the appropriate
* factory function in the Collector interface.
* @see Collector.
*/
/** Create a hook referencing the specified implementation.
Normally this won't be called directly. Instead, call the appropriate
factory function in the Collector interface.
@see Collector.
*/
explicit Hook(std::shared_ptr<HookImpl> impl) : impl_(std::move(impl))
{
}

View File

@@ -7,38 +7,33 @@
namespace beast::insight {
/**
* A metric for measuring an integral value.
*
* A meter may be thought of as an increment-only counter.
*
* This is a lightweight reference wrapper which is cheap to copy and assign.
* When the last reference goes away, the metric is no longer collected.
*/
/** A metric for measuring an integral value.
A meter may be thought of as an increment-only counter.
This is a lightweight reference wrapper which is cheap to copy and assign.
When the last reference goes away, the metric is no longer collected.
*/
class Meter final
{
public:
using value_type = MeterImpl::value_type;
/**
* Create a null metric.
* A null metric reports no information.
*/
/** Create a null metric.
A null metric reports no information.
*/
Meter() = default;
/**
* Create the metric reference the specified implementation.
* Normally this won't be called directly. Instead, call the appropriate
* factory function in the Collector interface.
* @see Collector.
*/
/** Create the metric reference the specified implementation.
Normally this won't be called directly. Instead, call the appropriate
factory function in the Collector interface.
@see Collector.
*/
explicit Meter(std::shared_ptr<MeterImpl> impl) : impl_(std::move(impl))
{
}
/**
* Increment the meter.
*/
/** Increment the meter. */
/** @{ */
void
increment(value_type amount) const

View File

@@ -6,9 +6,7 @@
namespace beast::insight {
/**
* A Collector which does not collect metrics.
*/
/** A Collector which does not collect metrics. */
class NullCollector : public Collector
{
public:

View File

@@ -9,22 +9,20 @@
namespace beast::insight {
/**
* A Collector that reports metrics to a StatsD server.
* Reference:
* https://github.com/b/statsd_spec
*/
/** A Collector that reports metrics to a StatsD server.
Reference:
https://github.com/b/statsd_spec
*/
class StatsDCollector : public Collector
{
public:
explicit StatsDCollector() = default;
/**
* Create a StatsD collector.
* @param address The IP address and port of the StatsD server.
* @param prefix A string pre-pended before each metric name.
* @param journal Destination for logging output.
*/
/** Create a StatsD collector.
@param address The IP address and port of the StatsD server.
@param prefix A string pre-pended before each metric name.
@param journal Destination for logging output.
*/
static std::shared_ptr<StatsDCollector>
make(IP::Endpoint const& address, std::string const& prefix, Journal journal);
};

View File

@@ -19,54 +19,42 @@ namespace IP {
using Address = boost::asio::ip::address;
/**
* Returns the address represented as a string.
*/
/** Returns the address represented as a string. */
inline std::string
to_string(Address const& addr)
{
return addr.to_string();
}
/**
* Returns `true` if this is a loopback address.
*/
/** Returns `true` if this is a loopback address. */
inline bool
isLoopback(Address const& addr)
{
return addr.is_loopback();
}
/**
* Returns `true` if the address is unspecified.
*/
/** Returns `true` if the address is unspecified. */
inline bool
isUnspecified(Address const& addr)
{
return addr.is_unspecified();
}
/**
* Returns `true` if the address is a multicast address.
*/
/** Returns `true` if the address is a multicast address. */
inline bool
isMulticast(Address const& addr)
{
return addr.is_multicast();
}
/**
* Returns `true` if the address is a private unroutable address.
*/
/** Returns `true` if the address is a private unroutable address. */
inline bool
isPrivate(Address const& addr)
{
return (addr.is_v4()) ? isPrivate(addr.to_v4()) : isPrivate(addr.to_v6());
}
/**
* Returns `true` if the address is a public routable address.
*/
/** Returns `true` if the address is a public routable address. */
inline bool
isPublic(Address const& addr)
{

View File

@@ -6,29 +6,23 @@
namespace beast::IP {
/**
* Convert to Endpoint.
* The port is set to zero.
*/
/** Convert to Endpoint.
The port is set to zero.
*/
Endpoint
fromAsio(boost::asio::ip::address const& address);
/**
* Convert to Endpoint.
*/
/** Convert to Endpoint. */
Endpoint
fromAsio(boost::asio::ip::tcp::endpoint const& endpoint);
/**
* Convert to asio::ip::address.
* The port is ignored.
*/
/** Convert to asio::ip::address.
The port is ignored.
*/
boost::asio::ip::address
toAsioAddress(Endpoint const& endpoint);
/**
* Convert to asio::ip::tcp::endpoint.
*/
/** Convert to asio::ip::tcp::endpoint. */
boost::asio::ip::tcp::endpoint
toAsioEndpoint(Endpoint const& endpoint);

View File

@@ -6,22 +6,17 @@ namespace beast::IP {
using AddressV4 = boost::asio::ip::address_v4;
/**
* Returns `true` if the address is a private unroutable address.
*/
/** Returns `true` if the address is a private unroutable address. */
bool
isPrivate(AddressV4 const& addr);
/**
* Returns `true` if the address is a public routable address.
*/
/** Returns `true` if the address is a public routable address. */
bool
isPublic(AddressV4 const& addr);
/**
* Returns the address class for the given address.
* @note Class 'D' represents multicast addresses (224.*.*.*).
*/
/** Returns the address class for the given address.
@note Class 'D' represents multicast addresses (224.*.*.*).
*/
char
getClass(AddressV4 const& address);

View File

@@ -6,15 +6,11 @@ namespace beast::IP {
using AddressV6 = boost::asio::ip::address_v6;
/**
* Returns `true` if the address is a private unroutable address.
*/
/** Returns `true` if the address is a private unroutable address. */
bool
isPrivate(AddressV6 const& addr);
/**
* Returns `true` if the address is a public routable address.
*/
/** Returns `true` if the address is a public routable address. */
bool
isPublic(AddressV6 const& addr);

View File

@@ -17,68 +17,51 @@ namespace beast::IP {
using Port = std::uint16_t;
/**
* A version-independent IP address and port combination.
*/
/** A version-independent IP address and port combination. */
class Endpoint
{
public:
/**
* Create an unspecified endpoint.
*/
/** Create an unspecified endpoint. */
Endpoint();
/**
* Create an endpoint from the address and optional port.
*/
/** Create an endpoint from the address and optional port. */
explicit Endpoint(Address addr, Port port = 0);
/**
* Create an Endpoint from a string.
* If the port is omitted, the endpoint will have a zero port.
* @return An optional endpoint; will be `std::nullopt` on failure
*/
/** Create an Endpoint from a string.
If the port is omitted, the endpoint will have a zero port.
@return An optional endpoint; will be `std::nullopt` on failure
*/
static std::optional<Endpoint>
fromStringChecked(std::string const& s);
static Endpoint
fromString(std::string const& s);
/**
* Returns a string representing the endpoint.
*/
/** Returns a string representing the endpoint. */
[[nodiscard]] std::string
toString() const;
/**
* Returns the port number on the endpoint.
*/
/** Returns the port number on the endpoint. */
[[nodiscard]] Port
port() const
{
return port_;
}
/**
* Returns a new Endpoint with a different port.
*/
/** Returns a new Endpoint with a different port. */
[[nodiscard]] Endpoint
atPort(Port port) const
{
return Endpoint(addr_, port);
}
/**
* Returns the address portion of this endpoint.
*/
/** Returns the address portion of this endpoint. */
[[nodiscard]] Address const&
address() const
{
return addr_;
}
/**
* Convenience accessors for the address part.
*/
/** Convenience accessors for the address part. */
/** @{ */
[[nodiscard]] bool
isV4() const
@@ -102,9 +85,7 @@ public:
}
/** @} */
/**
* Arithmetic comparison.
*/
/** Arithmetic comparison. */
/** @{ */
friend bool
operator==(Endpoint const& lhs, Endpoint const& rhs);
@@ -150,45 +131,35 @@ private:
// Properties
/**
* Returns `true` if the endpoint is a loopback address.
*/
/** Returns `true` if the endpoint is a loopback address. */
inline bool
isLoopback(Endpoint const& endpoint)
{
return isLoopback(endpoint.address());
}
/**
* Returns `true` if the endpoint is unspecified.
*/
/** Returns `true` if the endpoint is unspecified. */
inline bool
isUnspecified(Endpoint const& endpoint)
{
return isUnspecified(endpoint.address());
}
/**
* Returns `true` if the endpoint is a multicast address.
*/
/** Returns `true` if the endpoint is a multicast address. */
inline bool
isMulticast(Endpoint const& endpoint)
{
return isMulticast(endpoint.address());
}
/**
* Returns `true` if the endpoint is a private unroutable address.
*/
/** Returns `true` if the endpoint is a private unroutable address. */
inline bool
isPrivate(Endpoint const& endpoint)
{
return isPrivate(endpoint.address());
}
/**
* Returns `true` if the endpoint is a public routable address.
*/
/** Returns `true` if the endpoint is a public routable address. */
inline bool
isPublic(Endpoint const& endpoint)
{
@@ -197,18 +168,14 @@ isPublic(Endpoint const& endpoint)
//------------------------------------------------------------------------------
/**
* Returns the endpoint represented as a string.
*/
/** Returns the endpoint represented as a string. */
inline std::string
to_string(Endpoint const& endpoint)
{
return endpoint.toString();
}
/**
* Output stream conversion.
*/
/** Output stream conversion. */
template <typename OutputStream>
OutputStream&
operator<<(OutputStream& os, Endpoint const& endpoint)
@@ -217,9 +184,7 @@ operator<<(OutputStream& os, Endpoint const& endpoint)
return os;
}
/**
* Input stream conversion.
*/
/** Input stream conversion. */
std::istream&
operator>>(std::istream& is, Endpoint& endpoint);
@@ -228,9 +193,7 @@ operator>>(std::istream& is, Endpoint& endpoint);
//------------------------------------------------------------------------------
namespace std {
/**
* std::hash support.
*/
/** std::hash support. */
template <>
struct hash<::beast::IP::Endpoint>
{
@@ -245,9 +208,7 @@ struct hash<::beast::IP::Endpoint>
} // namespace std
namespace boost {
/**
* boost::hash support.
*/
/** boost::hash support. */
template <>
struct hash<::beast::IP::Endpoint>
{

View File

@@ -30,20 +30,17 @@ struct CiEqualPred
}
};
/**
* Returns `true` if `c` is linear white space.
*
* This excludes the CRLF sequence allowed for line continuations.
*/
/** Returns `true` if `c` is linear white space.
This excludes the CRLF sequence allowed for line continuations.
*/
inline bool
isLws(char c)
{
return c == ' ' || c == '\t';
}
/**
* Returns `true` if `c` is any whitespace character.
*/
/** Returns `true` if `c` is any whitespace character. */
inline bool
isWhite(char c)
{
@@ -90,15 +87,14 @@ trimRight(String const& s)
} // namespace detail
/**
* Parse a character sequence of values separated by commas.
* Double quotes and escape sequences will be converted. Excess white
* space, commas, double quotes, and empty elements are not copied.
* Format:
* #(token|quoted-string)
* Reference:
* http://www.w3.org/Protocols/rfc2616/rfc2616-sec2.html#sec2
*/
/** Parse a character sequence of values separated by commas.
Double quotes and escape sequences will be converted. Excess white
space, commas, double quotes, and empty elements are not copied.
Format:
#(token|quoted-string)
Reference:
http://www.w3.org/Protocols/rfc2616/rfc2616-sec2.html#sec2
*/
template <
class FwdIt,
class Result = std::vector<std::basic_string<typename std::iterator_traits<FwdIt>::value_type>>,
@@ -193,15 +189,14 @@ splitCommas(boost::beast::string_view const& s)
//------------------------------------------------------------------------------
/**
* Iterates through a comma separated list.
*
* Meets the requirements of ForwardIterator.
*
* List defined in rfc2616 2.1.
*
* @note Values returned may contain backslash escapes.
*/
/** Iterates through a comma separated list.
Meets the requirements of ForwardIterator.
List defined in rfc2616 2.1.
@note Values returned may contain backslash escapes.
*/
class ListIterator
{
using iter_type = boost::string_ref::const_iterator;
@@ -328,20 +323,17 @@ ListIterator::increment()
}
}
}
/**
* Returns true if two strings are equal.
*
* A case-insensitive comparison is used.
*/
/** Returns true if two strings are equal.
A case-insensitive comparison is used.
*/
inline bool
ciEqual(boost::string_ref s1, boost::string_ref s2)
{
return boost::range::equal(s1, s2, detail::CiEqualPred{});
}
/**
* Returns a range representing the list.
*/
/** Returns a range representing the list. */
inline boost::iterator_range<ListIterator>
makeList(boost::string_ref const& field)
{
@@ -349,22 +341,20 @@ makeList(boost::string_ref const& field)
ListIterator{field.begin(), field.end()}, ListIterator{field.end(), field.end()}};
}
/**
* Returns true if the specified token exists in the list.
*
* A case-insensitive comparison is used.
*/
/** Returns true if the specified token exists in the list.
A case-insensitive comparison is used.
*/
template <class = void>
bool
tokenInList(boost::string_ref const& value, boost::string_ref const& token)
{
auto const list = makeList(value);
// ListIterator is not default-constructible, so it does not model a std::ranges
// sentinel/range; the classic std::any_of (which only needs an input iterator)
// is used instead.
// NOLINTNEXTLINE(modernize-use-ranges)
return std::any_of(
list.begin(), list.end(), [&token](auto const& item) { return ciEqual(item, token); });
for (auto const& item : makeList(value))
{
if (ciEqual(item, token))
return true;
}
return false;
}
template <bool IsRequest, class Body, class Fields>

View File

@@ -19,13 +19,12 @@
namespace beast::test {
/**
* Mix-in to support tests using asio coroutines.
*
* Derive from this class and use yield_to to launch test
* functions inside coroutines. This is handy for testing
* asynchronous asio code.
*/
/** Mix-in to support tests using asio coroutines.
Derive from this class and use yield_to to launch test
functions inside coroutines. This is handy for testing
asynchronous asio code.
*/
class EnableYieldTo
{
protected:
@@ -39,9 +38,7 @@ private:
std::size_t running_ = 0;
public:
/**
* The type of yield context passed to functions.
*/
/// The type of yield context passed to functions.
using yield_context = boost::asio::yield_context;
explicit EnableYieldTo(std::size_t concurrency = 1) : work_(boost::asio::make_work_guard(ios_))
@@ -60,27 +57,24 @@ public:
t.join();
}
/**
* Return the `io_context` associated with the object
*/
/// Return the `io_context` associated with the object
boost::asio::io_context&
getIoContext()
{
return ios_;
}
/**
* Run one or more functions, each in a coroutine.
*
* This call will block until all coroutines terminate.
*
* Each functions should have this signature:
* @code
* void f(yield_context);
* @endcode
*
* @param fn... One or more functions to invoke.
*/
/** Run one or more functions, each in a coroutine.
This call will block until all coroutines terminate.
Each functions should have this signature:
@code
void f(yield_context);
@endcode
@param fn... One or more functions to invoke.
*/
#if BEAST_DOXYGEN
template <class... FN>
void

View File

@@ -10,9 +10,7 @@
namespace beast::unit_test {
/**
* Utility for producing nicely composed output of amounts with units.
*/
/** Utility for producing nicely composed output of amounts with units. */
class Amount
{
private:

View File

@@ -6,11 +6,10 @@
namespace beast::unit_test::detail {
/**
* Adapter to constrain a container interface.
* The interface allows for limited read only operations. Derived classes
* provide additional behavior.
*/
/** Adapter to constrain a container interface.
The interface allows for limited read only operations. Derived classes
provide additional behavior.
*/
template <class Container>
class ConstContainer
{
@@ -39,27 +38,21 @@ public:
using iterator = cont_type::const_iterator;
using const_iterator = cont_type::const_iterator;
/**
* Returns `true` if the container is empty.
*/
/** Returns `true` if the container is empty. */
[[nodiscard]] bool
empty() const
{
return cont_.empty();
}
/**
* Returns the number of items in the container.
*/
/** Returns the number of items in the container. */
[[nodiscard]] size_type
size() const
{
return cont_.size();
}
/**
* Returns forward iterators for traversal.
*/
/** Returns forward iterators for traversal. */
/** @{ */
[[nodiscard]] const_iterator
begin() const

View File

@@ -10,9 +10,7 @@ namespace beast::unit_test {
namespace detail {
/**
* Holds test suites registered during static initialization.
*/
/// Holds test suites registered during static initialization.
inline SuiteList&
globalSuites()
{
@@ -36,9 +34,7 @@ struct InsertSuite
} // namespace detail
/**
* Holds test suites registered during static initialization.
*/
/// Holds test suites registered during static initialization.
inline SuiteList const&
globalSuites()
{

View File

@@ -121,48 +121,42 @@ Selector::operator()(SuiteInfo const& s)
// Utility functions for producing predicates to select suites.
/**
* Returns a predicate that implements a smart matching rule.
* The predicate checks the suite, module, and library fields of the
* SuiteInfo in that order. When it finds a match, it changes modes
* depending on what was found:
*
* If a suite is matched first, then only the suite is selected. The
* suite may be marked manual.
*
* If a module is matched first, then only suites from that module
* and library not marked manual are selected from then on.
*
* If a library is matched first, then only suites from that library
* not marked manual are selected from then on.
*/
/** Returns a predicate that implements a smart matching rule.
The predicate checks the suite, module, and library fields of the
SuiteInfo in that order. When it finds a match, it changes modes
depending on what was found:
If a suite is matched first, then only the suite is selected. The
suite may be marked manual.
If a module is matched first, then only suites from that module
and library not marked manual are selected from then on.
If a library is matched first, then only suites from that library
not marked manual are selected from then on.
*/
inline Selector
matchAuto(std::string const& name)
{
return Selector(Selector::ModeT::Automatch, name);
}
/**
* Return a predicate that matches all suites not marked manual.
*/
/** Return a predicate that matches all suites not marked manual. */
inline Selector
matchAll()
{
return Selector(Selector::ModeT::All);
}
/**
* Returns a predicate that matches a specific suite.
*/
/** Returns a predicate that matches a specific suite. */
inline Selector
matchSuite(std::string const& name)
{
return Selector(Selector::ModeT::Suite, name);
}
/**
* Returns a predicate that matches all suites in a library.
*/
/** Returns a predicate that matches all suites in a library. */
inline Selector
matchLibrary(std::string const& name)
{

View File

@@ -13,9 +13,7 @@
namespace beast::unit_test {
/**
* A test runner that stores the results.
*/
/** A test runner that stores the results. */
class Recorder : public Runner
{
private:
@@ -26,9 +24,7 @@ private:
public:
Recorder() = default;
/**
* Returns a report with the results of all completed suites.
*/
/** Returns a report with the results of all completed suites. */
[[nodiscard]] Results const&
report() const
{

View File

@@ -25,10 +25,9 @@ namespace beast::unit_test {
namespace detail {
/**
* A simple test runner that writes everything to a stream in real time.
* The totals are output when the object is destroyed.
*/
/** A simple test runner that writes everything to a stream in real time.
The totals are output when the object is destroyed.
*/
template <class = void>
class Reporter : public Runner
{

View File

@@ -13,15 +13,11 @@
namespace beast::unit_test {
/**
* Holds a set of test condition outcomes in a testcase.
*/
/** Holds a set of test condition outcomes in a testcase. */
class CaseResults
{
public:
/**
* Holds the result of evaluating one test condition.
*/
/** Holds the result of evaluating one test condition. */
struct Test
{
explicit Test(bool pass) : pass(pass)
@@ -45,36 +41,28 @@ private:
public:
TestsT() = default;
/**
* Returns the total number of test conditions.
*/
/** Returns the total number of test conditions. */
[[nodiscard]] std::size_t
total() const
{
return cont().size();
}
/**
* Returns the number of failed test conditions.
*/
/** Returns the number of failed test conditions. */
[[nodiscard]] std::size_t
failed() const
{
return failed_;
}
/**
* Register a successful test condition.
*/
/** Register a successful test condition. */
void
pass()
{
cont().emplace_back(true);
}
/**
* Register a failed test condition.
*/
/** Register a failed test condition. */
void
fail(std::string const& reason = "")
{
@@ -86,9 +74,7 @@ private:
class LogT : public detail::ConstContainer<std::vector<std::string>>
{
public:
/**
* Insert a string into the log.
*/
/** Insert a string into the log. */
void
insert(std::string const& s)
{
@@ -103,31 +89,23 @@ public:
{
}
/**
* Returns the name of this testcase.
*/
/** Returns the name of this testcase. */
[[nodiscard]] std::string const&
name() const
{
return name_;
}
/**
* Memberspace for a container of test condition outcomes.
*/
/** Memberspace for a container of test condition outcomes. */
TestsT tests;
/**
* Memberspace for a container of testcase log messages.
*/
/** Memberspace for a container of testcase log messages. */
LogT log;
};
//--------------------------------------------------------------------------
/**
* Holds the set of testcase results in a suite.
*/
/** Holds the set of testcase results in a suite. */
class SuiteResults : public detail::ConstContainer<std::vector<CaseResults>>
{
private:
@@ -140,36 +118,28 @@ public:
{
}
/**
* Returns the name of this suite.
*/
/** Returns the name of this suite. */
[[nodiscard]] std::string const&
name() const
{
return name_;
}
/**
* Returns the total number of test conditions.
*/
/** Returns the total number of test conditions. */
[[nodiscard]] std::size_t
total() const
{
return total_;
}
/**
* Returns the number of failures.
*/
/** Returns the number of failures. */
[[nodiscard]] std::size_t
failed() const
{
return failed_;
}
/**
* Insert a set of testcase results.
*/
/** Insert a set of testcase results. */
/** @{ */
void
insert(CaseResults&& r)
@@ -192,9 +162,7 @@ public:
//------------------------------------------------------------------------------
// VFALCO TODO Make this a template class using scoped allocators
/**
* Holds the results of running a set of testsuites.
*/
/** Holds the results of running a set of testsuites. */
class Results : public detail::ConstContainer<std::vector<SuiteResults>>
{
private:
@@ -205,36 +173,28 @@ private:
public:
Results() = default;
/**
* Returns the total number of test cases.
*/
/** Returns the total number of test cases. */
[[nodiscard]] std::size_t
cases() const
{
return cases_;
}
/**
* Returns the total number of test conditions.
*/
/** Returns the total number of test conditions. */
[[nodiscard]] std::size_t
total() const
{
return total_;
}
/**
* Returns the number of failures.
*/
/** Returns the number of failures. */
[[nodiscard]] std::size_t
failed() const
{
return failed_;
}
/**
* Insert a set of suite results.
*/
/** Insert a set of suite results. */
/** @{ */
void
insert(SuiteResults&& r)

View File

@@ -13,12 +13,11 @@
namespace beast::unit_test {
/**
* Unit test runner interface.
*
* Derived classes can customize the reporting behavior. This interface is
* injected into the unit_test class to receive the results of the tests.
*/
/** Unit test runner interface.
Derived classes can customize the reporting behavior. This interface is
injected into the unit_test class to receive the results of the tests.
*/
class Runner
{
std::string arg_;
@@ -34,132 +33,110 @@ public:
Runner&
operator=(Runner const&) = delete;
/**
* Set the argument string.
*
* The argument string is available to suites and
* allows for customization of the test. Each suite
* defines its own syntax for the argument string.
* The same argument is passed to all suites.
*/
/** Set the argument string.
The argument string is available to suites and
allows for customization of the test. Each suite
defines its own syntax for the argument string.
The same argument is passed to all suites.
*/
void
arg(std::string const& s)
{
arg_ = s;
}
/**
* Returns the argument string.
*/
/** Returns the argument string. */
[[nodiscard]] std::string const&
arg() const
{
return arg_;
}
/**
* Run the specified suite.
* @return `true` if any conditions failed.
*/
/** Run the specified suite.
@return `true` if any conditions failed.
*/
template <class = void>
bool
run(SuiteInfo const& s);
/**
* Run a sequence of suites.
* The expression
* `FwdIter::value_type`
* must be convertible to `SuiteInfo`.
* @return `true` if any conditions failed.
*/
/** Run a sequence of suites.
The expression
`FwdIter::value_type`
must be convertible to `SuiteInfo`.
@return `true` if any conditions failed.
*/
template <class FwdIter>
bool
run(FwdIter first, FwdIter last);
/**
* Conditionally run a sequence of suites.
* pred will be called as:
* @code
* bool pred(SuiteInfo const&);
* @endcode
* @return `true` if any conditions failed.
*/
/** Conditionally run a sequence of suites.
pred will be called as:
@code
bool pred(SuiteInfo const&);
@endcode
@return `true` if any conditions failed.
*/
template <class FwdIter, class Pred>
bool
runIf(FwdIter first, FwdIter last, Pred pred = Pred{});
/**
* Run all suites in a container.
* @return `true` if any conditions failed.
*/
/** Run all suites in a container.
@return `true` if any conditions failed.
*/
template <class SequenceContainer>
bool
runEach(SequenceContainer const& c);
/**
* Conditionally run suites in a container.
* pred will be called as:
* @code
* bool pred(SuiteInfo const&);
* @endcode
* @return `true` if any conditions failed.
*/
/** Conditionally run suites in a container.
pred will be called as:
@code
bool pred(SuiteInfo const&);
@endcode
@return `true` if any conditions failed.
*/
template <class SequenceContainer, class Pred>
bool
runEachIf(SequenceContainer const& c, Pred pred = Pred{});
protected:
/**
* Called when a new suite starts.
*/
/// Called when a new suite starts.
virtual void
onSuiteBegin(SuiteInfo const&)
{
}
/**
* Called when a suite ends.
*/
/// Called when a suite ends.
virtual void
onSuiteEnd()
{
}
/**
* Called when a new case starts.
*/
/// Called when a new case starts.
virtual void
onCaseBegin(std::string const&)
{
}
/**
* Called when a new case ends.
*/
/// Called when a new case ends.
virtual void
onCaseEnd()
{
}
/**
* Called for each passing condition.
*/
/// Called for each passing condition.
virtual void
onPass()
{
}
/**
* Called for each failing condition.
*/
/// Called for each failing condition.
virtual void
onFail(std::string const&)
{
}
/**
* Called when a test logs output.
*/
/// Called when a test logs output.
virtual void
onLog(std::string const&)
{

View File

@@ -41,14 +41,13 @@ class Thread;
enum class AbortT { NoAbortOnFail, AbortOnFail };
/**
* A testsuite class.
*
* Derived classes execute a series of testcases, where each testcase is
* a series of pass/fail tests. To provide a unit test using this class,
* derive from it and use the BEAST_DEFINE_UNIT_TEST macro in a
* translation unit.
*/
/** A testsuite class.
Derived classes execute a series of testcases, where each testcase is
a series of pass/fail tests. To provide a unit test using this class,
derive from it and use the BEAST_DEFINE_UNIT_TEST macro in a
translation unit.
*/
class Suite
{
private:
@@ -119,17 +118,16 @@ private:
{
}
/**
* Open a new testcase.
*
* A testcase is a series of evaluated test conditions. A test
* suite may have multiple test cases. A test is associated with
* the last opened testcase. When the test first runs, a default
* unnamed case is opened. Tests with only one case may omit the
* call to testcase.
*
* @param abort Determines if suite continues running after a failure.
*/
/** Open a new testcase.
A testcase is a series of evaluated test conditions. A test
suite may have multiple test cases. A test is associated with
the last opened testcase. When the test first runs, a default
unnamed case is opened. Tests with only one case may omit the
call to testcase.
@param abort Determines if suite continues running after a failure.
*/
void
operator()(std::string const& name, AbortT abort = AbortT::NoAbortOnFail);
@@ -142,23 +140,19 @@ private:
};
public:
/**
* Logging output stream.
*
* Text sent to the log output stream will be forwarded to
* the output stream associated with the runner.
*/
/** Logging output stream.
Text sent to the log output stream will be forwarded to
the output stream associated with the runner.
*/
LogOs<char> log;
/**
* Memberspace for declaring test cases.
*/
/** Memberspace for declaring test cases. */
TestcaseT testcase;
/**
* Returns the "current" running suite.
* If no suite is running, nullptr is returned.
*/
/** Returns the "current" running suite.
If no suite is running, nullptr is returned.
*/
static Suite*
thisSuite()
{
@@ -174,34 +168,30 @@ public:
Suite&
operator=(Suite const&) = delete;
/**
* Invokes the test using the specified runner.
*
* Data members are set up here instead of the constructor as a
* convenience to writing the derived class to avoid repetition of
* forwarded constructor arguments to the base.
* Normally this is called by the framework for you.
*/
/** Invokes the test using the specified runner.
Data members are set up here instead of the constructor as a
convenience to writing the derived class to avoid repetition of
forwarded constructor arguments to the base.
Normally this is called by the framework for you.
*/
template <class = void>
void
operator()(Runner& r);
/**
* Record a successful test condition.
*/
/** Record a successful test condition. */
template <class = void>
void
pass();
/**
* Record a failure.
*
* @param reason Optional text added to the output on a failure.
*
* @param file The source code file where the test failed.
*
* @param line The source code line number where the test failed.
*/
/** Record a failure.
@param reason Optional text added to the output on a failure.
@param file The source code file where the test failed.
@param line The source code line number where the test failed.
*/
/** @{ */
template <class String>
void
@@ -212,24 +202,23 @@ public:
fail(std::string const& reason = "");
/** @} */
/**
* Evaluate a test condition.
*
* This function provides improved logging by incorporating the
* file name and line number into the reported output on failure,
* as well as additional text specified by the caller.
*
* @param shouldBeTrue The condition to test. The condition
* is evaluated in a boolean context.
*
* @param reason Optional added text to output on a failure.
*
* @param file The source code file where the test failed.
*
* @param line The source code line number where the test failed.
*
* @return `true` if the test condition indicates success.
*/
/** Evaluate a test condition.
This function provides improved logging by incorporating the
file name and line number into the reported output on failure,
as well as additional text specified by the caller.
@param shouldBeTrue The condition to test. The condition
is evaluated in a boolean context.
@param reason Optional added text to output on a failure.
@param file The source code file where the test failed.
@param line The source code line number where the test failed.
@return `true` if the test condition indicates success.
*/
/** @{ */
template <class Condition>
bool
@@ -286,19 +275,15 @@ public:
return unexcept(f, "");
}
/**
* Return the argument associated with the runner.
*/
/** Return the argument associated with the runner. */
std::string const&
arg() const
{
return runner_->arg();
}
/**
* DEPRECATED
* @return `true` if the test condition indicates success(a false value)
*/
// DEPRECATED
// @return `true` if the test condition indicates success(a false value)
template <class Condition, class String>
bool
unexpected(Condition shouldBeFalse, String const& reason);
@@ -320,9 +305,7 @@ private:
return &kPTs;
}
/**
* Runs the suite.
*/
/** Runs the suite. */
virtual void
run() = 0;
@@ -575,20 +558,18 @@ Suite::run(Runner& r)
}
#ifndef BEAST_EXPECT
/**
* Check a precondition.
*
* If the condition is false, the file and line number are reported.
*/
/** Check a precondition.
If the condition is false, the file and line number are reported.
*/
#define BEAST_EXPECT(cond) expect(cond, __FILE__, __LINE__)
#endif
#ifndef BEAST_EXPECTS
/**
* Check a precondition.
*
* If the condition is false, the file and line number are reported.
*/
/** Check a precondition.
If the condition is false, the file and line number are reported.
*/
#define BEAST_EXPECTS(cond, reason) \
((cond) ? (pass(), true) : (fail((reason), __FILE__, __LINE__), false))
#endif
@@ -612,43 +593,41 @@ Suite::run(Runner& r)
//
#ifndef BEAST_DEFINE_TESTSUITE
/**
* Enables insertion of test suites into the global container.
* The default is to insert all test suite definitions into the global
* container. If BEAST_DEFINE_TESTSUITE is user defined, this macro
* has no effect.
*/
/** Enables insertion of test suites into the global container.
The default is to insert all test suite definitions into the global
container. If BEAST_DEFINE_TESTSUITE is user defined, this macro
has no effect.
*/
#ifndef BEAST_NO_UNIT_TEST_INLINE
#define BEAST_NO_UNIT_TEST_INLINE 0
#endif
/**
* Define a unit test suite.
*
* Class The type representing the class being tested.
* Module Identifies the module.
* Library Identifies the library.
*
* The declaration for the class implementing the test should be the same
* as Class ## _test. For example, if Class is aged_ordered_container, the
* test class must be declared as:
*
* @code
*
* struct aged_ordered_container_test : beast::unit_test::suite
* {
* //...
* };
*
* @endcode
*
* The macro invocation must appear in the same namespace as the test class.
*
* Unit test priorities were introduced so parallel unit_test::suites would
* execute faster. Suites with longer running times have higher priorities
* than unit tests with shorter running times. Suites with no priorities
* are assumed to run most quickly, so they run last.
*/
/** Define a unit test suite.
Class The type representing the class being tested.
Module Identifies the module.
Library Identifies the library.
The declaration for the class implementing the test should be the same
as Class ## _test. For example, if Class is aged_ordered_container, the
test class must be declared as:
@code
struct aged_ordered_container_test : beast::unit_test::suite
{
//...
};
@endcode
The macro invocation must appear in the same namespace as the test class.
Unit test priorities were introduced so parallel unit_test::suites would
execute faster. Suites with longer running times have higher priorities
than unit tests with shorter running times. Suites with no priorities
are assumed to run most quickly, so they run last.
*/
#if BEAST_NO_UNIT_TEST_INLINE
#define BEAST_DEFINE_TESTSUITE(Class, Module, Library)

View File

@@ -13,9 +13,7 @@ namespace beast::unit_test {
class Runner;
/**
* Associates a unit test type with metadata.
*/
/** Associates a unit test type with metadata. */
class SuiteInfo
{
using run_type = std::function<void(Runner&)>;
@@ -62,27 +60,21 @@ public:
return library_;
}
/**
* Returns `true` if this suite only runs manually.
*/
/// Returns `true` if this suite only runs manually.
[[nodiscard]] bool
manual() const
{
return manual_;
}
/**
* Return the canonical suite name as a string.
*/
/// Return the canonical suite name as a string.
[[nodiscard]] std::string
fullName() const
{
return library_ + "." + module_ + "." + name_;
}
/**
* Run a new instance of the associated test suite.
*/
/// Run a new instance of the associated test suite.
void
run(Runner& r) const
{
@@ -101,9 +93,7 @@ public:
//------------------------------------------------------------------------------
/**
* Convenience for producing SuiteInfo for a given test type.
*/
/// Convenience for producing SuiteInfo for a given test type.
template <class Suite>
SuiteInfo
makeSuiteInfo(std::string name, std::string module, std::string library, bool manual, int priority)

View File

@@ -16,9 +16,7 @@
namespace beast::unit_test {
/**
* A container of test suites.
*/
/// A container of test suites.
class SuiteList : public detail::ConstContainer<std::set<SuiteInfo>>
{
private:
@@ -28,11 +26,10 @@ private:
#endif
public:
/**
* Insert a suite into the set.
*
* The suite must not already exist.
*/
/** Insert a suite into the set.
The suite must not already exist.
*/
template <class Suite>
void
insert(char const* name, char const* module, char const* library, bool manual, int priority);

View File

@@ -14,9 +14,7 @@
namespace beast::unit_test {
/**
* Replacement for std::thread that handles exceptions in unit tests.
*/
/** Replacement for std::thread that handles exceptions in unit tests. */
class Thread
{
private:

View File

@@ -10,9 +10,7 @@
namespace beast {
/**
* Severity level / threshold of a Journal message.
*/
/** Severity level / threshold of a Journal message. */
enum class Severity : std::uint8_t {
All = 0,
@@ -27,19 +25,18 @@ enum class Severity : std::uint8_t {
None = Disabled
};
/**
* A generic endpoint for log messages.
*
* The Journal has a few simple goals:
*
* * To be light-weight and copied by value.
* * To allow logging statements to be left in source code.
* * The logging is controlled at run-time based on a logging threshold.
*
* It is advisable to check Journal::active(level) prior to formatting log
* text. Doing so sidesteps expensive text formatting when the results
* will not be sent to the log.
*/
/** A generic endpoint for log messages.
The Journal has a few simple goals:
* To be light-weight and copied by value.
* To allow logging statements to be left in source code.
* The logging is controlled at run-time based on a logging threshold.
It is advisable to check Journal::active(level) prior to formatting log
text. Doing so sidesteps expensive text formatting when the results
will not be sent to the log.
*/
class Journal
{
public:
@@ -52,9 +49,7 @@ private:
public:
//--------------------------------------------------------------------------
/**
* Abstraction for the underlying message destination.
*/
/** Abstraction for the underlying message destination. */
class Sink
{
protected:
@@ -68,47 +63,36 @@ public:
Sink&
operator=(Sink const& lhs) = delete;
/**
* Returns `true` if text at the passed severity produces output.
*/
/** Returns `true` if text at the passed severity produces output. */
[[nodiscard]] virtual bool
active(Severity level) const;
/**
* Returns `true` if a message is also written to the Output Window
* (MSVC).
*/
/** Returns `true` if a message is also written to the Output Window
* (MSVC). */
[[nodiscard]] virtual bool
console() const;
/**
* Set whether messages are also written to the Output Window (MSVC).
/** Set whether messages are also written to the Output Window (MSVC).
*/
virtual void
console(bool output);
/**
* Returns the minimum severity level this sink will report.
*/
/** Returns the minimum severity level this sink will report. */
[[nodiscard]] virtual Severity
threshold() const;
/**
* Set the minimum severity this sink will report.
*/
/** Set the minimum severity this sink will report. */
virtual void
threshold(Severity thresh);
/**
* Write text to the sink at the specified severity.
* A conforming implementation will not write the text if the passed
* level is below the current threshold().
*/
/** Write text to the sink at the specified severity.
A conforming implementation will not write the text if the passed
level is below the current threshold().
*/
virtual void
write(Severity level, std::string const& text) = 0;
/**
* Bypass filter and write text to the sink at the specified severity.
/** Bypass filter and write text to the sink at the specified severity.
* Always write the message, but maintain the same formatting as if
* it passed through a level filter.
*
@@ -132,9 +116,7 @@ public:
static_assert(std::is_nothrow_destructible_v<Sink>);
#endif
/**
* Returns a Sink which does nothing.
*/
/** Returns a Sink which does nothing. */
static Sink&
getNullSink();
@@ -192,33 +174,26 @@ public:
//--------------------------------------------------------------------------
public:
/**
* Provide a light-weight way to check active() before string formatting
*/
/** Provide a light-weight way to check active() before string formatting */
class Stream
{
public:
/**
* Create a stream which produces no output.
*/
/** Create a stream which produces no output. */
explicit Stream() : sink_(getNullSink()), level_(Severity::Disabled)
{
}
/**
* Create a stream that writes at the given level.
*
* Constructor is inlined so checking active() very inexpensive.
*/
/** Create a stream that writes at the given level.
Constructor is inlined so checking active() very inexpensive.
*/
Stream(Sink& sink, Severity level) : sink_(sink), level_(level)
{
XRPL_ASSERT(
level_ < Severity::Disabled, "beast::Journal::Stream::Stream : maximum level");
}
/**
* Construct or copy another Stream.
*/
/** Construct or copy another Stream. */
Stream(Stream const& other) : Stream(other.sink_, other.level_)
{
}
@@ -226,27 +201,21 @@ public:
Stream&
operator=(Stream const& other) = delete;
/**
* Returns the Sink that this Stream writes to.
*/
/** Returns the Sink that this Stream writes to. */
[[nodiscard]] Sink&
sink() const
{
return sink_;
}
/**
* Returns the Severity level of messages this Stream reports.
*/
/** Returns the Severity level of messages this Stream reports. */
[[nodiscard]] Severity
level() const
{
return level_;
}
/**
* Returns `true` if sink logs anything at this stream's level.
*/
/** Returns `true` if sink logs anything at this stream's level. */
/** @{ */
[[nodiscard]] bool
active() const
@@ -261,9 +230,7 @@ public:
}
/** @} */
/**
* Output stream support.
*/
/** Output stream support. */
/** @{ */
ScopedStream
operator<<(std::ostream& manip(std::ostream&)) const;
@@ -289,50 +256,39 @@ public:
//--------------------------------------------------------------------------
/**
* Journal has no default constructor.
*/
/** Journal has no default constructor. */
Journal() = delete;
/**
* Create a journal that writes to the specified sink.
*/
/** Create a journal that writes to the specified sink. */
explicit Journal(Sink& sink) : sink_(&sink)
{
}
/**
* Returns the Sink associated with this Journal.
*/
/** Returns the Sink associated with this Journal. */
[[nodiscard]] Sink&
sink() const
{
return *sink_;
}
/**
* Returns a stream for this sink, with the specified severity level.
*/
/** Returns a stream for this sink, with the specified severity level. */
[[nodiscard]] Stream
stream(Severity level) const
{
return Stream(*sink_, level);
}
/**
* Returns `true` if any message would be logged at this severity level.
* For a message to be logged, the severity must be at or above the
* sink's severity threshold.
*/
/** Returns `true` if any message would be logged at this severity level.
For a message to be logged, the severity must be at or above the
sink's severity threshold.
*/
[[nodiscard]] bool
active(Severity level) const
{
return sink_->active(level);
}
/**
* Severity stream access functions.
*/
/** Severity stream access functions. */
/** @{ */
[[nodiscard]] Stream
trace() const

View File

@@ -12,9 +12,7 @@ namespace beast {
//------------------------------------------------------------------------------
/**
* Abstract stream with RAII containers that produce a property tree.
*/
/** Abstract stream with RAII containers that produce a property tree. */
class PropertyStream
{
public:
@@ -308,9 +306,7 @@ public:
//
//------------------------------------------------------------------------------
/**
* Subclasses can be called to write to a stream and have children.
*/
/** Subclasses can be called to write to a stream and have children. */
class PropertyStream::Source
{
private:
@@ -328,22 +324,17 @@ public:
Source&
operator=(Source const&) = delete;
/**
* Returns the name of this source.
*/
/** Returns the name of this source. */
[[nodiscard]] std::string const&
name() const;
/**
* Add a child source.
*/
/** Add a child source. */
void
add(Source& source);
/**
* Add a child source by pointer.
* The source pointer is returned so it can be used in ctor-initializers.
*/
/** Add a child source by pointer.
The source pointer is returned so it can be used in ctor-initializers.
*/
template <class Derived>
Derived*
add(Derived* child)
@@ -352,55 +343,45 @@ public:
return child;
}
/**
* Remove a child source from this Source.
*/
/** Remove a child source from this Source. */
void
remove(Source& child);
/**
* Remove all child sources from this Source.
*/
/** Remove all child sources from this Source. */
void
removeAll();
/**
* Write only this Source to the stream.
*/
/** Write only this Source to the stream. */
void
writeOne(PropertyStream& stream);
/**
* write this source and all its children recursively to the stream.
*/
/** write this source and all its children recursively to the stream. */
void
write(PropertyStream& stream);
/**
* Parse the path and write the corresponding Source and optional children.
* If the source is found, it is written. If the wildcard character '*'
* exists as the last character in the path, then all the children are
* written recursively.
*/
/** Parse the path and write the corresponding Source and optional children.
If the source is found, it is written. If the wildcard character '*'
exists as the last character in the path, then all the children are
written recursively.
*/
void
write(PropertyStream& stream, std::string const& path);
/**
* Parse the dot-delimited Source path and return the result.
* The first value will be a pointer to the Source object corresponding
* to the given path. If no Source object exists, then the first value
* will be nullptr and the second value will be undefined.
* The second value is a boolean indicating whether or not the path string
* specifies the wildcard character '*' as the last character.
*
* print statement examples
* "parent.child" prints child and all of its children
* "parent.child." start at the parent and print down to child
* "parent.grandchild" prints nothing- grandchild not direct descendent
* "parent.grandchild." starts at the parent and prints down to grandchild
* "parent.grandchild.*" starts at parent, print through grandchild
* children
*/
/** Parse the dot-delimited Source path and return the result.
The first value will be a pointer to the Source object corresponding
to the given path. If no Source object exists, then the first value
will be nullptr and the second value will be undefined.
The second value is a boolean indicating whether or not the path string
specifies the wildcard character '*' as the last character.
print statement examples
"parent.child" prints child and all of its children
"parent.child." start at the parent and print down to child
"parent.grandchild" prints nothing- grandchild not direct descendent
"parent.grandchild." starts at the parent and prints down to grandchild
"parent.grandchild.*" starts at parent, print through grandchild
children
*/
std::pair<Source*, bool>
find(std::string path);
@@ -420,10 +401,9 @@ public:
//--------------------------------------------------------------------------
/**
* Subclass override.
* The default version does nothing.
*/
/** Subclass override.
The default version does nothing.
*/
virtual void
onWrite(Map&);
};

View File

@@ -7,9 +7,7 @@
namespace beast {
/**
* Wraps a Journal::Sink to prefix its output with a string.
*/
/** Wraps a Journal::Sink to prefix its output with a string. */
// A WrappedSink both is a Sink and has a Sink:
// o It inherits from Sink so it has the correct interface.

View File

@@ -4,23 +4,22 @@
namespace beast {
/**
* Zero allows classes to offer efficient comparisons to zero.
*
* Zero is a struct to allow classes to efficiently compare with zero without
* requiring an rvalue construction.
*
* It's often the case that we have classes which combine a number and a unit.
* In such cases, comparisons like t > 0 or t != 0 make sense, but comparisons
* like t > 1 or t != 1 do not.
*
* The class Zero allows such comparisons to be easily made.
*
* The comparing class T either needs to have a method called signum() which
* returns a positive number, 0, or a negative; or there needs to be a signum
* function which resolves in the namespace which takes an instance of T and
* returns a positive, zero or negative number.
*/
/** Zero allows classes to offer efficient comparisons to zero.
Zero is a struct to allow classes to efficiently compare with zero without
requiring an rvalue construction.
It's often the case that we have classes which combine a number and a unit.
In such cases, comparisons like t > 0 or t != 0 make sense, but comparisons
like t > 1 or t != 1 do not.
The class Zero allows such comparisons to be easily made.
The comparing class T either needs to have a method called signum() which
returns a positive number, 0, or a negative; or there needs to be a signum
function which resolves in the namespace which takes an instance of T and
returns a positive, zero or negative number.
*/
struct Zero
{
@@ -29,9 +28,7 @@ struct Zero
inline constexpr Zero kZero{};
/**
* Default implementation of signum calls the method on the class.
*/
/** Default implementation of signum calls the method on the class. */
template <typename T>
auto
signum(T const& t)

View File

@@ -4,9 +4,7 @@
namespace beast {
/**
* Makes T const or non const depending on a bool.
*/
/** Makes T const or non const depending on a bool. */
template <bool IsConst, class T>
struct MaybeConst
{
@@ -15,9 +13,7 @@ struct MaybeConst
conditional_t<IsConst, typename std::remove_const<T>::type const, std::remove_const_t<T>>;
};
/**
* Alias for omitting `typename`.
*/
/** Alias for omitting `typename`. */
template <bool IsConst, class T>
using maybe_const_t = MaybeConst<IsConst, T>::type;

View File

@@ -6,12 +6,11 @@
namespace beast {
/**
* RAII temporary directory.
*
* The directory and all its contents are deleted when
* the instance of `temp_dir` is destroyed.
*/
/** RAII temporary directory.
The directory and all its contents are deleted when
the instance of `temp_dir` is destroyed.
*/
class TempDir
{
boost::filesystem::path path_;
@@ -23,9 +22,7 @@ public:
operator=(TempDir const&) = delete;
#endif
/**
* Construct a temporary directory.
*/
/// Construct a temporary directory.
TempDir()
{
auto const dir = boost::filesystem::temp_directory_path();
@@ -36,9 +33,7 @@ public:
boost::filesystem::create_directory(path_);
}
/**
* Destroy a temporary directory.
*/
/// Destroy a temporary directory.
~TempDir()
{
// use non-throwing calls in the destructor
@@ -47,20 +42,17 @@ public:
// TODO: warn/notify if ec set ?
}
/**
* Get the native path for the temporary directory
*/
/// Get the native path for the temporary directory
[[nodiscard]] std::string
path() const
{
return path_.string();
}
/**
* Get the native path for the a file.
*
* The file does not need to exist.
*/
/** Get the native path for the a file.
The file does not need to exist.
*/
[[nodiscard]] std::string
file(std::string const& name) const
{

View File

@@ -85,15 +85,14 @@ XorShiftEngine<Unused>::murmurhash3(result_type x) -> result_type
} // namespace detail
/**
* XOR-shift Generator.
*
* Meets the requirements of UniformRandomNumberGenerator.
*
* Simple and fast RNG based on:
* http://xorshift.di.unimi.it/xorshift128plus.c
* does not accept seed==0
*/
/** XOR-shift Generator.
Meets the requirements of UniformRandomNumberGenerator.
Simple and fast RNG based on:
http://xorshift.di.unimi.it/xorshift128plus.c
does not accept seed==0
*/
using xor_shift_engine = detail::XorShiftEngine<>;
} // namespace beast

View File

@@ -24,49 +24,42 @@ enum class Type : std::uint8_t {
class Condition
{
public:
/**
* The largest binary condition we support.
*
* @note This value will be increased in the future, but it
* must never decrease, as that could cause conditions
* that were previously considered valid to no longer
* be allowed.
*/
/** The largest binary condition we support.
@note This value will be increased in the future, but it
must never decrease, as that could cause conditions
that were previously considered valid to no longer
be allowed.
*/
static constexpr std::size_t kMaxSerializedCondition = 128;
/**
* Load a condition from its binary form
*
* @param s The buffer containing the fulfillment to load.
* @param ec Set to the error, if any occurred.
*
* The binary format for a condition is specified in the
* cryptoconditions RFC. See:
*
* https://tools.ietf.org/html/draft-thomas-crypto-conditions-02#section-7.2
*/
/** Load a condition from its binary form
@param s The buffer containing the fulfillment to load.
@param ec Set to the error, if any occurred.
The binary format for a condition is specified in the
cryptoconditions RFC. See:
https://tools.ietf.org/html/draft-thomas-crypto-conditions-02#section-7.2
*/
static std::unique_ptr<Condition>
deserialize(Slice s, std::error_code& ec);
public:
Type type;
/**
* An identifier for this condition.
*
* This fingerprint is meant to be unique only with
* respect to other conditions of the same type.
*/
/** An identifier for this condition.
This fingerprint is meant to be unique only with
respect to other conditions of the same type.
*/
Buffer fingerprint;
/**
* The cost associated with this condition.
*/
/** The cost associated with this condition. */
std::uint32_t cost;
/**
* For compound conditions, set of conditions includes
*/
/** For compound conditions, set of conditions includes */
std::set<Type> subtypes;
Condition(Type t, std::uint32_t c, Slice fp) : type(t), fingerprint(fp), cost(c)

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