Compare commits

...

162 Commits

Author SHA1 Message Date
Luc des Trois Maisons
80090fb327 Stub mpt_verify_send_proof for throughput ceiling measurement
Skip bulletproof range proof verification in ConfidentialMPTSend to
measure the upper bound on Send throughput when verification is free.
NOT FOR PRODUCTION USE.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-06-05 16:21:07 -04:00
Peter Chen
dacd108657 Refactor confidential Test into 2 files (#7351) 2026-05-29 14:14:41 -04:00
Peter Chen
5869c23ecd Add specific checks for COA and OA (#7275) 2026-05-26 13:44:36 -04:00
yinyiqian1
ca7da3600f Add Batch + Delegation + Confidential tests (#7279) 2026-05-15 14:08:58 -04:00
Peter Chen
bab0c48d01 add amm pseudo account test with confidential Transfer (#7276) 2026-05-15 10:26:43 -04:00
Peter Chen
71983a59b6 add public MPT txn after Clearing Confidential Flag (#7113) 2026-05-13 09:57:18 -04:00
yinyiqian1
70f03eba66 Update error code for transfer rate error (#7115) 2026-05-12 13:31:13 -04:00
yinyiqian1
d7158abb63 Enforce zero transfer rate for confidential MPT (#7106) 2026-05-11 11:35:44 -04:00
yinyiqian1
c5cfeefc44 refactor and check deposit preauth before ZK proof (#7085) 2026-05-07 11:13:11 -04:00
yinyiqian1
ed6de36cb4 Increase confidential transactions fee (#7063) 2026-05-06 17:15:39 -04:00
Shawn Xie
b831b661ed Merge develop into confidential-transfer
Merge `develop` into `confidential-transfer`
2026-05-04 20:45:24 -04:00
Shawn Xie
cd193bba31 exclude bugprone access 2026-05-04 19:40:27 -04:00
Shawn Xie
086d95aa2c exclude constness for ConfidentialTransfer test file 2026-05-04 18:03:51 -04:00
Shawn Xie
6960e3a234 exclude const clang tidy 2026-05-04 17:20:48 -04:00
Shawn Xie
d7d9e54f92 fix const 2026-05-04 16:08:55 -04:00
Shawn Xie
541c4afeca clang tidy 2026-05-04 15:45:12 -04:00
Shawn Xie
64b5c3cf8f update delegable test cnt 2026-05-04 15:12:18 -04:00
Shawn Xie
feb9782387 fix autogen 2026-05-04 14:53:46 -04:00
Shawn Xie
aa55d7e360 Merge branch 'ripple/confidential-transfer' into ct-merge-dev-may-4 2026-05-04 14:39:54 -04:00
Shawn Xie
f1de2738a3 Fix clang tidy and compile errors 2026-05-04 14:39:03 -04:00
yinyiqian1
cad129921d add IssuerEncryptedBalance check in ConvertBack (#7060)
Co-authored-by: Peter Chen <34582813+PeterChen13579@users.noreply.github.com>
2026-05-04 14:32:23 -04:00
Shawn Xie
5afa29cd39 Merge remote-tracking branch 'upstream/develop' into ct-merge-dev-may-4
# Conflicts:
#	include/xrpl/protocol/detail/features.macro
#	include/xrpl/protocol/detail/ledger_entries.macro
#	include/xrpl/protocol/detail/secp256k1.h
#	include/xrpl/protocol/detail/transactions.macro
#	src/libxrpl/ledger/helpers/TokenHelpers.cpp
#	src/libxrpl/protocol/PublicKey.cpp
#	src/libxrpl/tx/invariants/MPTInvariant.cpp
#	src/libxrpl/tx/transactors/token/MPTokenIssuanceSet.cpp
#	src/test/app/Delegate_test.cpp
#	src/test/jtx/impl/mpt.cpp
#	src/test/jtx/mpt.h
2026-05-04 13:51:58 -04:00
Ayaz Salikhov
d050073842 ci: Rewrite clang-tidy workflow(s) in a reusable manner (#7062) 2026-05-04 12:51:07 +00:00
Alex Kremer
8490206228 chore: Ignore identifier-naming update in git blame (#7066)
Co-authored-by: Bart <bthomee@users.noreply.github.com>
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
2026-05-03 21:42:44 +00:00
Alex Kremer
8995564ed6 refactor: Enable clang-tidy readability-identifier-naming check (#6571) 2026-05-03 10:31:53 +00:00
Shawn Xie
9a62a1e471 fix: add credential amendment check and more refactoring (#7041) 2026-05-01 12:25:01 -04:00
Bart
182d844996 refactor: Revert certain Throws by LogicErrors (#7036)
Co-authored-by: Bart <11445373+bthomee@users.noreply.github.com>
2026-05-01 09:50:00 +00:00
Ayaz Salikhov
37b895b678 ci: Rename print-env -> print-build-env (#7061) 2026-05-01 09:44:52 +00:00
Peter Chen
cc58844d49 Merge pull request #7048 from PeterChen13579/add_defensive_checks
add defensive checks
2026-04-30 15:12:06 -04:00
Peter Chen
58337c61c5 Fix comments 2026-04-30 14:36:19 -04:00
Pratik Mankawde
c6053f5d64 fix: Gate -mcmodel flags to x86_64 in sanitizer builds (#7049)
Signed-off-by: Pratik Mankawde <3397372+pratikmankawde@users.noreply.github.com>
2026-04-30 13:33:33 +00:00
Vito Tumas
31180f94c2 fix: Prevents overwriting a bool value in an invariant (#6609)
Co-authored-by: Ed Hennis <ed@ripple.com>
2026-04-30 13:05:09 +00:00
Pratik Mankawde
6407f0fa52 fix: Address code review comments regarding boost::coroutine2 (#6977)
Signed-off-by: Pratik Mankawde <3397372+pratikmankawde@users.noreply.github.com>
2026-04-30 10:36:12 +00:00
Bart
4d0ea8ae36 refactor: Apply various minor improvements and corrections (#7045)
Co-authored-by: Bart <11445373+bthomee@users.noreply.github.com>
2026-04-30 10:22:11 +00:00
Zhiyuan Wang
dbd646bd53 fix: Store Delegate object in delegating and authorized account directories for proper deletion (#6681) 2026-04-29 18:17:01 +00:00
Ayaz Salikhov
6ae090ba45 ci: Use print-env from XRPLF/actions (#7052) 2026-04-29 18:14:16 +00:00
Mayukha Vadari
7be98d95de fix: Make assorted RPC fixes (#6529)
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2026-04-29 18:05:34 +00:00
Peter Chen
d09352af59 add another check 2026-04-29 13:36:20 -04:00
Peter Chen
7fad75d2b2 add test 2026-04-29 12:10:23 -04:00
Peter Chen
5f1c3ba4eb add defensive checks 2026-04-29 11:28:56 -04:00
Alex Kremer
f7275b7ad9 chore: Enable clang-tidy v21 new checks (#7031) 2026-04-29 15:17:35 +00:00
Shawn Xie
9bfd78e2fc Add ZKP and ciphertext malleability tests (#6999) 2026-04-28 11:25:40 -04:00
Jingchen
46b997b774 feat: Create new transaction testing framework TxTest (#6537)
Signed-off-by: JCW <a1q123456@users.noreply.github.com>
Co-authored-by: xrplf-ai-reviewer[bot] <266832837+xrplf-ai-reviewer[bot]@users.noreply.github.com>
Co-authored-by: Copilot <copilot@github.com>
2026-04-28 14:16:10 +00:00
Vito Tumas
147da57348 feat: Add cleanup amendment for 3.2.0 (#7037) 2026-04-28 10:22:32 +00:00
Pratik Mankawde
3547112540 fix: Fix ubsan flagged issues (#6151)
Signed-off-by: Pratik Mankawde <3397372+pratikmankawde@users.noreply.github.com>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
Co-authored-by: xrplf-ai-reviewer[bot] <266832837+xrplf-ai-reviewer[bot]@users.noreply.github.com>
2026-04-27 20:34:16 +00:00
Shawn Xie
5a643b1a7f fix: assorted safety checks (#7030) 2026-04-27 14:36:54 -04:00
yinyiqian1
8457b91b10 Test inconsistent C1 for ConfidentialMPTSend (#7017) 2026-04-24 15:03:26 -04:00
yinyiqian1
4520de22ef Merge pull request #7002 from yinyiqian1/merge-ct2
Merge develop into confidential-transfer
2026-04-23 12:24:22 -04:00
yinyiqian1
b0386622ca fix clang-tidy 2026-04-23 11:38:05 -04:00
yinyiqian1
c53d6aca08 resolve conflicts 2026-04-23 01:05:20 -04:00
yinyiqian1
be8de20a0b Merge branch 'develop' into merge-ct2 2026-04-23 00:41:44 -04:00
yinyiqian1
235547f460 Revert "Merge develop into ConfidentialTransfer (#6987)" (#7001) 2026-04-22 23:57:01 -04:00
yinyiqian1
1e73f3f3ff Merge develop into ConfidentialTransfer (#6987)
Signed-off-by: dependabot[bot] <support@github.com>
Signed-off-by: chuanshanjida <chuanshanjida@outlook.com>
Co-authored-by: Ed Hennis <ed@ripple.com>
Co-authored-by: Bart <bthomee@users.noreply.github.com>
Co-authored-by: Bart <11445373+bthomee@users.noreply.github.com>
Co-authored-by: Zhiyuan Wang <96991820+Kassaking7@users.noreply.github.com>
Co-authored-by: Alex Kremer <akremer@ripple.com>
Co-authored-by: Ayaz Salikhov <mathbunnyru@users.noreply.github.com>
Co-authored-by: Sergey Kuznetsov <skuznetsov@ripple.com>
Co-authored-by: JCW <a1q123456@users.noreply.github.com>
Co-authored-by: xrplf-ai-reviewer[bot] <266832837+xrplf-ai-reviewer[bot]@users.noreply.github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Gregory Tsipenyuk <gregtatcam@users.noreply.github.com>
Co-authored-by: chuanshanjida <chuanshanjida@outlook.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Co-authored-by: Vito Tumas <5780819+Tapanito@users.noreply.github.com>
2026-04-22 23:34:03 -04:00
Shawn Xie
2b65b740d0 Add destination tag to ConfidentialMPTSend (#6988) 2026-04-22 17:07:31 -04:00
yinyiqian1
f08121de35 Address coding style comments (#6966) 2026-04-20 13:31:09 -04:00
yinyiqian1
09778f2fec Support compact AND-composed sigma proof (#6859) 2026-04-16 17:51:31 -04:00
Shawn Xie
5229ff5a45 fix: fix pipeline failures (#6850) 2026-04-10 13:42:59 -04:00
Shawn Xie
6a8016f288 Merge develop into confidential-transfer 2026-04-09 11:54:29 -04:00
Shawn Xie
5d38603f90 fix compile and test failure 2026-04-09 11:22:31 -04:00
Shawn Xie
6f4fddc1ae Merge remote-tracking branch 'upstream/develop' into ct-merge-mpt-dex 2026-04-09 11:05:31 -04:00
Peter Chen
4ae17f193f Add JS fields required for Clio mpt_holder_api (#6810) 2026-04-09 10:49:10 -04:00
Peter Chen
36c805692a add batch tests (#6598) 2026-04-08 14:45:11 -04:00
yinyiqian1
5bd7ce1dfd Add tests for confidential delegation with tickets (#6808) 2026-04-08 13:20:59 -04:00
yinyiqian1
0d7bf6948e Add delegation tests for Confidential Transfers (#6729) 2026-04-07 17:45:26 -04:00
Peter Chen
58e38e05f9 add non-curve point tests (#6695) 2026-04-07 13:50:08 -04:00
Shawn Xie
697786afab Merge develop into confidential-transfer
- Resolved conflicts from autogen files and modularization
2026-04-06 15:45:06 -04:00
Shawn Xie
834cb72515 Update autogen files and delegable count 2026-04-06 15:00:07 -04:00
Shawn Xie
261e7d7769 Resolve conflicts 2026-04-06 12:11:45 -04:00
Shawn Xie
042b09563b Merge remote-tracking branch 'upstream/develop' into ct-merge 2026-04-06 11:57:06 -04:00
yinyiqian1
cc2d6cbff6 Integrate mpt_utility SDK for tests (#6705) 2026-04-02 12:04:05 -04:00
yinyiqian1
6f1232140b remove dead functions due to integration (#6683) 2026-03-30 16:37:55 -04:00
Peter Chen
13b3a243a3 add tests: encrypt under wrong public key (#6650) 2026-03-30 10:38:03 -04:00
yinyiqian1
2472ef7df7 Integrate mpt-crypto SDK lib for on-chain verification (#6679) 2026-03-27 16:26:37 -04:00
Shawn Xie
b34ecc476a Add ProofReader and auth/lock and overflow edge case checks (#6651) 2026-03-26 13:16:51 -04:00
Shawn Xie
4c0e6012e3 Handle edge cases checks in flag setting and token deletion (#6596) 2026-03-24 11:41:27 -04:00
Peter Chen
3f749ecf76 tests: add ticket tests (#6576) 2026-03-20 10:52:18 -04:00
Shawn Xie
a43cf94ff7 update sfBlindingFactor to type uint256 and refactor helper functions to return std::optional 2026-03-19 14:04:03 -04:00
Shawn Xie
9f4cf28aea Rename privacy flag and public key names (#6550)
Corresponding spec change:
https://github.com/XRPLF/XRPL-Standards/pull/501

### Field Renames (SFields)

| Before | After |
|--------|-------|
| `sfIssuerElGamalPublicKey` | `sfIssuerEncryptionKey` |
| `sfHolderElGamalPublicKey` | `sfHolderEncryptionKey` |
| `sfAuditorElGamalPublicKey` | `sfAuditorEncryptionKey` |

### Flag Renames

#### Transaction Flags (`tf`)

| Before | After |
|--------|-------|
| `tfMPTCanPrivacy` | `tfMPTCanConfidentialAmount` |

#### Ledger State Flags (`lsf`)

| Before | After |
|--------|-------|
| `lsfMPTCanPrivacy` | `lsfMPTCanConfidentialAmount` |

#### Ledger State Mutable Flags (`lsmf`)

| Before | After |
|--------|-------|
| `lsmfMPTCannotMutatePrivacy` |
`lsmfMPTCannotMutateCanConfidentialAmount` |

#### Transaction Mutable Flags (`tmf`)

| Before | After |
|--------|-------|
| `tmfMPTCannotMutatePrivacy` |
`tmfMPTCannotMutateCanConfidentialAmount` |
| `tmfMPTSetPrivacy` | `tmfMPTSetCanConfidentialAmount` |
| `tmfMPTClearPrivacy` | `tmfMPTClearCanConfidentialAmount` |
2026-03-17 10:53:17 -04:00
Peter Chen
c45177b69e add homomorphic tests (#6490) 2026-03-16 11:27:36 -04:00
Shawn Xie
d615098849 refactor: improve readability and clean up code from review comments (#6544) 2026-03-16 10:47:39 -04:00
Shawn Xie
eeb0d15ea9 refactor: return optional buffers for helper functions (#6520) 2026-03-11 12:02:27 -04:00
Shawn Xie
84cc8599af chore: Apply clang-format width 100 (#6516) 2026-03-10 11:24:01 -04:00
Shawn Xie
36c1c5f3cd Merge develop into confidential-transfer 2026-03-09 16:50:01 -04:00
Shawn Xie
2c94e213c2 Resolve conflicts 2026-03-09 15:32:42 -04:00
Shawn Xie
cbcc75ff2d Merge remote-tracking branch 'upstream/develop' into ct-merge-dev-100col 2026-03-09 15:25:10 -04:00
Shawn Xie
da7698974c Merge commit '2c1fad102353e11293e3edde1c043224e7d3e983' into ct-merge-dev-100col 2026-03-09 14:24:26 -04:00
Shawn Xie
a3a82faa3d fix conflicts and update modularization 2026-03-09 14:23:22 -04:00
Shawn Xie
fff83c1d4a Merge commit '25cca465538a56cce501477f9e5e2c1c7ea2d84c' into ct-merge-dev-100col 2026-03-09 14:02:31 -04:00
Shawn Xie
803ab67fc5 fix: address auditor feedbacks (#6511) 2026-03-09 13:59:32 -04:00
yinyiqian1
734b11c0e3 Support shared r for ConfidentialMPTSend equality proof (#6496)
* Support shared r for send equality proof
2026-03-06 18:28:35 -05:00
Peter Chen
fae34d0f36 tests: add replay tests to confidential MPT (#6451) 2026-03-04 13:43:43 -05:00
yinyiqian1
c52d317810 Update hashing and support ticket (#6444) 2026-02-27 11:50:22 -05:00
Peter Chen
c2f8b91397 Add invariants and tests (#6403) 2026-02-25 16:40:44 -05:00
Peter Chen
1ea9312946 update crypto-lib (#6418) 2026-02-25 12:18:31 -05:00
yinyiqian1
6ad60d7141 Support Range Proof for ConfidentialMPTSend (#6404)
- proving send amount m is in the range [0, 2^64)
- proving remaining balance b-m is in the range [0, 2^64)
2026-02-20 14:18:34 -05:00
Shawn Xie
94e911ed69 Add Range Proof Verification to ConvertBack (#6377) 2026-02-19 19:22:48 -05:00
Shawn Xie
b2c434dd73 Compress ElGamal Public Keys and Pedersen Commitments + Add Validation (#6385) 2026-02-19 08:41:15 -05:00
Peter Chen
b6d1a8d62b Test Auditor for Confidential Send and revealed R (#6320) 2026-02-17 14:27:33 -05:00
Shawn Xie
9d0c854139 Remove hardcoded library functions in ConfidentialTransfer (#6365) 2026-02-12 14:18:36 -05:00
Ayaz Salikhov
3a6ca681ff chore: Use mpt-crypto library (#6362) 2026-02-12 12:59:36 -05:00
Shawn Xie
a216824c15 Merge develop into confidential-transfer 2026-02-12 11:40:07 -05:00
Shawn Xie
90cf86a920 remove newline 2026-02-12 11:33:34 -05:00
Shawn Xie
e69d3c9bd7 Merge remote-tracking branch 'upstream/develop' into ct-merge-develop-lib 2026-02-12 11:14:40 -05:00
Shawn Xie
fd390a4f1c Add doxygen comments for new transactions and helper functions (#6332) 2026-02-10 10:51:50 -05:00
Shawn Xie
3941283438 Prefix confidential transfer transaction names with "MPT" (#6312) 2026-02-02 12:13:18 -05:00
Shawn Xie
86af28d91d Apply clang-format due to new column size (#6311) 2026-02-02 11:15:39 -05:00
Shawn Xie
41f7102fb8 Merge develop into ripple/confidential-transfer
Merge `develop` into `ripple/confidential-transfer`
2026-02-02 09:46:25 -05:00
Shawn Xie
66ed0fa452 namespace rename 2026-01-30 12:36:15 -05:00
Shawn Xie
cad8fb328a Merge branch 'develop' into ct-merge-develop-new 2026-01-30 12:25:55 -05:00
Shawn Xie
31346425f0 Merge commit '5f638f55536def0d88b970d1018a465a238e55f4' into ct-merge-develop-new 2026-01-30 12:25:36 -05:00
Shawn Xie
40bfaa25d2 Merge commit '92046785d1fea5f9efe5a770d636792ea6cab78b' into ct-merge-develop-new 2026-01-30 12:25:16 -05:00
Peter Chen
c4916f1251 Add more Auditor Tests for Convert and ConvertBack (#6255) 2026-01-29 12:17:19 -05:00
yinyiqian1
fc8b7898c5 Support Pedersen-ElGamal linkage for ConfidentialSend (#6289)
* support Pedersen Amount commitment for ConfidentialSend
* support Pedersen Balance commitment for ConfidentialSend
2026-01-29 11:18:46 -05:00
Shawn Xie
446f9fbe6d Reuse getConfidentialRecipientCount (#6281) 2026-01-26 13:04:02 -05:00
yinyiqian1
1297385b7e Support ConfidentialSend equality proof (#6274)
* Support ConfidentialSend equality proof

* resolve conflicts

* Add version check in send
2026-01-26 12:39:35 -05:00
Shawn Xie
114adc0c57 Pedersen commitment with ConvertBack and basic test (#6243) 2026-01-22 13:00:19 -05:00
yinyiqian1
1d349c32c5 fix encrypt zero balance and remove improper throw (#6242) 2026-01-20 12:27:44 -05:00
Shawn Xie
a5f20c129d Copying over pedersen commitment from crypto lib (#6238) 2026-01-19 13:56:10 -05:00
yinyiqian1
75d143a2a0 support new design to reveal blinding factor (#6237)
* reveal blinding factor and optimize
* schnorr proof is added for registering holder pub key
* clean env.close that already closed
* clean up the lib functions
2026-01-19 13:07:19 -05:00
Shawn Xie
e3da98e310 Update unit test framework to use shared random factor (#6233) 2026-01-16 16:36:49 -05:00
Shawn Xie
ec6d7cb91d Add equality proof to ConvertBack and refactor to reduce redundancy (#6220) 2026-01-16 10:28:55 -05:00
Shawn Xie
fa055c2bd5 Add auditing feature across confidential transfer transactions (#6200) 2026-01-14 11:18:06 -05:00
Shawn Xie
6c38086f17 ConfidentialConvert with Equality Proof (#6177) 2026-01-07 16:17:07 -05:00
Shawn Xie
3e9dc276ed add back clawback hash (#6175) 2026-01-06 12:21:00 -05:00
Shawn Xie
abf7a62b1f Refactor proof (#6168) 2026-01-05 12:00:41 -05:00
yinyiqian1
bd3a6e1631 Support equality proof for confidential clawback (#6149) 2026-01-02 11:48:06 -05:00
yinyiqian1
7c0bd419a4 support mutability for MPTPrivacy (#6137)
Update lsfMPTNoConfidentialTransfer to lsfMPTPrivacy
Add flag lsmfMPTPrivacy to control the mutability of lsfMPTPrivacy.
disallow mutating lsfMPTPrivacy when lsfMPTPrivacy is not set.
disallow mutating lsfMPTPrivacy when there's confidential outstanding amount.
2025-12-10 17:10:33 -05:00
yinyiqian1
d3126959e7 Merge pull request #6123 from yinyiqian1/merge
Merge remote-tracking branch 'origin/develop' into 'ripple/confidential-transfer'
2025-12-09 10:49:11 -05:00
yinyiqian1
67e8e89e0f copyright fix 2025-12-08 18:36:34 -05:00
yinyiqian1
4e4326a174 trigger ci 2025-12-08 18:25:47 -05:00
yinyiqian1
5397bd6d6e fix naming 2025-12-08 17:58:32 -05:00
yinyiqian1
6dece25cc3 fix test failure 2025-12-08 17:34:20 -05:00
yinyiqian1
d9da8733be resolve pre-commit clang-format 2025-12-08 16:45:41 -05:00
yinyiqian1
f6f51451e7 Merge remote-tracking branch 'origin/develop' into merge 2025-12-08 15:09:04 -05:00
Shawn Xie
b94c95b3e9 Change err code (#6050) 2025-11-18 14:19:41 -05:00
yinyiqian1
8365148b5c feat: support ConfidentialClawback and add tests (#6023) 2025-11-13 14:24:40 -05:00
Shawn Xie
c03866bf0f Variable rename (#6028) 2025-11-12 11:58:05 -05:00
Shawn Xie
389afc5f06 Add deposit preauth and other checks (#6011) 2025-11-10 10:52:23 -05:00
Shawn Xie
7b04eaae81 ConvertBack preclaim tests (#6006) 2025-11-05 13:58:52 -05:00
Shawn Xie
1343019509 ConvertBack tests (#6005) 2025-11-05 13:52:55 -05:00
Shawn Xie
cd75e630a2 Change ConfidentialSend preflight error code (#5994) 2025-11-03 18:46:27 -05:00
Shawn Xie
ec57fbdc5f Merge remote-tracking branch 'upstream/develop' into confidential-transfer 2025-11-03 18:42:41 -05:00
Shawn Xie
4fe67f5715 ConvertBack preflight tests (#5991) 2025-11-03 15:58:32 -05:00
Shawn Xie
44d885e39b Basic ConvertBack test (#5979) 2025-10-31 11:46:24 -04:00
yinyiqian1
3af758145c Check auth for ConfidentialSend (#5968) 2025-10-30 11:02:46 -04:00
yinyiqian1
f3d4d4341b add ciphertext check for ConfidentialSend (#5964) 2025-10-29 12:10:48 -04:00
Shawn Xie
ddb518ad09 MergeInbox tests (#5949) 2025-10-28 13:21:11 -04:00
Shawn Xie
3899e3f36c Add auth checks for convert (#5937) 2025-10-24 11:42:43 -04:00
yinyiqian1
e4a8ba51f9 check lock in ConfidentialSend (#5933) 2025-10-23 12:58:38 -04:00
Shawn Xie
35e4fad557 Add ciphertext check (#5930) 2025-10-23 11:57:18 -04:00
yinyiqian1
8e9cb3c1da support ConfidentialSend (#5921) 2025-10-22 12:02:00 -04:00
Shawn Xie
18d92058e3 MergeInbox (#5922) 2025-10-22 11:30:44 -04:00
Shawn Xie
f24d584f29 ConfidentialConvert tests (#5911) 2025-10-20 14:39:16 -04:00
Shawn Xie
da3fbcd25b Remove unused header file (#5908) 2025-10-17 16:42:08 -04:00
Shawn Xie
daa1303b5a Update decryption test helper function (#5907) 2025-10-17 14:19:19 -04:00
Shawn Xie
a636fe5871 Update test framework for encryption (#5906) 2025-10-17 14:04:54 -04:00
Shawn Xie
bbc3071fd1 Update mpt-crypto with zero encryption (#5905) 2025-10-17 11:41:39 -04:00
Shawn Xie
8fdc639206 ConfidentialConvert (#5901)
ConfidentialConvert and some test framework update
2025-10-16 14:31:14 -04:00
Shawn Xie
5a89641d98 remove duplicate code 2025-10-07 15:52:18 -04:00
Shawn Xie
beefa248a6 Merge remote-tracking branch 'upstream/develop' into confidential-transfer 2025-10-07 15:00:14 -04:00
Shawn Xie
e919a25ecb Merge develop into ripple/confidential-transfer (#5835)
* Fix: Don't flag consensus as stalled prematurely (#5658)

Fix stalled consensus detection to prevent false positives in situations where there are no disputed transactions.

Stalled consensus detection was added to 2.5.0 in response to a network consensus halt that caused a round to run for over an hour. However, it has a flaw that makes it very easy to have false positives. Those false positives are usually mitigated by other checks that prevent them from having an effect, but there have been several instances of validators "running ahead" because there are circumstances where the other checks are "successful", allowing the stall state to be checked.

* Set version to 2.5.1

* fix: Skip processing transaction batch if the batch is empty (#5670)

Avoids an assertion failure in NetworkOPsImp::apply in the unlikely event that all incoming transactions are invalid.

* Fix: EscrowTokenV1 (#5571)

* resolves an accounting inconsistency in MPT escrows where transfer fees were not properly handled when unlocking escrowed tokens.

* refactor: Wrap GitHub CI conditionals in curly braces (#5796)

This change wraps all GitHub conditionals in `${{ .. }}`, both for consistency and to reduce unexpected failures, because it was previously noticed that not all conditionals work without those curly braces.

* Only notify clio for PRs targeting the release and master branches (#5794)

Clio should only be notified when releases are about to be made, instead of for all PR, so this change only notifies Clio when a PR targets the release or master branch.

* Support DynamicMPT XLS-94d (#5705)

* extends the functionality of the MPTokenIssuanceSet transaction, allowing the issuer to update fields or flags that were explicitly marked as mutable during creation.

* Bugfix: Adds graceful peer disconnection (#5669)

The XRPL establishes connections in three stages: first a TCP connection, then a TLS/SSL handshake to secure the connection, and finally an upgrade to the bespoke XRP Ledger peer-to-peer protocol. During connection termination, xrpld directly closes the TCP connection, bypassing the TLS/SSL shutdown handshake. This makes peer disconnection diagnostics more difficult - abrupt TCP termination appears as if the peer crashed rather than disconnected gracefully.

This change refactors the connection lifecycle with the following changes:
- Enhanced outgoing connection logic with granular timeouts for each connection stage (TCP, TLS, XRPL handshake) to improve diagnostic capabilities
- Updated both PeerImp and ConnectAttempt to use proper asynchronous TLS shutdown procedures for graceful connection termination

* Downgrade to boost 1.83

* Set version to 2.6.1-rc1

* chore: Use self hosted windows runners (#5780)

This changes switches from the GitHub-managed Windows runners to self-hosted runners to significantly reduce build time.

* Rename mutable flags (#5797)

This is a minor change on top of #5705

* fix(amendment): Add missing fields for keylets to ledger objects (#5646)

This change adds a fix amendment (`fixIncludeKeyletFields`) that adds:
* `sfSequence` to `Escrow` and `PayChannel`
* `sfOwner` to `SignerList`
* `sfOracleDocumentID` to `Oracle`

This ensures that all ledger entries hold all the information needed to determine their keylet.

* chore: Limits CI build and test parallelism to reduce resource contention (#5799)

GitHub runners have a limit on how many concurrent jobs they can actually process (even though they will try to run them all at the same time), and similarly the Conan remote cannot handle hundreds of concurrent requests. Previously, the Conan dependency uploading was already limited to max 10 jobs running in parallel, and this change makes the same change to the build+test workflow.

* chore: Build and test all configs for daily scheduled run (#5801)

This change re-enables building and testing all configurations, but only for the daily scheduled run. Previously all configurations were run for each merge into the develop branch, but that overwhelmed both the GitHub runners and the Conan remote, and thus they were limited to just a subset of configurations. Now that the number of jobs is limited via `max-parallel: 10`, we should be able to safely enable building all configurations again. However, building them all once a day instead of for each PR merge should be sufficient.

* chore: Add unit tests dir to code coverage excludes (#5803)

This change excludes unit test code from code coverage reporting.

* refactor: Modularise ledger (#5493)

This change moves the ledger code to libxrpl.

* Mark PermissionDelegation as unsupported

* Set version to 2.6.1-rc2

* Miscellaneous refactors and updates (#5590)

- Added a new Invariant: `ValidPseudoAccounts` which checks that all pseudo-accounts behave consistently through creation and updates, and that no "real" accounts look like pseudo-accounts (which means they don't have a 0 sequence). 
- `to_short_string(base_uint)`. Like `to_string`, but only returns the first 8 characters. (Similar to how a git commit ID can be abbreviated.) Used as a wrapped sink to prefix most transaction-related messages. More can be added later.
- `XRPL_ASSERT_PARTS`. Convenience wrapper for `XRPL_ASSERT`, which takes the `function` and `description` as separate parameters.
- `SField::sMD_PseudoAccount`. Metadata option for `SField` definitions to indicate that the field, if set in an `AccountRoot` indicates that account is a pseudo-account. Removes the need for hard-coded field lists all over the place. Added the flag to `AMMID` and `VaultID`.
- Added functionality to `SField` ctor to detect both code and name collisions using asserts. And require all SFields to have a name
- Convenience type aliases `STLedgerEntry::const_pointer` and `STLedgerEntry::const_ref`. (`SLE` is an alias to `STLedgerEntry`.)
- Generalized `feeunit.h` (`TaggedFee`) into `unit.h` (`ValueUnit`) and added new "BIPS"-related tags for future use. Also refactored the type restrictions to use Concepts.
- Restructured `transactions.macro` to do two big things
	1. Include the `#include` directives for transactor header files directly in the macro file. Removes the need to update `applySteps.cpp` and the resulting conflicts.
	2. Added a `privileges` parameter to the `TRANSACTION` macro, which specifies some of the operations a transaction is allowed to do. These `privileges` are enforced by invariant checks. Again, removed the need to update scattered lists of transaction types in various checks.
- Unit tests:
	1.  Moved more helper functions into `TestHelpers.h` and `.cpp`. 
	2. Cleaned up the namespaces to prevent / mitigate random collisions and ambiguous symbols, particularly in unity builds.
	3. Generalized `Env::balance` to add support for `MPTIssue` and `Asset`.
	4. Added a set of helper classes to simplify `Env` transaction parameter classes: `JTxField`, `JTxFieldWrapper`, and a bunch of classes derived or aliased from it. For an example of how awesome it is, check the changes `src/test/jtx/escrow.h` for how much simpler the definitions are for `finish_time`, `cancel_time`, `condition`, and `fulfillment`. 
	5. Generalized several of the amount-related helper classes to understand `Asset`s.
     6. `env.balance` for an MPT issuer will return a negative number (or 0) for consistency with IOUs.

* refactor: Simplify STParsedJSON with some helper functions (#5591)

- Add code coverage for STParsedJSON edge cases

Co-authored-by: Denis Angell <dangell@transia.co>

* test: Add STInteger and STParsedJSON tests (#5726)

This change is to improve code coverage (and to simplify #5720 and #5725); there is otherwise no change in functionality. The change adds basic tests for `STInteger` and `STParsedJSON`, so it becomes easier to test smaller changes to the types, as well as removes `STParsedJSONArray`, since it is not used anywhere (including in Clio).

* Revert "Update Conan dependencies: OpenSSL" (#5807)

This change reverts #5617, because it will require extensive testing that will take up more time than we have before the next scheduled release.

Reverting this change does not mean we are abandoning it. We aim to pick it back up once there's a sufficient time window to allow for testing on multiple distros running a mixture of OpenSSL 1.x and 3.x.

* docs: Add warning about using std::counting_semaphore (#5595)

This adds a comment to avoid using `std::counting_semaphore` until the minimum compiler versions of GCC and Clang have been updated to no longer contain the bug that is present in older compilers.

* Improve ValidatorList invalid UNL manifest logging (#5804)

This change raises logging severity from `INFO` to `WARN` when handling UNL manifest signed with an unexpected / invalid key. It also changes the internal error code for an invalid format of UNL manifest to `invalid` (from `untrusted`).

This is a follow up to problems experienced by an UNL node due to old manifest key configured in `validators.txt`, which would be easier to diagnose with improved logging.

It also replaces a log line with `UNREACHABLE` for an impossible situation when we match UNL manifest key against a configured key which has an invalid type (we cannot configure such a key because of checks when loading configured keys).

* chore: Pin all CI Docker tags (#5813)

To avoid surprises and ensure reproducibility, this change pins all CI Docker image tags to the latest version in the XRPLF/CI repo.

* change `fixPriceOracleOrder` to `Supported::yes` (#5749)

* fix: Address http header case sensitivity (#5767)

This change makes the regex in `HttpClient.cpp` that matches the content-length http header case insensitive to improve compatibility, as http headers are case insensitive.

* test: add more comprehensive tests for `FeeVote` (#5746)

This change adds more comprehensive tests for the `FeeVote` module, which previously only checked the basics, and not the more comprehensive flows in that class.

* ci: Call all reusable workflows reusable (#5818)

* Add `STInt32` as a new `SType` (#5788)

This change adds `STInt32` as a new `SType` under the `STInteger` umbrella, with `SType` value `12`. This is the first and only `STInteger` type that supports negative values.

* switch `fixIncludeKeyletFields` to `Supported::yes` (#5819)

* refactor: Restructure Transactor::preflight to reduce boilerplate (#5592)

* Restructures `Transactor::preflight` to create several functions that will remove the need for error-prone boilerplate code in derived classes' implementations of `preflight`.

* refactor: Add support for extra transaction signatures (#5594)

* Restructures Transactor signature checking code to be able to handle a `sigObject`, which may be the full transaction, or may be an object field containing a separate signature. Either way, the `sigObject` can be a single- or multi-sign signature.

* ci: Upload artifacts during build and test in a separate job (#5817)

* chore: Set free-form CI inputs as env vars (#5822)

This change moves CI values that could be user-provided into environment variables.

* Rename flags for DynamicMPT (#5820)

* Set version to 2.6.1

* fix: FD/handle guarding + exponential backoff (#5823)

* fix: Transaction sig checking functions do not get a full context (#5829)

Fixes a (currently harmless) bug introduced by PR #5594

* Remove bogus coverage warning (#5838)

* fix return type

---------

Co-authored-by: Ed Hennis <ed@ripple.com>
Co-authored-by: Jingchen <a1q123456@users.noreply.github.com>
Co-authored-by: Denis Angell <dangell@transia.co>
Co-authored-by: Bart <bthomee@users.noreply.github.com>
Co-authored-by: yinyiqian1 <yqian@ripple.com>
Co-authored-by: Vito Tumas <5780819+Tapanito@users.noreply.github.com>
Co-authored-by: Bronek Kozicki <brok@incorrekt.com>
Co-authored-by: Mayukha Vadari <mvadari@ripple.com>
Co-authored-by: Valentin Balaschenko <13349202+vlntb@users.noreply.github.com>
Co-authored-by: tequ <git@tequ.dev>
Co-authored-by: Ayaz Salikhov <mathbunnyru@users.noreply.github.com>
2025-10-07 14:14:34 -04:00
Shawn Xie
c3fdbc0430 SFields and formats (#5795) 2025-10-01 17:02:11 +00:00
1556 changed files with 82837 additions and 60190 deletions

View File

@@ -1,11 +1,10 @@
---
# This entire group of checks was applied to all cpp files but not all header files.
# ---
Checks: "-*,
bugprone-argument-comment,
bugprone-assert-side-effect,
bugprone-bad-signal-to-kill-thread,
bugprone-bool-pointer-implicit-conversion,
bugprone-capturing-this-in-member-variable,
bugprone-casting-through-void,
bugprone-chained-comparison,
bugprone-compare-pointer-to-member-virtual-function,
@@ -25,6 +24,7 @@ Checks: "-*,
bugprone-lambda-function-name,
bugprone-macro-parentheses,
bugprone-macro-repeated-side-effects,
bugprone-misleading-setter-of-reference,
bugprone-misplaced-operator-in-strlen-in-alloc,
bugprone-misplaced-pointer-arithmetic-in-alloc,
bugprone-misplaced-widening-cast,
@@ -73,10 +73,10 @@ Checks: "-*,
bugprone-unhandled-self-assignment,
bugprone-unique-ptr-array-mismatch,
bugprone-unsafe-functions,
bugprone-use-after-move,
bugprone-unused-local-non-trivial-variable,
bugprone-unused-raii,
bugprone-unused-return-value,
bugprone-unused-local-non-trivial-variable,
bugprone-use-after-move,
bugprone-virtual-near-miss,
cppcoreguidelines-init-variables,
cppcoreguidelines-misleading-capture-default-by-value,
@@ -85,8 +85,10 @@ Checks: "-*,
cppcoreguidelines-pro-type-static-cast-downcast,
cppcoreguidelines-rvalue-reference-param-not-moved,
cppcoreguidelines-use-default-member-init,
cppcoreguidelines-use-enum-class,
cppcoreguidelines-virtual-class-destructor,
hicpp-ignored-remove-result,
llvm-namespace-comment,
misc-const-correctness,
misc-definitions-in-headers,
misc-header-include-cycle,
@@ -98,6 +100,7 @@ Checks: "-*,
misc-unused-alias-decls,
misc-unused-using-decls,
modernize-concat-nested-namespaces,
modernize-deprecated-headers,
modernize-make-shared,
modernize-make-unique,
modernize-pass-by-value,
@@ -109,11 +112,10 @@ Checks: "-*,
modernize-use-nodiscard,
modernize-use-override,
modernize-use-ranges,
modernize-use-scoped-lock,
modernize-use-starts-ends-with,
modernize-use-std-numbers,
modernize-use-using,
modernize-deprecated-headers,
llvm-namespace-comment,
performance-faster-string-find,
performance-for-range-copy,
performance-implicit-conversion-in-loop,
@@ -122,6 +124,7 @@ Checks: "-*,
performance-move-constructor-init,
performance-no-automatic-move,
performance-trivially-destructible,
readability-ambiguous-smartptr-reset-call,
readability-avoid-nested-conditional-operator,
readability-avoid-return-with-void-value,
readability-braces-around-statements,
@@ -132,6 +135,7 @@ Checks: "-*,
readability-duplicate-include,
readability-else-after-return,
readability-enum-initial-value,
readability-identifier-naming,
readability-implicit-bool-conversion,
readability-make-member-function-const,
readability-math-missing-parentheses,
@@ -149,52 +153,47 @@ Checks: "-*,
readability-use-std-min-max
"
# ---
# other checks that have issues that need to be resolved:
#
# readability-inconsistent-declaration-parameter-name, # in this codebase this check will break a lot of arg names
# readability-static-accessed-through-instance, # this check is probably unnecessary. it makes the code less readable
# readability-identifier-naming, # https://github.com/XRPLF/rippled/pull/6571
# ---
#
CheckOptions:
readability-braces-around-statements.ShortStatementLines: 2
# readability-identifier-naming.MacroDefinitionCase: UPPER_CASE
# readability-identifier-naming.ClassCase: CamelCase
# readability-identifier-naming.StructCase: CamelCase
# readability-identifier-naming.UnionCase: CamelCase
# readability-identifier-naming.EnumCase: CamelCase
# readability-identifier-naming.EnumConstantCase: CamelCase
# readability-identifier-naming.ScopedEnumConstantCase: CamelCase
# readability-identifier-naming.GlobalConstantCase: UPPER_CASE
# readability-identifier-naming.GlobalConstantPrefix: "k"
# readability-identifier-naming.GlobalVariableCase: CamelCase
# readability-identifier-naming.GlobalVariablePrefix: "g"
# readability-identifier-naming.ConstexprFunctionCase: camelBack
# readability-identifier-naming.ConstexprMethodCase: camelBack
# readability-identifier-naming.ClassMethodCase: camelBack
# readability-identifier-naming.ClassMemberCase: camelBack
# readability-identifier-naming.ClassConstantCase: UPPER_CASE
# readability-identifier-naming.ClassConstantPrefix: "k"
# readability-identifier-naming.StaticConstantCase: UPPER_CASE
# readability-identifier-naming.StaticConstantPrefix: "k"
# readability-identifier-naming.StaticVariableCase: UPPER_CASE
# readability-identifier-naming.StaticVariablePrefix: "k"
# readability-identifier-naming.ConstexprVariableCase: UPPER_CASE
# readability-identifier-naming.ConstexprVariablePrefix: "k"
# readability-identifier-naming.LocalConstantCase: camelBack
# readability-identifier-naming.LocalVariableCase: camelBack
# readability-identifier-naming.TemplateParameterCase: CamelCase
# readability-identifier-naming.ParameterCase: camelBack
# readability-identifier-naming.FunctionCase: camelBack
# readability-identifier-naming.MemberCase: camelBack
# readability-identifier-naming.PrivateMemberSuffix: _
# readability-identifier-naming.ProtectedMemberSuffix: _
# readability-identifier-naming.PublicMemberSuffix: ""
# readability-identifier-naming.FunctionIgnoredRegexp: ".*tag_invoke.*"
readability-identifier-naming.MacroDefinitionCase: UPPER_CASE
readability-identifier-naming.ClassCase: CamelCase
readability-identifier-naming.StructCase: CamelCase
readability-identifier-naming.UnionCase: CamelCase
readability-identifier-naming.EnumCase: CamelCase
readability-identifier-naming.EnumConstantCase: CamelCase
readability-identifier-naming.ScopedEnumConstantCase: CamelCase
readability-identifier-naming.GlobalConstantCase: UPPER_CASE
readability-identifier-naming.GlobalConstantPrefix: "k"
readability-identifier-naming.GlobalVariableCase: CamelCase
readability-identifier-naming.GlobalVariablePrefix: "g"
readability-identifier-naming.ConstexprFunctionCase: camelBack
readability-identifier-naming.ConstexprMethodCase: camelBack
readability-identifier-naming.ClassMethodCase: camelBack
readability-identifier-naming.ClassMemberCase: camelBack
readability-identifier-naming.ClassConstantCase: UPPER_CASE
readability-identifier-naming.ClassConstantPrefix: "k"
readability-identifier-naming.StaticConstantCase: UPPER_CASE
readability-identifier-naming.StaticConstantPrefix: "k"
readability-identifier-naming.StaticVariableCase: UPPER_CASE
readability-identifier-naming.StaticVariablePrefix: "k"
readability-identifier-naming.ConstexprVariableCase: UPPER_CASE
readability-identifier-naming.ConstexprVariablePrefix: "k"
readability-identifier-naming.LocalConstantCase: camelBack
readability-identifier-naming.LocalVariableCase: camelBack
readability-identifier-naming.TemplateParameterCase: CamelCase
readability-identifier-naming.ParameterCase: camelBack
readability-identifier-naming.FunctionCase: camelBack
readability-identifier-naming.MemberCase: camelBack
readability-identifier-naming.PrivateMemberSuffix: _
readability-identifier-naming.ProtectedMemberSuffix: _
readability-identifier-naming.PublicMemberSuffix: ""
readability-identifier-naming.GlobalFunctionIgnoredRegexp: "^(to_string|hash_append|tuple_hash)$"
bugprone-unsafe-functions.ReportMoreUnsafeFunctions: true
bugprone-unused-return-value.CheckedReturnTypes: ::std::error_code;::std::error_condition;::std::errc
misc-include-cleaner.IgnoreHeaders: ".*/(detail|impl)/.*;.*fwd\\.h(pp)?;time.h;stdlib.h;sqlite3.h;netinet/in\\.h;sys/resource\\.h;sys/sysinfo\\.h;linux/sysinfo\\.h;__chrono/.*;bits/.*;_abort\\.h;boost/uuid/uuid_hash.hpp;boost/beast/core/flat_buffer\\.hpp;boost/beast/http/field\\.hpp;boost/beast/http/dynamic_body\\.hpp;boost/beast/http/message\\.hpp;boost/beast/http/read\\.hpp;boost/beast/http/write\\.hpp;openssl/obj_mac\\.h"
#
HeaderFilterRegex: '^.*/(test|xrpl|xrpld)/.*\.(h|hpp)$'
HeaderFilterRegex: '^.*/(test|xrpl|xrpld)/.*\.(h|hpp|ipp)$'
ExcludeHeaderFilterRegex: '^.*/protocol_autogen/.*\.(h|hpp)$'
WarningsAsErrors: "*"

View File

@@ -5,6 +5,8 @@
# This file is sorted in reverse chronological order, with the most recent commits at the top.
# The commits listed here are ignored by git blame, which is useful for formatting-only commits that would otherwise obscure the history of changes to a file.
# refactor: Enable clang-tidy `readability-identifier-naming` check (#6571)
8995564ed6b9e453e144bb663303072a3c1ba305
# refactor: Enable remaining clang-tidy `cppcoreguidelines` checks (#6538)
72f4cb097f626b08b02fc3efcb4aa11cb2e7adb8
# refactor: Rename system name from 'ripple' to 'xrpld' (#6347)

View File

@@ -1,43 +0,0 @@
name: Print build environment
description: "Print environment and some tooling versions"
runs:
using: composite
steps:
- name: Check configuration (Windows)
if: ${{ runner.os == 'Windows' }}
shell: bash
run: |
echo 'Checking environment variables.'
set
- name: Check configuration (Linux and macOS)
if: ${{ runner.os == 'Linux' || runner.os == 'macOS' }}
shell: bash
run: |
echo 'Checking path.'
echo ${PATH} | tr ':' '\n'
echo 'Checking environment variables.'
env | sort
echo 'Checking compiler version.'
${{ runner.os == 'Linux' && '${CC}' || 'clang' }} --version
echo 'Checking Ninja version.'
ninja --version
echo 'Checking nproc version.'
nproc --version
- name: Check configuration (all)
shell: bash
run: |
echo 'Checking Ccache version.'
ccache --version
echo 'Checking CMake version.'
cmake --version
echo 'Checking Conan version.'
conan --version

View File

@@ -33,17 +33,6 @@ updates:
prefix: "ci: [DEPENDABOT] "
target-branch: develop
- package-ecosystem: github-actions
directory: .github/actions/print-env/
schedule:
interval: weekly
day: monday
time: "04:00"
timezone: Etc/GMT
commit-message:
prefix: "ci: [DEPENDABOT] "
target-branch: develop
- package-ecosystem: github-actions
directory: .github/actions/setup-conan/
schedule:

View File

@@ -188,10 +188,16 @@ test.toplevel > xrpl.json
test.unit_test > xrpl.basics
test.unit_test > xrpl.protocol
tests.libxrpl > xrpl.basics
tests.libxrpl > xrpl.core
tests.libxrpl > xrpl.json
tests.libxrpl > xrpl.ledger
tests.libxrpl > xrpl.net
tests.libxrpl > xrpl.nodestore
tests.libxrpl > xrpl.protocol
tests.libxrpl > xrpl.protocol_autogen
tests.libxrpl > xrpl.server
tests.libxrpl > xrpl.shamap
tests.libxrpl > xrpl.tx
xrpl.conditions > xrpl.basics
xrpl.conditions > xrpl.protocol
xrpl.core > xrpl.basics

View File

@@ -62,7 +62,7 @@ ${SED_COMMAND} -i 's@ripple/@xrpld/@g' src/test/core/Config_test.cpp
${SED_COMMAND} -i 's/Rippled/File/g' src/test/core/Config_test.cpp
# Restore the old config file name in the code that maintains support for now.
${SED_COMMAND} -i 's/configLegacyName = "xrpld.cfg"/configLegacyName = "rippled.cfg"/g' src/xrpld/core/detail/Config.cpp
${SED_COMMAND} -i 's/kCONFIG_LEGACY_NAME = "xrpld.cfg"/kCONFIG_LEGACY_NAME = "rippled.cfg"/g' src/xrpld/core/detail/Config.cpp
# Restore an URL.
${SED_COMMAND} -i 's/connect-your-xrpld-to-the-xrp-test-net.html/connect-your-rippled-to-the-xrp-test-net.html/g' cfg/xrpld-example.cfg

View File

@@ -90,7 +90,7 @@ ${SED_COMMAND} -i 's/www.ripple.com/www.xrpl.org/g' src/test/protocol/Seed_test.
# Restore specific changes.
${SED_COMMAND} -i 's@b5efcc/src/xrpld@b5efcc/src/ripple@' include/xrpl/protocol/README.md
${SED_COMMAND} -i 's/dbPrefix_ = "xrpldb"/dbPrefix_ = "rippledb"/' src/xrpld/app/misc/SHAMapStoreImp.h # cspell: disable-line
${SED_COMMAND} -i 's/configLegacyName = "xrpld.cfg"/configLegacyName = "rippled.cfg"/' src/xrpld/core/detail/Config.cpp
${SED_COMMAND} -i 's/kCONFIG_LEGACY_NAME = "xrpld.cfg"/kCONFIG_LEGACY_NAME = "rippled.cfg"/' src/xrpld/core/detail/Config.cpp
popd
echo "Renaming complete."

View File

@@ -51,20 +51,21 @@ def generate_strategy_matrix(all: bool, config: Config) -> list:
# Only generate a subset of configurations in PRs.
if not all:
# Debian:
# - Bookworm using GCC 13: Release on linux/amd64, set the reference
# fee to 500.
# - Bookworm using GCC 15: Debug on linux/amd64, enable code
# coverage (which will be done below).
# - Bookworm using GCC 13: Debug on linux/amd64, set the reference
# fee to 500 and enable code coverage (which will be done below).
# - Bookworm using GCC 15: Debug on linux/amd64, enable Address and
# UB sanitizers (which will be done below).
# - Bookworm using Clang 16: Debug on linux/amd64, enable voidstar.
# - Bookworm using Clang 17: Release on linux/amd64, set the
# reference fee to 1000.
# - Bookworm using Clang 20: Debug on linux/amd64.
# - Bookworm using Clang 20: Debug on linux/amd64, enable Address
# and UB sanitizers (which will be done below).
if os["distro_name"] == "debian":
skip = True
if os["distro_version"] == "bookworm":
if (
f"{os['compiler_name']}-{os['compiler_version']}" == "gcc-13"
and build_type == "Release"
and build_type == "Debug"
and architecture["platform"] == "linux/amd64"
):
cmake_args = f"-DUNIT_TEST_REFERENCE_FEE=500 {cmake_args}"
@@ -193,11 +194,11 @@ def generate_strategy_matrix(all: bool, config: Config) -> list:
):
continue
# Enable code coverage for Debian Bookworm using GCC 15 in Debug on
# linux/amd64
# Enable code coverage for Debian Bookworm using GCC 13 in Debug on
# linux/amd64.
if (
f"{os['distro_name']}-{os['distro_version']}" == "debian-bookworm"
and f"{os['compiler_name']}-{os['compiler_version']}" == "gcc-15"
and f"{os['compiler_name']}-{os['compiler_version']}" == "gcc-13"
and build_type == "Debug"
and architecture["platform"] == "linux/amd64"
):
@@ -234,23 +235,39 @@ def generate_strategy_matrix(all: bool, config: Config) -> list:
# Add the configuration to the list, with the most unique fields first,
# so that they are easier to identify in the GitHub Actions UI, as long
# names get truncated.
# Add Address and Thread (both coupled with UB) sanitizers for specific bookworm distros.
# Add Address and UB sanitizers as separate configurations for specific
# bookworm distros. Thread sanitizer is currently disabled (see below).
# GCC-Asan xrpld-embedded tests are failing because of https://github.com/google/sanitizers/issues/856
if (
os["distro_version"] == "bookworm"
and f"{os['compiler_name']}-{os['compiler_version']}" == "clang-20"
):
# Add ASAN + UBSAN configuration.
if os[
"distro_version"
] == "bookworm" and f"{os['compiler_name']}-{os['compiler_version']}" in [
"gcc-15",
"clang-20",
]:
# Add ASAN configuration.
configurations.append(
{
"config_name": config_name + "-asan-ubsan",
"config_name": config_name + "-asan",
"cmake_args": cmake_args,
"cmake_target": cmake_target,
"build_only": build_only,
"build_type": build_type,
"os": os,
"architecture": architecture,
"sanitizers": "address,undefinedbehavior",
"sanitizers": "address",
}
)
# Add UBSAN configuration.
configurations.append(
{
"config_name": config_name + "-ubsan",
"cmake_args": cmake_args,
"cmake_target": cmake_target,
"build_only": build_only,
"build_type": build_type,
"os": os,
"architecture": architecture,
"sanitizers": "undefinedbehavior",
}
)
# TSAN is deactivated due to seg faults with latest compilers.

View File

@@ -58,15 +58,12 @@ jobs:
# Keep the paths below in sync with those in `on-trigger.yml`.
.github/actions/build-deps/**
.github/actions/build-test/**
.github/actions/generate-version/**
.github/actions/setup-conan/**
.github/scripts/strategy-matrix/**
.github/workflows/reusable-build.yml
.github/workflows/reusable-build-test-config.yml
.github/workflows/reusable-build-test.yml
.github/workflows/reusable-clang-tidy.yml
.github/workflows/reusable-clang-tidy-files.yml
.github/workflows/reusable-strategy-matrix.yml
.github/workflows/reusable-test.yml
.github/workflows/reusable-upload-recipe.yml
@@ -176,4 +173,4 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Fail
run: false
run: exit 1

View File

@@ -15,15 +15,12 @@ on:
# Keep the paths below in sync with those in `on-pr.yml`.
- ".github/actions/build-deps/**"
- ".github/actions/build-test/**"
- ".github/actions/generate-version/**"
- ".github/actions/setup-conan/**"
- ".github/scripts/strategy-matrix/**"
- ".github/workflows/reusable-build.yml"
- ".github/workflows/reusable-build-test-config.yml"
- ".github/workflows/reusable-build-test.yml"
- ".github/workflows/reusable-clang-tidy.yml"
- ".github/workflows/reusable-clang-tidy-files.yml"
- ".github/workflows/reusable-strategy-matrix.yml"
- ".github/workflows/reusable-test.yml"
- ".github/workflows/reusable-upload-recipe.yml"

View File

@@ -14,7 +14,7 @@ on:
jobs:
# Call the workflow in the XRPLF/actions repo that runs the pre-commit hooks.
run-hooks:
uses: XRPLF/actions/.github/workflows/pre-commit.yml@9307df762265e15c745ddcdb38a581c989f7f349
uses: XRPLF/actions/.github/workflows/pre-commit.yml@5e942d61bf32f7557a7c159cfac4712a687b3e3a
with:
runs_on: ubuntu-latest
container: '{ "image": "ghcr.io/xrplf/ci/tools-rippled-pre-commit:sha-41ec7c1" }'

View File

@@ -116,7 +116,7 @@ jobs:
run: echo "CCACHE_LOGFILE=${{ runner.temp }}/ccache.log" >> "${GITHUB_ENV}"
- name: Print build environment
uses: ./.github/actions/print-env
uses: XRPLF/actions/print-build-env@59dec886e4afb05a1724443af08baccbc045b574
- name: Get number of processors
uses: XRPLF/actions/get-nproc@cf0433aa74563aead044a1e395610c96d65a37cf

View File

@@ -1,175 +0,0 @@
name: Run clang-tidy on files
on:
workflow_call:
inputs:
files:
description: "List of files to check (empty means check all files)"
type: string
default: ""
create_issue_on_failure:
description: "Whether to create an issue if the check failed"
type: boolean
default: false
defaults:
run:
shell: bash
env:
# Conan installs the generators in the build/generators directory, see the
# layout() method in conanfile.py. We then run CMake from the build directory.
BUILD_DIR: build
BUILD_TYPE: Release
jobs:
run-clang-tidy:
name: Run clang tidy
runs-on: ["self-hosted", "Linux", "X64", "heavy"]
container: "ghcr.io/xrplf/ci/debian-trixie:clang-21-sha-53033a2"
permissions:
issues: write
contents: read
steps:
- name: Checkout repository
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
- name: Prepare runner
uses: XRPLF/actions/prepare-runner@90f11ee655d1687824fb8793db770477d52afbab
with:
enable_ccache: false
- name: Print build environment
uses: ./.github/actions/print-env
- name: Get number of processors
uses: XRPLF/actions/get-nproc@cf0433aa74563aead044a1e395610c96d65a37cf
id: nproc
- name: Setup Conan
uses: ./.github/actions/setup-conan
- name: Build dependencies
uses: ./.github/actions/build-deps
with:
build_nproc: ${{ steps.nproc.outputs.nproc }}
build_type: ${{ env.BUILD_TYPE }}
log_verbosity: verbose
- name: Configure CMake
working-directory: ${{ env.BUILD_DIR }}
run: |
cmake \
-G 'Ninja' \
-DCMAKE_TOOLCHAIN_FILE:FILEPATH=build/generators/conan_toolchain.cmake \
-DCMAKE_BUILD_TYPE="${BUILD_TYPE}" \
-Dtests=ON \
-Dwerr=ON \
-Dxrpld=ON \
..
# clang-tidy needs headers generated from proto files
- name: Build libxrpl.libpb
working-directory: ${{ env.BUILD_DIR }}
run: |
ninja -j ${{ steps.nproc.outputs.nproc }} xrpl.libpb
- name: Run clang tidy
id: run_clang_tidy
continue-on-error: true
env:
TARGETS: ${{ inputs.files != '' && inputs.files || 'src tests' }}
run: |
run-clang-tidy -j ${{ steps.nproc.outputs.nproc }} -p "${BUILD_DIR}" -quiet -fix -allow-no-checks ${TARGETS} 2>&1 | tee clang-tidy-output.txt
- name: Upload clang-tidy output
if: ${{ github.event.repository.visibility == 'public' && steps.run_clang_tidy.outcome != 'success' }}
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: clang-tidy-results
path: clang-tidy-output.txt
retention-days: 30
- name: Generate git diff
if: ${{ steps.run_clang_tidy.outcome != 'success' }}
run: |
git diff | tee clang-tidy-git-diff.txt
- name: Upload clang-tidy diff output
if: ${{ github.event.repository.visibility == 'public' && steps.run_clang_tidy.outcome != 'success' }}
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: clang-tidy-git-diff
path: clang-tidy-git-diff.txt
retention-days: 30
- name: Create an issue
if: ${{ steps.run_clang_tidy.outcome != 'success' && inputs.create_issue_on_failure }}
id: create_issue
shell: bash
env:
GH_TOKEN: ${{ github.token }}
run: |
# Prepare issue body with clang-tidy output
cat > issue.md <<EOF
## Clang-tidy Check Failed
**Workflow:** ${{ github.workflow }}
**Run ID:** ${{ github.run_id }}
**Commit:** ${{ github.sha }}
**Branch/Ref:** ${{ github.ref }}
**Triggered by:** ${{ github.actor }}
### Clang-tidy Output:
\`\`\`
EOF
# Append clang-tidy output (filter for errors and warnings)
if [ -f clang-tidy-output.txt ]; then
# Extract lines containing 'error:', 'warning:', or 'note:'
grep -E '(error:|warning:|note:)' clang-tidy-output.txt > filtered-output.txt || true
# If filtered output is empty, use original (might be a different error format)
if [ ! -s filtered-output.txt ]; then
cp clang-tidy-output.txt filtered-output.txt
fi
# Truncate if too large
head -c 60000 filtered-output.txt >> issue.md
if [ "$(wc -c < filtered-output.txt)" -gt 60000 ]; then
echo "" >> issue.md
echo "... (output truncated, see artifacts for full output)" >> issue.md
fi
rm filtered-output.txt
else
echo "No output file found" >> issue.md
fi
cat >> issue.md <<EOF
\`\`\`
**Workflow run:** ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
---
*This issue was automatically created by the clang-tidy workflow.*
EOF
# Create the issue
gh issue create \
--label "Bug,Clang-tidy" \
--title "Clang-tidy check failed" \
--body-file ./issue.md \
> create_issue.log
created_issue="$(sed 's|.*/||' create_issue.log)"
echo "created_issue=$created_issue" >> $GITHUB_OUTPUT
echo "Created issue #$created_issue"
rm -f create_issue.log issue.md clang-tidy-output.txt
- name: Fail the workflow if clang-tidy failed
if: ${{ steps.run_clang_tidy.outcome != 'success' }}
run: |
echo "Clang-tidy check failed!"
exit 1

View File

@@ -1,4 +1,4 @@
name: Clang-tidy check
name: Run clang-tidy on files
on:
workflow_call:
@@ -16,40 +16,198 @@ defaults:
run:
shell: bash
env:
BUILD_DIR: build
BUILD_TYPE: Debug # Debug so that ASSERTS and such participate in clang-tidy check
OUTPUT_FILE: clang-tidy-output.txt
DIFF_FILE: clang-tidy-git-diff.txt
ISSUE_FILE: clang-tidy-issue.md
jobs:
determine-files:
name: Determine files to check
if: ${{ inputs.check_only_changed }}
runs-on: ubuntu-latest
outputs:
clang_tidy_config_changed: ${{ steps.changed_clang_tidy.outputs.any_changed }}
any_cpp_changed: ${{ steps.changed_files.outputs.any_changed }}
all_changed_files: ${{ steps.changed_files.outputs.all_changed_files }}
permissions:
contents: read
uses: XRPLF/actions/.github/workflows/determine-tidy-files.yml@12f5dbc98a2260259a66970e57fa4d26fb7f285c
run-clang-tidy:
name: Run clang tidy
needs: [determine-files]
if: ${{ always() && !cancelled() && (!inputs.check_only_changed || needs.determine-files.outputs.cpp_changed_files != '' || needs.determine-files.outputs.clang_tidy_config_changed == 'true') }}
runs-on: ["self-hosted", "Linux", "X64", "heavy"]
container: "ghcr.io/xrplf/ci/debian-trixie:clang-21-sha-53033a2"
permissions:
contents: read
steps:
- name: Checkout repository
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
- name: Get changed C++ files
id: changed_files
uses: tj-actions/changed-files@9426d40962ed5378910ee2e21d5f8c6fcbf2dd96 # v47.0.6
- name: Prepare runner
uses: XRPLF/actions/prepare-runner@90f11ee655d1687824fb8793db770477d52afbab
with:
files: |
**/*.cpp
**/*.h
**/*.ipp
separator: " "
enable_ccache: false
- name: Get changed clang-tidy configuration
id: changed_clang_tidy
uses: tj-actions/changed-files@9426d40962ed5378910ee2e21d5f8c6fcbf2dd96 # v47.0.6
- name: Print build environment
uses: XRPLF/actions/print-build-env@59dec886e4afb05a1724443af08baccbc045b574
- name: Get number of processors
uses: XRPLF/actions/get-nproc@cf0433aa74563aead044a1e395610c96d65a37cf
id: nproc
- name: Setup Conan
uses: ./.github/actions/setup-conan
- name: Build dependencies
uses: ./.github/actions/build-deps
with:
files: |
.clang-tidy
build_nproc: ${{ steps.nproc.outputs.nproc }}
build_type: ${{ env.BUILD_TYPE }}
log_verbosity: verbose
run-clang-tidy:
needs: [determine-files]
if: ${{ always() && !cancelled() && (!inputs.check_only_changed || needs.determine-files.outputs.any_cpp_changed == 'true' || needs.determine-files.outputs.clang_tidy_config_changed == 'true') }}
uses: ./.github/workflows/reusable-clang-tidy-files.yml
with:
files: ${{ (needs.determine-files.outputs.clang_tidy_config_changed != 'true' && inputs.check_only_changed) && needs.determine-files.outputs.all_changed_files || '' }}
create_issue_on_failure: ${{ inputs.create_issue_on_failure }}
- name: Configure CMake
working-directory: ${{ env.BUILD_DIR }}
run: |
cmake \
-G 'Ninja' \
-DCMAKE_TOOLCHAIN_FILE:FILEPATH=build/generators/conan_toolchain.cmake \
-DCMAKE_BUILD_TYPE="${BUILD_TYPE}" \
-Dtests=ON \
-Dwerr=ON \
-Dxrpld=ON \
..
# clang-tidy needs headers generated from proto files
- name: Build libxrpl.libpb
working-directory: ${{ env.BUILD_DIR }}
run: |
ninja -j ${{ steps.nproc.outputs.nproc }} xrpl.libpb
- name: Run clang tidy
id: run_clang_tidy
continue-on-error: true
env:
TARGETS: ${{ (needs.determine-files.outputs.clang_tidy_config_changed != 'true' && inputs.check_only_changed) && needs.determine-files.outputs.cpp_changed_files || 'src tests' }}
run: |
set -o pipefail
run-clang-tidy -j ${{ steps.nproc.outputs.nproc }} -p "${BUILD_DIR}" -quiet -fix -allow-no-checks ${TARGETS} 2>&1 | tee "${OUTPUT_FILE}"
- name: Upload clang-tidy output
if: ${{ github.event.repository.visibility == 'public' && steps.run_clang_tidy.outcome != 'success' }}
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
path: ${{ env.OUTPUT_FILE }}
archive: false
retention-days: 30
- name: Generate git diff
if: ${{ steps.run_clang_tidy.outcome != 'success' }}
run: |
git diff | tee "${DIFF_FILE}"
- name: Upload clang-tidy diff output
if: ${{ github.event.repository.visibility == 'public' && steps.run_clang_tidy.outcome != 'success' }}
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
path: ${{ env.DIFF_FILE }}
archive: false
retention-days: 30
- name: Write issue header
if: ${{ steps.run_clang_tidy.outcome != 'success' }}
run: |
# Prepare issue body with clang-tidy output
cat > "${ISSUE_FILE}" <<EOF
## Clang-tidy Check Failed
**Workflow:** ${{ github.workflow }}
**Run ID:** ${{ github.run_id }}
**Commit:** ${{ github.sha }}
**Branch/Ref:** ${{ github.ref }}
**Triggered by:** ${{ github.actor }}
### Clang-tidy Output:
\`\`\`
EOF
- name: Append clang-tidy output to issue body
if: ${{ steps.run_clang_tidy.outcome != 'success' }}
run: |
# Append clang-tidy output (filter for errors and warnings)
if [ -f "${OUTPUT_FILE}" ]; then
# Extract lines containing 'error:', 'warning:', or 'note:'
grep -E '(error:|warning:|note:)' "${OUTPUT_FILE}" > filtered-output.txt || true
# If filtered output is empty, use original (might be a different error format)
if [ ! -s filtered-output.txt ]; then
cp "${OUTPUT_FILE}" filtered-output.txt
fi
# Truncate if too large
head -c 60000 filtered-output.txt >> "${ISSUE_FILE}"
if [ "$(wc -c < filtered-output.txt)" -gt 60000 ]; then
echo "" >> "${ISSUE_FILE}"
echo "... (output truncated, see artifacts for full output)" >> "${ISSUE_FILE}"
fi
rm filtered-output.txt
else
echo "No output file found" >> "${ISSUE_FILE}"
fi
- name: Append issue footer
if: ${{ steps.run_clang_tidy.outcome != 'success' }}
run: |
cat >> "${ISSUE_FILE}" <<EOF
\`\`\`
**Workflow run:** ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
---
*This issue was automatically created by the clang-tidy workflow.*
EOF
- name: Upload issue body artifact
if: ${{ github.event.repository.visibility == 'public' && steps.run_clang_tidy.outcome != 'success' }}
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
path: ${{ env.ISSUE_FILE }}
archive: false
retention-days: 30
- name: Fail if clang-tidy found issues
if: ${{ steps.run_clang_tidy.outcome != 'success' }}
run: |
echo "Clang-tidy check failed!"
exit 1
create-issue-on-failure:
name: Create GitHub issue on failure
runs-on: ubuntu-latest
needs: [run-clang-tidy]
if: ${{ always() && !cancelled() && inputs.create_issue_on_failure && needs.run-clang-tidy.result == 'failure' && github.event.repository.visibility == 'public' }}
permissions:
issues: write
contents: read
steps:
- name: Download clang-tidy-issue.md
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
with:
name: ${{ env.ISSUE_FILE }}
- name: Create GitHub issue
env:
GH_TOKEN: ${{ github.token }}
run: |
# Create the issue
gh issue create \
--label "Bug,Clang-tidy" \
--title "Clang-tidy check failed" \
--body-file ./"${ISSUE_FILE}" \
> create_issue.log
- name: Output created issue number
run: |
created_issue="$(sed 's|.*/||' create_issue.log)"
echo "created_issue=$created_issue" >> $GITHUB_OUTPUT
echo "Created issue #$created_issue"

View File

@@ -75,7 +75,7 @@ jobs:
enable_ccache: false
- name: Print build environment
uses: ./.github/actions/print-env
uses: XRPLF/actions/print-build-env@59dec886e4afb05a1724443af08baccbc045b574
- name: Get number of processors
uses: XRPLF/actions/get-nproc@cf0433aa74563aead044a1e395610c96d65a37cf

View File

@@ -28,6 +28,8 @@ This section contains changes targeting a future version.
### Additions
- `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)):
- `TRANSACTION_FORMATS`: Describes the fields and their optionality for each transaction type, including common fields shared across all transactions.
- `LEDGER_ENTRY_FORMATS`: Describes the fields and their optionality for each ledger entry type, including common fields shared across all ledger entries.
@@ -40,6 +42,14 @@ This section contains changes targeting a future version.
- Peer Crawler: The `port` field in `overlay.active[]` now consistently returns an integer instead of a string for outbound peers. [#6318](https://github.com/XRPLF/rippled/pull/6318)
- `ping`: The `ip` field is no longer returned as an empty string for proxied connections without a forwarded-for header. It is now omitted, consistent with the behavior for identified connections. [#6730](https://github.com/XRPLF/rippled/pull/6730)
- gRPC `GetLedgerDiff`: Fixed error message that incorrectly said "base ledger not validated" when the desired ledger was not validated. [#6730](https://github.com/XRPLF/rippled/pull/6730)
- `account_channels`: The `destination_account` field now returns an error if the value is not a string. [#6529](https://github.com/XRPLF/rippled/pull/6529)
- `subscribe`: The `taker` field in the `books` array now returns an error if the value is not a string. [#6529](https://github.com/XRPLF/rippled/pull/6529)
- `account_info`: The `urlgravatar` field now uses HTTPS instead of HTTP. [#6529](https://github.com/XRPLF/rippled/pull/6529)
- `ledger`: The `full`, `accounts`, `transactions`, `expand`, `binary`, `owner_funds`, and `queue` fields now return an error if the value is not a boolean. [#6529](https://github.com/XRPLF/rippled/pull/6529)
- `ledger_data`: The `binary` field now returns an error if the value is not a boolean. [#6529](https://github.com/XRPLF/rippled/pull/6529)
- `submit`: The `fail_hard` field now returns an error if the value is not a boolean. [#6529](https://github.com/XRPLF/rippled/pull/6529)
- `subscribe`: The `taker` field in the `books` array now returns `actMalformed` instead of `badIssuer` if the value is not a valid account. [#6529](https://github.com/XRPLF/rippled/pull/6529)
- Fixed a bug in `Forwarded` HTTP header parsing where the extracted IP address could be incorrect when no comma or semicolon delimiter follows the address. This could cause the server to misidentify a client's IP address when operating behind a reverse proxy. [#6529](https://github.com/XRPLF/rippled/pull/6529)
## XRP Ledger server version 3.1.0

View File

@@ -88,6 +88,7 @@ find_package(ed25519 REQUIRED)
find_package(gRPC REQUIRED)
find_package(LibArchive REQUIRED)
find_package(lz4 REQUIRED)
find_package(mpt-crypto REQUIRED)
find_package(nudb REQUIRED)
find_package(OpenSSL REQUIRED)
find_package(secp256k1 REQUIRED)
@@ -100,6 +101,7 @@ target_link_libraries(
INTERFACE
ed25519::ed25519
lz4::lz4
mpt-crypto::mpt-crypto
OpenSSL::Crypto
OpenSSL::SSL
secp256k1::secp256k1

View File

@@ -348,8 +348,8 @@ For this reason:
- Contract description for `UNREACHABLE` should describe the _unexpected_
situation which caused the line to have been reached.
- Example good name for an
`UNREACHABLE` macro `"Json::operator==(Value, Value) : invalid type"`; example
good name for an `XRPL_ASSERT` macro `"Json::Value::asCString : valid type"`.
`UNREACHABLE` macro `"json::operator==(Value, Value) : invalid type"`; example
good name for an `XRPL_ASSERT` macro `"json::Value::asCString : valid type"`.
- Example **bad** name
`"RFC1751::insert(char* s, int x, int start, int length) : length is greater than or equal zero"`
(missing namespace, unnecessary full function signature, description too verbose).

View File

@@ -23,7 +23,6 @@ target_compile_definitions(
BOOST_FILESYSTEM_NO_DEPRECATED
>
$<$<NOT:$<BOOL:${boost_show_deprecated}>>:
BOOST_COROUTINES2_NO_DEPRECATION_WARNING
BOOST_BEAST_ALLOW_DEPRECATED
BOOST_FILESYSTEM_DEPRECATED
>

View File

@@ -34,10 +34,12 @@
* -fsanitize=<types>: Links sanitizer runtime libraries
* -mcmodel=large/medium: (GCC only) Matches compile-time code model
- SANITIZERS_RELOCATION_FLAGS: (GCC only) Code model flags for linking.
- SANITIZERS_RELOCATION_FLAGS: (GCC only, x86_64 only) Code model flags for linking.
Used to handle large instrumented binaries on x86_64:
* -mcmodel=large: For AddressSanitizer (prevents relocation errors)
* -mcmodel=medium: For ThreadSanitizer (large model is incompatible)
On ARM64, these flags are omitted since GCC does not support
-mcmodel=large with -fPIC, and -mcmodel=medium does not exist.
#]===================================================================]
include(CompilationEnv)
@@ -151,9 +153,11 @@ if(is_gcc)
elseif(enable_tsan)
# GCC doesn't support atomic_thread_fence with tsan. Suppress warnings.
list(APPEND SANITIZERS_COMPILE_FLAGS "-Wno-tsan")
message(STATUS " Using medium code model (-mcmodel=medium)")
list(APPEND SANITIZERS_COMPILE_FLAGS "-mcmodel=medium")
list(APPEND SANITIZERS_RELOCATION_FLAGS "-mcmodel=medium")
if(is_amd64)
message(STATUS " Using medium code model (-mcmodel=medium)")
list(APPEND SANITIZERS_COMPILE_FLAGS "-mcmodel=medium")
list(APPEND SANITIZERS_RELOCATION_FLAGS "-mcmodel=medium")
endif()
endif()
# Join sanitizer flags with commas for -fsanitize option

View File

@@ -152,10 +152,10 @@ def parse_sfields_macro(sfields_path):
def create_field_list_parser():
"""Create a pyparsing parser for field lists like '({...})'."""
# A field identifier (e.g., sfDestination, soeREQUIRED, soeMPTSupported)
# A field identifier (e.g., sfDestination, SoeRequired, SoeMptSupported)
field_identifier = pp.Word(pp.alphas + "_", pp.alphanums + "_")
# A single field definition: {sfName, soeREQUIRED, ...}
# A single field definition: {sfName, SoeRequired, ...}
# Allow optional trailing comma inside the braces
field_def = (
pp.Suppress("{")
@@ -185,8 +185,8 @@ def parse_field_list(fields_str):
Args:
fields_str: A string like '({
{sfDestination, soeREQUIRED},
{sfAmount, soeREQUIRED, soeMPTSupported}
{sfDestination, SoeRequired},
{sfAmount, SoeRequired, SoeMptSupported}
})'
Returns:
@@ -205,7 +205,7 @@ def parse_field_list(fields_str):
field_name = field_parts[0]
requirement = field_parts[1]
flags = list(field_parts[2:]) if len(field_parts) > 2 else []
supports_mpt = "soeMPTSupported" in flags
supports_mpt = "SoeMptSupported" in flags
fields.append(
{

View File

@@ -52,13 +52,13 @@ public:
% if field.get('mpt_support'):
* MPT Support: ${field['mpt_support']}
% endif
% if field['requirement'] == 'soeREQUIRED':
% if field['requirement'] == 'SoeRequired':
* @return The field value.
% else:
* @return The field value, or std::nullopt if not present.
% endif
*/
% if field['requirement'] == 'soeREQUIRED':
% if field['requirement'] == 'SoeRequired':
[[nodiscard]]
${field['typeData']['return_type']}
get${field['name'][2:]}() const
@@ -94,13 +94,13 @@ public:
* MPT Support: ${field['mpt_support']}
% endif
* @note This is an untyped field (${field.get('cppType', 'unknown')}).
% if field['requirement'] == 'soeREQUIRED':
% if field['requirement'] == 'SoeRequired':
* @return The field value.
% else:
* @return The field value, or std::nullopt if not present.
% endif
*/
% if field['requirement'] == 'soeREQUIRED':
% if field['requirement'] == 'SoeRequired':
[[nodiscard]]
${field['typeData']['return_type']}
get${field['name'][2:]}() const
@@ -133,13 +133,13 @@ public:
};
<%
required_fields = [f for f in fields if f['requirement'] == 'soeREQUIRED']
required_fields = [f for f in fields if f['requirement'] == 'SoeRequired']
%>\
/**
* @brief Builder for ${name} ledger entries.
*
* Provides a fluent interface for constructing ledger entries with method chaining.
* Uses Json::Value internally for flexible ledger entry construction.
* Uses STObject internally for flexible ledger entry construction.
* Inherits common field setters from LedgerEntryBuilderBase.
*/
class ${name}Builder : public LedgerEntryBuilderBase<${name}Builder>

View File

@@ -1,7 +1,7 @@
// Auto-generated unit tests for ledger entry ${name}
<%
required_fields = [f for f in fields if f["requirement"] == "soeREQUIRED"]
optional_fields = [f for f in fields if f["requirement"] != "soeREQUIRED"]
required_fields = [f for f in fields if f["requirement"] == "SoeRequired"]
optional_fields = [f for f in fields if f["requirement"] != "SoeRequired"]
def canonical_expr(field):
return f"canonical_{field['stiSuffix']}()"

View File

@@ -54,13 +54,13 @@ public:
% if field.get('supports_mpt'):
* @note This field supports MPT (Multi-Purpose Token) amounts.
% endif
% if field['requirement'] == 'soeREQUIRED':
% if field['requirement'] == 'SoeRequired':
* @return The field value.
% else:
* @return The field value, or std::nullopt if not present.
% endif
*/
% if field['requirement'] == 'soeREQUIRED':
% if field['requirement'] == 'SoeRequired':
[[nodiscard]]
${field['typeData']['return_type']}
get${field['name'][2:]}() const
@@ -97,13 +97,13 @@ public:
* @note This field supports MPT (Multi-Purpose Token) amounts.
% endif
* @note This is an untyped field.
% if field['requirement'] == 'soeREQUIRED':
% if field['requirement'] == 'SoeRequired':
* @return The field value.
% else:
* @return The field value, or std::nullopt if not present.
% endif
*/
% if field['requirement'] == 'soeREQUIRED':
% if field['requirement'] == 'SoeRequired':
[[nodiscard]]
${field['typeData']['return_type']}
get${field['name'][2:]}() const
@@ -136,13 +136,13 @@ public:
};
<%
required_fields = [f for f in fields if f['requirement'] == 'soeREQUIRED']
required_fields = [f for f in fields if f['requirement'] == 'SoeRequired']
%>\
/**
* @brief Builder for ${name} transactions.
*
* Provides a fluent interface for constructing transactions with method chaining.
* Uses Json::Value internally for flexible transaction construction.
* Uses STObject internally for flexible transaction construction.
* Inherits common field setters from TransactionBuilderBase.
*/
class ${name}Builder : public TransactionBuilderBase<${name}Builder>

View File

@@ -1,7 +1,7 @@
// Auto-generated unit tests for transaction ${name}
<%
required_fields = [f for f in fields if f["requirement"] == "soeREQUIRED"]
optional_fields = [f for f in fields if f["requirement"] != "soeREQUIRED"]
required_fields = [f for f in fields if f["requirement"] == "SoeRequired"]
optional_fields = [f for f in fields if f["requirement"] != "SoeRequired"]
def canonical_expr(field):
return f"canonical_{field['stiSuffix']}()"
@@ -33,7 +33,7 @@ TEST(Transactions${name}Tests, BuilderSettersRoundTrip)
{
// Generate a deterministic keypair for signing
auto const [publicKey, secretKey] =
generateKeyPair(KeyType::secp256k1, generateSeed("test${name}"));
generateKeyPair(KeyType::Secp256k1, generateSeed("test${name}"));
// Common transaction fields
auto const accountValue = calcAccountID(publicKey);
@@ -101,7 +101,7 @@ TEST(Transactions${name}Tests, BuilderFromStTxRoundTrip)
{
// Generate a deterministic keypair for signing
auto const [publicKey, secretKey] =
generateKeyPair(KeyType::secp256k1, generateSeed("test${name}FromTx"));
generateKeyPair(KeyType::Secp256k1, generateSeed("test${name}FromTx"));
// Common transaction fields
auto const accountValue = calcAccountID(publicKey);
@@ -168,7 +168,7 @@ TEST(Transactions${name}Tests, WrapperThrowsOnWrongTxType)
{
// Build a valid transaction of a different type
auto const [pk, sk] =
generateKeyPair(KeyType::secp256k1, generateSeed("testWrongType"));
generateKeyPair(KeyType::Secp256k1, generateSeed("testWrongType"));
auto const account = calcAccountID(pk);
% if wrong_tx_include == "AccountSet":
@@ -186,7 +186,7 @@ TEST(Transactions${name}Tests, BuilderThrowsOnWrongTxType)
{
// Build a valid transaction of a different type
auto const [pk, sk] =
generateKeyPair(KeyType::secp256k1, generateSeed("testWrongTypeBuilder"));
generateKeyPair(KeyType::Secp256k1, generateSeed("testWrongTypeBuilder"));
auto const account = calcAccountID(pk);
% if wrong_tx_include == "AccountSet":
@@ -205,7 +205,7 @@ TEST(Transactions${name}Tests, OptionalFieldsReturnNullopt)
{
// Generate a deterministic keypair for signing
auto const [publicKey, secretKey] =
generateKeyPair(KeyType::secp256k1, generateSeed("test${name}Nullopt"));
generateKeyPair(KeyType::Secp256k1, generateSeed("test${name}Nullopt"));
// Common transaction fields
auto const accountValue = calcAccountID(publicKey);

View File

@@ -12,6 +12,7 @@
"protobuf/6.33.5#d96d52ba5baaaa532f47bda866ad87a5%1774467363.12",
"openssl/3.6.1#e6399de266349245a4542fc5f6c71552%1774458290.139",
"nudb/2.0.9#11149c73f8f2baff9a0198fe25971fc7%1774883011.384",
"mpt-crypto/0.3.0-rc1#468344c6855d4aeaa8bd31fb2c403f89%1776358155.918",
"lz4/1.10.0#59fc63cac7f10fbe8e05c7e62c2f3504%1765850143.914",
"libiconv/1.17#1e65319e945f2d31941a9d28cc13c058%1765842973.492",
"libbacktrace/cci.20210118#a7691bfccd8caaf66309df196790a5a1%1765842973.03",
@@ -34,6 +35,7 @@
"msys2/cci.latest#d22fe7b2808f5fd34d0a7923ace9c54f%1770657326.649",
"m4/1.4.19#5d7a4994e5875d76faf7acf3ed056036%1774365463.87",
"cmake/4.3.0#b939a42e98f593fb34d3a8c5cc860359%1774439249.183",
"cmake/3.31.10#313d16a1aa16bbdb2ca0792467214b76%1765850153.479",
"b2/5.4.2#ffd6084a119587e70f11cd45d1a386e2%1774439233.447",
"automake/1.16.5#b91b7c384c3deaa9d535be02da14d04f%1755524470.56",
"autoconf/2.71#51077f068e61700d65bb05541ea1e4b0%1731054366.86",
@@ -58,6 +60,12 @@
],
"lz4/[>=1.9.4 <2]": [
"lz4/1.10.0#59fc63cac7f10fbe8e05c7e62c2f3504"
],
"openssl/3.5.5": [
"openssl/3.6.1"
],
"openssl/[>=3 <4]": [
"openssl/3.6.1"
]
},
"config_requires": []

View File

@@ -1,5 +1,6 @@
include(default)
{% set compiler, version, compiler_exe = detect_api.detect_default_compiler() %}
{% set arch = detect_api.detect_arch() %}
{% set sanitizers = os.getenv("SANITIZERS") %}
[conf]
@@ -13,12 +14,16 @@ include(default)
{% if "address" in sanitizers %}
{% set _ = sanitizer_list.append("address") %}
{% set model_code = "-mcmodel=large" %}
{% if arch == "x86_64" %}
{% set model_code = "-mcmodel=large" %}
{% endif %}
{% set _ = defines.append("BOOST_USE_ASAN")%}
{% set _ = defines.append("BOOST_USE_UCONTEXT")%}
{% elif "thread" in sanitizers %}
{% set _ = sanitizer_list.append("thread") %}
{% set model_code = "-mcmodel=medium" %}
{% if arch == "x86_64" %}
{% set model_code = "-mcmodel=medium" %}
{% endif %}
{% set _ = extra_cxxflags.append("-Wno-tsan") %}
{% set _ = defines.append("BOOST_USE_TSAN")%}
{% set _ = defines.append("BOOST_USE_UCONTEXT")%}
@@ -82,5 +87,12 @@ tools.info.package_id:confs+=["tools.build:cxxflags", "tools.build:exelinkflags"
boost/*:without_context=False
# Boost stacktrace fails to build with some sanitizers
boost/*:without_stacktrace=True
{% elif "thread" in sanitizers %}
# Build Boost.Context with ucontext backend for TSAN. fcontext (assembly)
# has no TSAN annotations, so without this the BOOST_USE_TSAN/BOOST_USE_UCONTEXT
# defines in [conf] would be ineffective.
boost/*:extra_b2_flags=context-impl=ucontext thread-sanitizer=on define=BOOST_USE_TSAN=1
boost/*:without_context=False
boost/*:without_stacktrace=True
{% endif %}
{% endif %}

View File

@@ -31,6 +31,7 @@ class Xrpl(ConanFile):
"ed25519/2015.03",
"grpc/1.78.1",
"libarchive/3.8.1",
"mpt-crypto/0.3.0-rc1",
"nudb/2.0.9",
"openssl/3.6.1",
"secp256k1/0.7.1",
@@ -129,12 +130,6 @@ class Xrpl(ConanFile):
if self.settings.compiler in ["clang", "gcc"]:
self.options["boost"].without_cobalt = True
# Check if environment variable exists
if "SANITIZERS" in os.environ:
sanitizers = os.environ["SANITIZERS"]
if "address" in sanitizers.lower():
self.default_options["fPIC"] = False
def requirements(self):
self.requires("boost/1.90.0", force=True, transitive_headers=True)
self.requires("date/3.0.4", transitive_headers=True)
@@ -214,6 +209,7 @@ class Xrpl(ConanFile):
"grpc::grpc++",
"libarchive::libarchive",
"lz4::lz4",
"mpt-crypto::mpt-crypto",
"nudb::nudb",
"openssl::crypto",
"protobuf::libprotobuf",

View File

@@ -59,6 +59,7 @@ words:
- autobridging
- bimap
- bindir
- blindings
- bookdir
- Bougalis
- Britto
@@ -91,6 +92,7 @@ words:
- daria
- dcmake
- dearmor
- decryptor
- deleteme
- demultiplexer
- deserializaton
@@ -100,6 +102,7 @@ words:
- distro
- doxyfile
- dxrpl
- elgamal
- enabled
- endmacro
- exceptioned
@@ -110,6 +113,7 @@ words:
- fmtdur
- fsanitize
- funclets
- Gamal
- gcov
- gcovr
- ghead
@@ -151,6 +155,7 @@ words:
- lseq
- lsmf
- ltype
- mathbunnyru
- mcmodel
- MEMORYSTATUSEX
- MPTAMM
@@ -199,6 +204,7 @@ words:
- partitioner
- paychan
- paychans
- Pedersen
- permdex
- perminute
- permissioned
@@ -219,6 +225,8 @@ words:
- queuable
- Raphson
- replayer
- rerandomization
- rerandomized
- rerere
- retriable
- RIPD
@@ -235,6 +243,7 @@ words:
- sahyadri
- Satoshi
- scons
- Schnorr
- secp
- sendq
- seqit
@@ -262,6 +271,7 @@ words:
- stvar
- stvector
- stxchainattestations
- summands
- superpeer
- superpeers
- takergets

View File

@@ -98,7 +98,7 @@ export LSAN_OPTIONS="include=sanitizers/suppressions/runtime-lsan-options.txt:su
**Why `detect_container_overflow=0`?**
- Boost intrusive containers (used in `aged_unordered_container`) trigger false positives
- Boost intrusive containers (used in `AgedUnorderedContainer`) trigger false positives
- Boost context switching (used in `Workers.cpp`) confuses ASAN's stack tracking
- Since we usually don't build Boost (because we don't want to instrument Boost and detect issues in Boost code) with ASAN but use Boost containers in ASAN instrumented xrpld code, it generates false positives.
- Building dependencies with ASAN instrumentation reduces false positives. But we don't want to instrument dependencies like Boost with ASAN because it is slow (to compile as well as run tests) and not necessary.

View File

@@ -477,7 +477,7 @@ struct Ledger
// The parent ledger's close time
NetClock::time_point parentCloseTime() const;
Json::Value getJson() const;
json::Value getJson() const;
//... implementation specific
};

View File

@@ -27,7 +27,7 @@ private:
std::unordered_map<std::string, std::string> lookup_;
std::vector<std::string> lines_;
std::vector<std::string> values_;
bool had_trailing_comments_ = false;
bool hadTrailingComments_ = false;
using const_iterator = decltype(lookup_)::const_iterator;
@@ -133,7 +133,7 @@ public:
/// Returns a value if present, else another value.
template <class T>
[[nodiscard]] T
value_or(std::string const& name, T const& other) const
valueOr(std::string const& name, T const& other) const
{
auto const v = get<T>(name);
return v.has_value() ? *v : other;
@@ -142,9 +142,9 @@ public:
// indicates if trailing comments were seen
// during the appending of any lines/values
[[nodiscard]] bool
had_trailing_comments() const
hadTrailingComments() const
{
return had_trailing_comments_;
return hadTrailingComments_;
}
friend std::ostream&
@@ -273,9 +273,9 @@ public:
// indicates if trailing comments were seen
// in any loaded Sections
[[nodiscard]] bool
had_trailing_comments() const
hadTrailingComments() const
{
return std::ranges::any_of(map_, [](auto s) { return s.second.had_trailing_comments(); });
return std::ranges::any_of(map_, [](auto s) { return s.second.hadTrailingComments(); });
}
protected:
@@ -294,17 +294,17 @@ template <class T>
bool
set(T& target, std::string const& name, Section const& section)
{
bool found_and_valid = false;
bool foundAndValid = false;
try
{
auto const val = section.get<T>(name);
if ((found_and_valid = val.has_value()))
if ((foundAndValid = val.has_value()))
target = *val;
}
catch (boost::bad_lexical_cast const&) // NOLINT(bugprone-empty-catch)
{
}
return found_and_valid;
return foundAndValid;
}
/** Set a value from a configuration Section
@@ -316,10 +316,10 @@ template <class T>
bool
set(T& target, T const& defaultValue, std::string const& name, Section const& section)
{
bool const found_and_valid = set<T>(target, name, section);
if (!found_and_valid)
bool const foundAndValid = set<T>(target, name, section);
if (!foundAndValid)
target = defaultValue;
return found_and_valid;
return foundAndValid;
}
/** Retrieve a key/value pair from a section.
@@ -333,7 +333,7 @@ get(Section const& section, std::string const& name, T const& defaultValue = T{}
{
try
{
return section.value_or<T>(name, defaultValue);
return section.valueOr<T>(name, defaultValue);
}
catch (boost::bad_lexical_cast const&) // NOLINT(bugprone-empty-catch)
{
@@ -358,17 +358,17 @@ get(Section const& section, std::string const& name, char const* defaultValue)
template <class T>
bool
get_if_exists(Section const& section, std::string const& name, T& v)
getIfExists(Section const& section, std::string const& name, T& v)
{
return set<T>(v, name, section);
}
template <>
inline bool
get_if_exists<bool>(Section const& section, std::string const& name, bool& v)
getIfExists<bool>(Section const& section, std::string const& name, bool& v)
{
int intVal = 0;
auto stat = get_if_exists(section, name, intVal);
auto stat = getIfExists(section, name, intVal);
if (stat)
v = bool(intVal);
return stat;

View File

@@ -38,11 +38,11 @@ public:
do
{
head = instance.m_head.load();
head = instance.head_.load();
next_ = head;
} while (instance.m_head.exchange(this) != head);
} while (instance.head_.exchange(this) != head);
++instance.m_count;
++instance.count_;
}
~Counter() noexcept = default;
@@ -88,8 +88,8 @@ private:
~CountedObjects() noexcept = default;
private:
std::atomic<int> m_count;
std::atomic<Counter*> m_head;
std::atomic<int> count_;
std::atomic<Counter*> head_;
};
//------------------------------------------------------------------------------
@@ -108,8 +108,8 @@ private:
static auto&
getCounter() noexcept
{
static CountedObjects::Counter c{beast::type_name<Object>()};
return c;
static CountedObjects::Counter kC{beast::typeName<Object>()};
return kC;
}
CountedObject() noexcept

View File

@@ -20,7 +20,7 @@ public:
/**
@param now Start time of DecayingSample.
*/
explicit DecayingSample(time_point now) : m_value(value_type()), m_when(now)
explicit DecayingSample(time_point now) : value_(value_type()), when_(now)
{
}
@@ -31,8 +31,8 @@ public:
add(value_type value, time_point now)
{
decay(now);
m_value += value;
return m_value / Window;
value_ += value;
return value_ / Window;
}
/** Retrieve the current value in normalized units.
@@ -42,7 +42,7 @@ public:
value(time_point now)
{
decay(now);
return m_value / Window;
return value_ / Window;
}
private:
@@ -50,36 +50,38 @@ private:
void
decay(time_point now)
{
if (now == m_when)
if (now == when_)
return;
if (m_value != value_type())
if (value_ != value_type())
{
std::size_t elapsed =
std::chrono::duration_cast<std::chrono::seconds>(now - m_when).count();
std::chrono::duration_cast<std::chrono::seconds>(now - when_).count();
// A span larger than four times the window decays the
// value to an insignificant amount so just reset it.
//
if (elapsed > 4 * Window)
{
m_value = value_type();
value_ = value_type();
}
else
{
while ((elapsed--) != 0u)
m_value -= (m_value + Window - 1) / Window;
for (; elapsed > 0; --elapsed)
{
value_ -= (value_ + Window - 1) / Window;
}
}
}
m_when = now;
when_ = now;
}
// Current value in exponential units
value_type m_value;
value_type value_;
// Last time the aging function was applied
time_point m_when;
time_point when_;
};
//------------------------------------------------------------------------------

View File

@@ -16,9 +16,9 @@ namespace xrpl {
*/
// Exception thrown by an invalid access to Expected.
struct bad_expected_access : public std::runtime_error
struct BadExpectedAccess : public std::runtime_error
{
bad_expected_access() : runtime_error("bad expected access")
BadExpectedAccess() : runtime_error("bad expected access")
{
}
};
@@ -26,30 +26,33 @@ struct bad_expected_access : public std::runtime_error
namespace detail {
// Custom policy for Expected. Always throw on an invalid access.
struct throw_policy : public boost::outcome_v2::policy::base
struct ThrowPolicy : public boost::outcome_v2::policy::base
{
template <class Impl>
static constexpr void
// NOLINTNEXTLINE(readability-identifier-naming)
wide_value_check(Impl&& self)
{
if (!base::_has_value(std::forward<Impl>(self)))
Throw<bad_expected_access>();
Throw<BadExpectedAccess>();
}
template <class Impl>
static constexpr void
// NOLINTNEXTLINE(readability-identifier-naming)
wide_error_check(Impl&& self)
{
if (!base::_has_error(std::forward<Impl>(self)))
Throw<bad_expected_access>();
Throw<BadExpectedAccess>();
}
template <class Impl>
static constexpr void
// NOLINTNEXTLINE(readability-identifier-naming)
wide_exception_check(Impl&& self)
{
if (!base::_has_exception(std::forward<Impl>(self)))
Throw<bad_expected_access>();
Throw<BadExpectedAccess>();
}
};
@@ -107,9 +110,9 @@ Unexpected(E (&)[N]) -> Unexpected<E const*>;
// Definition of Expected. All of the machinery comes from boost::result.
template <class T, class E>
class [[nodiscard]] Expected : private boost::outcome_v2::result<T, E, detail::throw_policy>
class [[nodiscard]] Expected : private boost::outcome_v2::result<T, E, detail::ThrowPolicy>
{
using Base = boost::outcome_v2::result<T, E, detail::throw_policy>;
using Base = boost::outcome_v2::result<T, E, detail::ThrowPolicy>;
public:
template <typename U>
@@ -126,6 +129,7 @@ public:
}
[[nodiscard]] constexpr bool
// NOLINTNEXTLINE(readability-identifier-naming)
has_value() const
{
return Base::has_value();
@@ -193,9 +197,9 @@ public:
// (without a value) or the reason for the failure.
template <class E>
class [[nodiscard]]
Expected<void, E> : private boost::outcome_v2::result<void, E, detail::throw_policy>
Expected<void, E> : private boost::outcome_v2::result<void, E, detail::ThrowPolicy>
{
using Base = boost::outcome_v2::result<void, E, detail::throw_policy>;
using Base = boost::outcome_v2::result<void, E, detail::ThrowPolicy>;
public:
// The default constructor makes a successful Expected<void, E>.

View File

@@ -164,11 +164,11 @@ public:
/** Return the strong count */
[[nodiscard]] std::size_t
use_count() const;
useCount() const;
template <class TT, class... Args>
friend SharedIntrusive<TT>
make_SharedIntrusive(Args&&... args);
makeSharedIntrusive(Args&&... args);
template <class TT>
friend class SharedIntrusive;
@@ -364,7 +364,7 @@ public:
* return 0
*/
[[nodiscard]] std::size_t
use_count() const;
useCount() const;
/** Return true if there is a non-zero strong count. */
[[nodiscard]] bool
@@ -406,8 +406,8 @@ private:
// pointer. The low bit must be masked to zero when converting back to a
// pointer. If the low bit is '1', this is a weak pointer.
std::uintptr_t tp_{0};
static constexpr std::uintptr_t tagMask = 1;
static constexpr std::uintptr_t ptrMask = ~tagMask;
static constexpr std::uintptr_t kTAG_MASK = 1;
static constexpr std::uintptr_t kPTR_MASK = ~kTAG_MASK;
private:
/** Return the raw pointer held by this object.
@@ -415,7 +415,7 @@ private:
[[nodiscard]] T*
unsafeGetRawPtr() const;
enum class RefStrength { strong, weak };
enum class RefStrength { Strong, Weak };
/** Set the raw pointer and tag bit directly.
*/
void
@@ -442,7 +442,7 @@ private:
*/
template <class TT, class... Args>
SharedIntrusive<TT>
make_SharedIntrusive(Args&&... args)
makeSharedIntrusive(Args&&... args)
{
auto p = new TT(std::forward<Args>(args)...);
@@ -469,21 +469,21 @@ using SharedWeakUnionPtr = SharedWeakUnion<T>;
template <class T, class... A>
SharedPtr<T>
make_shared(A&&... args)
makeShared(A&&... args)
{
return make_SharedIntrusive<T>(std::forward<A>(args)...);
return makeSharedIntrusive<T>(std::forward<A>(args)...);
}
template <class T, class TT>
SharedPtr<T>
static_pointer_cast(TT const& v)
staticPointerCast(TT const& v)
{
return SharedPtr<T>(StaticCastTagSharedIntrusive{}, v);
}
template <class T, class TT>
SharedPtr<T>
dynamic_pointer_cast(TT const& v)
dynamicPointerCast(TT const& v)
{
return SharedPtr<T>(DynamicCastTagSharedIntrusive{}, v);
}

View File

@@ -43,14 +43,16 @@ SharedIntrusive<T>::SharedIntrusive(SharedIntrusive<TT> const& rhs)
}
template <class T>
SharedIntrusive<T>::SharedIntrusive(SharedIntrusive&& rhs) : ptr_{rhs.unsafeExchange(nullptr)}
SharedIntrusive<T>::SharedIntrusive(SharedIntrusive&& rhs)
: ptr_{std::move(rhs).unsafeExchange(nullptr)}
{
}
template <class T>
template <class TT>
requires std::convertible_to<TT*, T*>
SharedIntrusive<T>::SharedIntrusive(SharedIntrusive<TT>&& rhs) : ptr_{rhs.unsafeExchange(nullptr)}
SharedIntrusive<T>::SharedIntrusive(SharedIntrusive<TT>&& rhs)
: ptr_{std::move(rhs).unsafeExchange(nullptr)}
{
}
template <class T>
@@ -93,7 +95,7 @@ SharedIntrusive<T>::operator=(SharedIntrusive&& rhs)
if (this == &rhs)
return *this;
unsafeReleaseAndStore(rhs.unsafeExchange(nullptr));
unsafeReleaseAndStore(std::move(rhs).unsafeExchange(nullptr));
return *this;
}
@@ -105,7 +107,7 @@ SharedIntrusive<T>::operator=(SharedIntrusive<TT>&& rhs)
{
static_assert(!std::is_same_v<T, TT>, "This overload should not be instantiated for T == TT");
unsafeReleaseAndStore(rhs.unsafeExchange(nullptr));
unsafeReleaseAndStore(std::move(rhs).unsafeExchange(nullptr));
return *this;
}
@@ -157,7 +159,7 @@ SharedIntrusive<T>::SharedIntrusive(StaticCastTagSharedIntrusive, SharedIntrusiv
template <class T>
template <class TT>
SharedIntrusive<T>::SharedIntrusive(StaticCastTagSharedIntrusive, SharedIntrusive<TT>&& rhs)
: ptr_{static_cast<T*>(rhs.unsafeExchange(nullptr))}
: ptr_{static_cast<T*>(std::move(rhs).unsafeExchange(nullptr))}
{
}
@@ -184,8 +186,10 @@ SharedIntrusive<T>::SharedIntrusive(DynamicCastTagSharedIntrusive, SharedIntrusi
{
ptr_ = dynamic_cast<T*>(toSet);
if (!ptr_)
{
// need to set the pointer back or will leak
rhs.unsafeExchange(toSet);
std::move(rhs).unsafeExchange(toSet);
}
}
}
@@ -226,10 +230,10 @@ SharedIntrusive<T>::get() const
template <class T>
std::size_t
SharedIntrusive<T>::use_count() const
SharedIntrusive<T>::useCount() const
{
if (auto p = unsafeGetRawPtr())
return p->use_count();
return p->useCount();
return 0;
}
@@ -266,12 +270,12 @@ SharedIntrusive<T>::unsafeReleaseAndStore(T* next)
auto action = prev->releaseStrongRef();
switch (action)
{
case noop:
case NoOp:
break;
case destroy:
case Destroy:
delete prev;
break;
case partialDestroy:
case PartialDestroy:
prev->partialDestructor();
partialDestructorFinished(&prev);
// prev is null and may no longer be used
@@ -345,7 +349,7 @@ template <class T>
bool
WeakIntrusive<T>::expired() const
{
return (!ptr_ || ptr_->expired());
return ((ptr_ == nullptr) || ptr_->expired());
}
template <class T>
@@ -360,16 +364,16 @@ template <class T>
void
WeakIntrusive<T>::unsafeReleaseNoStore()
{
if (!ptr_)
if (ptr_ == nullptr)
return;
using enum ReleaseWeakRefAction;
auto action = ptr_->releaseWeakRef();
switch (action)
{
case noop:
case NoOp:
break;
case destroy:
case Destroy:
delete ptr_;
break;
}
@@ -385,9 +389,13 @@ SharedWeakUnion<T>::SharedWeakUnion(SharedWeakUnion const& rhs) : tp_{rhs.tp_}
return;
if (rhs.isStrong())
{
p->addStrongRef();
}
else
{
p->addWeakRef();
}
}
template <class T>
@@ -398,7 +406,7 @@ SharedWeakUnion<T>::SharedWeakUnion(SharedIntrusive<TT> const& rhs)
auto p = rhs.unsafeGetRawPtr();
if (p)
p->addStrongRef();
unsafeSetRawPtr(p, RefStrength::strong);
unsafeSetRawPtr(p, RefStrength::Strong);
}
template <class T>
@@ -414,8 +422,8 @@ SharedWeakUnion<T>::SharedWeakUnion(SharedIntrusive<TT>&& rhs)
{
auto p = rhs.unsafeGetRawPtr();
if (p)
unsafeSetRawPtr(p, RefStrength::strong);
rhs.unsafeSetRawPtr(nullptr);
unsafeSetRawPtr(p, RefStrength::Strong);
std::move(rhs).unsafeSetRawPtr(nullptr);
}
template <class T>
@@ -431,12 +439,12 @@ SharedWeakUnion<T>::operator=(SharedWeakUnion const& rhs)
if (rhs.isStrong())
{
p->addStrongRef();
unsafeSetRawPtr(p, RefStrength::strong);
unsafeSetRawPtr(p, RefStrength::Strong);
}
else
{
p->addWeakRef();
unsafeSetRawPtr(p, RefStrength::weak);
unsafeSetRawPtr(p, RefStrength::Weak);
}
}
else
@@ -456,7 +464,7 @@ SharedWeakUnion<T>::operator=(SharedIntrusive<TT> const& rhs)
auto p = rhs.unsafeGetRawPtr();
if (p)
p->addStrongRef();
unsafeSetRawPtr(p, RefStrength::strong);
unsafeSetRawPtr(p, RefStrength::Strong);
return *this;
}
@@ -467,8 +475,8 @@ SharedWeakUnion<T>&
SharedWeakUnion<T>::operator=(SharedIntrusive<TT>&& rhs)
{
unsafeReleaseNoStore();
unsafeSetRawPtr(rhs.unsafeGetRawPtr(), RefStrength::strong);
rhs.unsafeSetRawPtr(nullptr);
unsafeSetRawPtr(rhs.unsafeGetRawPtr(), RefStrength::Strong);
std::move(rhs).unsafeSetRawPtr(nullptr);
return *this;
}
@@ -517,10 +525,10 @@ SharedWeakUnion<T>::get() const
template <class T>
std::size_t
SharedWeakUnion<T>::use_count() const
SharedWeakUnion<T>::useCount() const
{
if (auto p = get())
return p->use_count();
return p->useCount();
return 0;
}
@@ -559,14 +567,14 @@ template <class T>
bool
SharedWeakUnion<T>::isStrong() const
{
return !(tp_ & tagMask);
return (tp_ & kTAG_MASK) == 0u;
}
template <class T>
bool
SharedWeakUnion<T>::isWeak() const
{
return tp_ & tagMask;
return (tp_ & kTAG_MASK) != 0u;
}
template <class T>
@@ -581,10 +589,10 @@ SharedWeakUnion<T>::convertToStrong()
{
[[maybe_unused]] auto action = p->releaseWeakRef();
XRPL_ASSERT(
(action == ReleaseWeakRefAction::noop),
(action == ReleaseWeakRefAction::NoOp),
"xrpl::SharedWeakUnion::convertToStrong : "
"action is noop");
unsafeSetRawPtr(p, RefStrength::strong);
unsafeSetRawPtr(p, RefStrength::Strong);
return true;
}
return false;
@@ -605,9 +613,9 @@ SharedWeakUnion<T>::convertToWeak()
auto action = p->addWeakReleaseStrongRef();
switch (action)
{
case noop:
case NoOp:
break;
case destroy:
case Destroy:
// We just added a weak ref. How could we destroy?
// LCOV_EXCL_START
UNREACHABLE(
@@ -617,7 +625,7 @@ SharedWeakUnion<T>::convertToWeak()
unsafeSetRawPtr(nullptr);
return true; // Should never happen
// LCOV_EXCL_STOP
case partialDestroy:
case PartialDestroy:
// This is a weird case. We just converted the last strong
// pointer to a weak pointer.
p->partialDestructor();
@@ -625,7 +633,7 @@ SharedWeakUnion<T>::convertToWeak()
// p is null and may no longer be used
break;
}
unsafeSetRawPtr(p, RefStrength::weak);
unsafeSetRawPtr(p, RefStrength::Weak);
return true;
}
@@ -633,7 +641,7 @@ template <class T>
T*
SharedWeakUnion<T>::unsafeGetRawPtr() const
{
return reinterpret_cast<T*>(tp_ & ptrMask);
return reinterpret_cast<T*>(tp_ & kPTR_MASK);
}
template <class T>
@@ -641,8 +649,8 @@ void
SharedWeakUnion<T>::unsafeSetRawPtr(T* p, RefStrength rs)
{
tp_ = reinterpret_cast<std::uintptr_t>(p);
if (tp_ && rs == RefStrength::weak)
tp_ |= tagMask;
if (tp_ && rs == RefStrength::Weak)
tp_ |= kTAG_MASK;
}
template <class T>
@@ -666,12 +674,12 @@ SharedWeakUnion<T>::unsafeReleaseNoStore()
auto strongAction = p->releaseStrongRef();
switch (strongAction)
{
case noop:
case NoOp:
break;
case destroy:
case Destroy:
delete p;
break;
case partialDestroy:
case PartialDestroy:
p->partialDestructor();
partialDestructorFinished(&p);
// p is null and may no longer be used
@@ -684,9 +692,9 @@ SharedWeakUnion<T>::unsafeReleaseNoStore()
auto weakAction = p->releaseWeakRef();
switch (weakAction)
{
case noop:
case NoOp:
break;
case destroy:
case Destroy:
delete p;
break;
}

View File

@@ -18,7 +18,7 @@ namespace xrpl {
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 };
enum class ReleaseStrongRefAction { NoOp, PartialDestroy, Destroy };
/** Action to perform when releasing a weak pointer.
@@ -28,7 +28,7 @@ enum class ReleaseStrongRefAction { noop, partialDestroy, destroy };
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 };
enum class ReleaseWeakRefAction { NoOp, Destroy };
/** Implement the strong count, weak count, and bit flags for an intrusive
pointer.
@@ -71,7 +71,7 @@ struct IntrusiveRefCounts
expired() const noexcept;
std::size_t
use_count() const noexcept;
useCount() const noexcept;
// This function MUST be called after a partial destructor finishes running.
// Calling this function may cause other threads to delete the object
@@ -98,11 +98,11 @@ private:
// enough for strong pointers and 14 bit counts are enough for weak
// pointers. Use type aliases to make it easy to switch types.
using CountType = std::uint16_t;
static constexpr size_t StrongCountNumBits = sizeof(CountType) * 8;
static constexpr size_t WeakCountNumBits = StrongCountNumBits - 2;
static constexpr size_t kSTRONG_COUNT_NUM_BITS = sizeof(CountType) * 8;
static constexpr size_t kWEAK_COUNT_NUM_BITS = kSTRONG_COUNT_NUM_BITS - 2;
using FieldType = std::uint32_t;
static constexpr size_t FieldTypeBits = sizeof(FieldType) * 8;
static constexpr FieldType one = 1;
static constexpr size_t kFIELD_TYPE_BITS = sizeof(FieldType) * 8;
static constexpr FieldType kONE = 1;
/** `refCounts` consists of four fields that are treated atomically:
@@ -137,21 +137,21 @@ private:
*/
mutable std::atomic<FieldType> refCounts{strongDelta};
mutable std::atomic<FieldType> refCounts_{kSTRONG_DELTA};
/** 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 strongDelta = 1;
static constexpr FieldType kSTRONG_DELTA = 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
*/
static constexpr FieldType weakDelta = (one << StrongCountNumBits);
static constexpr FieldType kWEAK_DELTA = (kONE << kSTRONG_COUNT_NUM_BITS);
/** Flag that is set when the partialDestroy function has started running
(or is about to start running).
@@ -159,33 +159,34 @@ private:
See description of the `refCounts` field for a fuller description of
this field.
*/
static constexpr FieldType partialDestroyStartedMask = (one << (FieldTypeBits - 1));
static constexpr FieldType kPARTIAL_DESTROY_STARTED_MASK = (kONE << (kFIELD_TYPE_BITS - 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.
*/
static constexpr FieldType partialDestroyFinishedMask = (one << (FieldTypeBits - 2));
static constexpr FieldType kPARTIAL_DESTROY_FINISHED_MASK = (kONE << (kFIELD_TYPE_BITS - 2));
/** Mask that will zero out all the `count` bits and leave the tag bits
unchanged.
*/
static constexpr FieldType tagMask = partialDestroyStartedMask | partialDestroyFinishedMask;
static constexpr FieldType kTAG_MASK =
kPARTIAL_DESTROY_STARTED_MASK | kPARTIAL_DESTROY_FINISHED_MASK;
/** Mask that will zero out the `tag` bits and leave the count bits
unchanged.
*/
static constexpr FieldType valueMask = ~tagMask;
static constexpr FieldType kVALUE_MASK = ~kTAG_MASK;
/** Mask that will zero out everything except the strong count.
*/
static constexpr FieldType strongMask = ((one << StrongCountNumBits) - 1) & valueMask;
static constexpr FieldType kSTRONG_MASK = ((kONE << kSTRONG_COUNT_NUM_BITS) - 1) & kVALUE_MASK;
/** Mask that will zero out everything except the weak count.
*/
static constexpr FieldType weakMask =
(((one << WeakCountNumBits) - 1) << StrongCountNumBits) & valueMask;
static constexpr FieldType kWEAK_MASK =
(((kONE << kWEAK_COUNT_NUM_BITS) - 1) << kSTRONG_COUNT_NUM_BITS) & kVALUE_MASK;
/** Unpack the count and tag fields from the packed atomic integer form. */
struct RefCountPair
@@ -210,29 +211,29 @@ private:
[[nodiscard]] FieldType
combinedValue() const noexcept;
static constexpr CountType maxStrongValue =
static_cast<CountType>((one << StrongCountNumBits) - 1);
static constexpr CountType maxWeakValue =
static_cast<CountType>((one << WeakCountNumBits) - 1);
static constexpr CountType kMAX_STRONG_VALUE =
static_cast<CountType>((kONE << kSTRONG_COUNT_NUM_BITS) - 1);
static constexpr CountType kMAX_WEAK_VALUE =
static_cast<CountType>((kONE << kWEAK_COUNT_NUM_BITS) - 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).
*/
static constexpr CountType checkStrongMaxValue = maxStrongValue - 32;
static constexpr CountType checkWeakMaxValue = maxWeakValue - 32;
static constexpr CountType kCHECK_STRONG_MAX_VALUE = kMAX_STRONG_VALUE - 32;
static constexpr CountType kCHECK_WEAK_MAX_VALUE = kMAX_WEAK_VALUE - 32;
};
};
inline void
IntrusiveRefCounts::addStrongRef() const noexcept
{
refCounts.fetch_add(strongDelta, std::memory_order_acq_rel);
refCounts_.fetch_add(kSTRONG_DELTA, std::memory_order_acq_rel);
}
inline void
IntrusiveRefCounts::addWeakRef() const noexcept
{
refCounts.fetch_add(weakDelta, std::memory_order_acq_rel);
refCounts_.fetch_add(kWEAK_DELTA, std::memory_order_acq_rel);
}
inline ReleaseStrongRefAction
@@ -246,36 +247,36 @@ IntrusiveRefCounts::releaseStrongRef() const
// conditional `fetch_or`. This loop will almost always run once.
using enum ReleaseStrongRefAction;
auto prevIntVal = refCounts.load(std::memory_order_acquire);
auto prevIntVal = refCounts_.load(std::memory_order_acquire);
while (true)
{
RefCountPair const prevVal{prevIntVal};
XRPL_ASSERT(
(prevVal.strong >= strongDelta),
(prevVal.strong >= kSTRONG_DELTA),
"xrpl::IntrusiveRefCounts::releaseStrongRef : previous ref "
"higher than new");
auto nextIntVal = prevIntVal - strongDelta;
ReleaseStrongRefAction action = noop;
auto nextIntVal = prevIntVal - kSTRONG_DELTA;
ReleaseStrongRefAction action = NoOp;
if (prevVal.strong == 1)
{
if (prevVal.weak == 0)
{
action = destroy;
action = Destroy;
}
else
{
nextIntVal |= partialDestroyStartedMask;
action = partialDestroy;
nextIntVal |= kPARTIAL_DESTROY_STARTED_MASK;
action = PartialDestroy;
}
}
if (refCounts.compare_exchange_weak(prevIntVal, nextIntVal, std::memory_order_acq_rel))
if (refCounts_.compare_exchange_weak(prevIntVal, nextIntVal, std::memory_order_acq_rel))
{
// Can't be in partial destroy because only decrementing the strong
// count to zero can start a partial destroy, and that can't happen
// twice.
XRPL_ASSERT(
(action == noop) || !(prevIntVal & partialDestroyStartedMask),
(action == NoOp) || !(prevIntVal & kPARTIAL_DESTROY_STARTED_MASK),
"xrpl::IntrusiveRefCounts::releaseStrongRef : not in partial "
"destroy");
return action;
@@ -288,9 +289,9 @@ IntrusiveRefCounts::addWeakReleaseStrongRef() const
{
using enum ReleaseStrongRefAction;
static_assert(weakDelta > strongDelta);
auto constexpr delta = weakDelta - strongDelta;
auto prevIntVal = refCounts.load(std::memory_order_acquire);
static_assert(kWEAK_DELTA > kSTRONG_DELTA);
auto constexpr kDELTA = kWEAK_DELTA - kSTRONG_DELTA;
auto prevIntVal = refCounts_.load(std::memory_order_acquire);
// This loop will almost always run once. The loop is needed to atomically
// change the counts and flags (the count could be atomically changed, but
// the flags depend on the current value of the counts).
@@ -311,24 +312,24 @@ IntrusiveRefCounts::addWeakReleaseStrongRef() const
"xrpl::IntrusiveRefCounts::addWeakReleaseStrongRef : not in "
"partial destroy");
auto nextIntVal = prevIntVal + delta;
ReleaseStrongRefAction action = noop;
auto nextIntVal = prevIntVal + kDELTA;
ReleaseStrongRefAction action = NoOp;
if (prevVal.strong == 1)
{
if (prevVal.weak == 0)
{
action = noop;
action = NoOp;
}
else
{
nextIntVal |= partialDestroyStartedMask;
action = partialDestroy;
nextIntVal |= kPARTIAL_DESTROY_STARTED_MASK;
action = PartialDestroy;
}
}
if (refCounts.compare_exchange_weak(prevIntVal, nextIntVal, std::memory_order_acq_rel))
if (refCounts_.compare_exchange_weak(prevIntVal, nextIntVal, std::memory_order_acq_rel))
{
XRPL_ASSERT(
(!(prevIntVal & partialDestroyStartedMask)),
(!(prevIntVal & kPARTIAL_DESTROY_STARTED_MASK)),
"xrpl::IntrusiveRefCounts::addWeakReleaseStrongRef : not "
"started partial destroy");
return action;
@@ -339,7 +340,7 @@ IntrusiveRefCounts::addWeakReleaseStrongRef() const
inline ReleaseWeakRefAction
IntrusiveRefCounts::releaseWeakRef() const
{
auto prevIntVal = refCounts.fetch_sub(weakDelta, std::memory_order_acq_rel);
auto prevIntVal = refCounts_.fetch_sub(kWEAK_DELTA, std::memory_order_acq_rel);
RefCountPair prev = prevIntVal;
if (prev.weak == 1 && prev.strong == 0)
{
@@ -348,19 +349,19 @@ IntrusiveRefCounts::releaseWeakRef() const
// This case should only be hit if the partialDestroyStartedBit is
// set non-atomically (and even then very rarely). The code is kept
// in case we need to set the flag non-atomically for perf reasons.
refCounts.wait(prevIntVal, std::memory_order_acquire);
prevIntVal = refCounts.load(std::memory_order_acquire);
refCounts_.wait(prevIntVal, std::memory_order_acquire);
prevIntVal = refCounts_.load(std::memory_order_acquire);
prev = RefCountPair{prevIntVal};
}
if (prev.partialDestroyFinishedBit == 0u)
{
// partial destroy MUST finish before running a full destroy (when
// using weak pointers)
refCounts.wait(prevIntVal - weakDelta, std::memory_order_acquire);
refCounts_.wait(prevIntVal - kWEAK_DELTA, std::memory_order_acquire);
}
return ReleaseWeakRefAction::destroy;
return ReleaseWeakRefAction::Destroy;
}
return ReleaseWeakRefAction::noop;
return ReleaseWeakRefAction::NoOp;
}
inline bool
@@ -369,13 +370,13 @@ IntrusiveRefCounts::checkoutStrongRefFromWeak() const noexcept
auto curValue = RefCountPair{1, 1}.combinedValue();
auto desiredValue = RefCountPair{2, 1}.combinedValue();
while (!refCounts.compare_exchange_weak(curValue, desiredValue, std::memory_order_acq_rel))
while (!refCounts_.compare_exchange_weak(curValue, desiredValue, std::memory_order_acq_rel))
{
RefCountPair const prev{curValue};
if (prev.strong == 0u)
return false;
desiredValue = curValue + strongDelta;
desiredValue = curValue + kSTRONG_DELTA;
}
return true;
}
@@ -383,38 +384,39 @@ IntrusiveRefCounts::checkoutStrongRefFromWeak() const noexcept
inline bool
IntrusiveRefCounts::expired() const noexcept
{
RefCountPair const val = refCounts.load(std::memory_order_acquire);
RefCountPair const val = refCounts_.load(std::memory_order_acquire);
return val.strong == 0;
}
inline std::size_t
IntrusiveRefCounts::use_count() const noexcept
IntrusiveRefCounts::useCount() const noexcept
{
RefCountPair const val = refCounts.load(std::memory_order_acquire);
RefCountPair const val = refCounts_.load(std::memory_order_acquire);
return val.strong;
}
inline IntrusiveRefCounts::~IntrusiveRefCounts() noexcept
{
#ifndef NDEBUG
auto v = refCounts.load(std::memory_order_acquire);
auto v = refCounts_.load(std::memory_order_acquire);
XRPL_ASSERT(
(!(v & valueMask)), "xrpl::IntrusiveRefCounts::~IntrusiveRefCounts : count must be zero");
auto t = v & tagMask;
XRPL_ASSERT((!t || t == tagMask), "xrpl::IntrusiveRefCounts::~IntrusiveRefCounts : valid tag");
(!(v & kVALUE_MASK)), "xrpl::IntrusiveRefCounts::~IntrusiveRefCounts : count must be zero");
auto t = v & kTAG_MASK;
XRPL_ASSERT(
(!t || t == kTAG_MASK), "xrpl::IntrusiveRefCounts::~IntrusiveRefCounts : valid tag");
#endif
}
//------------------------------------------------------------------------------
inline IntrusiveRefCounts::RefCountPair::RefCountPair(IntrusiveRefCounts::FieldType v) noexcept
: strong{static_cast<CountType>(v & strongMask)}
, weak{static_cast<CountType>((v & weakMask) >> StrongCountNumBits)}
, partialDestroyStartedBit{v & partialDestroyStartedMask}
, partialDestroyFinishedBit{v & partialDestroyFinishedMask}
: strong{static_cast<CountType>(v & kSTRONG_MASK)}
, weak{static_cast<CountType>((v & kWEAK_MASK) >> kSTRONG_COUNT_NUM_BITS)}
, partialDestroyStartedBit{v & kPARTIAL_DESTROY_STARTED_MASK}
, partialDestroyFinishedBit{v & kPARTIAL_DESTROY_FINISHED_MASK}
{
XRPL_ASSERT(
(strong < checkStrongMaxValue && weak < checkWeakMaxValue),
(strong < kCHECK_STRONG_MAX_VALUE && weak < kCHECK_WEAK_MAX_VALUE),
"xrpl::IntrusiveRefCounts::RefCountPair(FieldType) : inputs inside "
"range");
}
@@ -425,7 +427,7 @@ inline IntrusiveRefCounts::RefCountPair::RefCountPair(
: strong{s}, weak{w}
{
XRPL_ASSERT(
(strong < checkStrongMaxValue && weak < checkWeakMaxValue),
(strong < kCHECK_STRONG_MAX_VALUE && weak < kCHECK_WEAK_MAX_VALUE),
"xrpl::IntrusiveRefCounts::RefCountPair(CountType, CountType) : "
"inputs inside range");
}
@@ -434,11 +436,11 @@ inline IntrusiveRefCounts::FieldType
IntrusiveRefCounts::RefCountPair::combinedValue() const noexcept
{
XRPL_ASSERT(
(strong < checkStrongMaxValue && weak < checkWeakMaxValue),
(strong < kCHECK_STRONG_MAX_VALUE && weak < kCHECK_WEAK_MAX_VALUE),
"xrpl::IntrusiveRefCounts::RefCountPair::combinedValue : inputs "
"inside range");
return (static_cast<IntrusiveRefCounts::FieldType>(weak)
<< IntrusiveRefCounts::StrongCountNumBits) |
<< IntrusiveRefCounts::kSTRONG_COUNT_NUM_BITS) |
static_cast<IntrusiveRefCounts::FieldType>(strong) | partialDestroyStartedBit |
partialDestroyFinishedBit;
}
@@ -449,7 +451,7 @@ partialDestructorFinished(T** o)
{
T& self = **o;
IntrusiveRefCounts::RefCountPair const p =
self.refCounts.fetch_or(IntrusiveRefCounts::partialDestroyFinishedMask);
self.refCounts_.fetch_or(IntrusiveRefCounts::kPARTIAL_DESTROY_FINISHED_MASK);
XRPL_ASSERT(
(!p.partialDestroyFinishedBit && p.partialDestroyStartedBit && !p.strong),
"xrpl::partialDestructorFinished : not a weak ref");
@@ -458,7 +460,7 @@ partialDestructorFinished(T** o)
// There was a weak count before the partial destructor ran (or we would
// have run the full destructor) and now there isn't a weak count. Some
// thread is waiting to run the destructor.
self.refCounts.notify_one();
self.refCounts_.notify_one();
}
// Set the pointer to null to emphasize that the object shouldn't be used
// after calling this function as it may be destroyed in another thread.

View File

@@ -26,17 +26,17 @@ struct LocalValues
template <class T>
struct Value : BasicValue
{
T t_;
T t;
Value() = default;
explicit Value(T t) : t_(std::move(t))
explicit Value(T t) : t(std::move(t))
{
}
void*
get() override
{
return &t_;
return &t;
}
};
@@ -55,8 +55,8 @@ template <class = void>
boost::thread_specific_ptr<detail::LocalValues>&
getLocalValues()
{
static boost::thread_specific_ptr<detail::LocalValues> tsp(&detail::LocalValues::cleanup);
return tsp;
static boost::thread_specific_ptr<detail::LocalValues> kTSP(&detail::LocalValues::cleanup);
return kTSP;
}
} // namespace detail

View File

@@ -15,16 +15,17 @@
namespace xrpl {
// DEPRECATED use beast::severities::Severity instead
// NOLINTNEXTLINE(cppcoreguidelines-use-enum-class)
enum LogSeverity {
lsINVALID = -1, // used to indicate an invalid severity
lsTRACE = 0, // Very low-level progress information, details inside
LSInvalid = -1, // used to indicate an invalid severity
LSTrace = 0, // Very low-level progress information, details inside
// an operation
lsDEBUG = 1, // Function-level progress information, operations
lsINFO = 2, // Server-level progress information, major operations
lsWARNING = 3, // Conditions that warrant human attention, may indicate
LSDebug = 1, // Function-level progress information, operations
LSInfo = 2, // Server-level progress information, major operations
LSWarning = 3, // Conditions that warrant human attention, may indicate
// a problem
lsERROR = 4, // A condition that indicates a problem
lsFATAL = 5 // A severe condition that indicates a server problem
LSError = 4, // A condition that indicates a problem
LSFatal = 5 // A severe condition that indicates a server problem
};
/** Manages partitions for logging. */
@@ -129,8 +130,8 @@ private:
/** @} */
private:
std::unique_ptr<std::ofstream> m_stream;
boost::filesystem::path m_path;
std::unique_ptr<std::ofstream> stream_;
boost::filesystem::path path_;
};
std::mutex mutable mutex_;
@@ -167,7 +168,7 @@ public:
threshold(beast::severities::Severity thresh);
std::vector<std::pair<std::string, std::string>>
partition_severities() const;
partitionSeverities() const;
void
write(
@@ -207,11 +208,13 @@ public:
fromString(std::string const& s);
private:
// Need to be named before converting
// NOLINTNEXTLINE(cppcoreguidelines-use-enum-class)
enum {
// Maximum line length for log messages.
// If the message exceeds this length it will be truncated with
// ellipses.
maximumMessageCharacters = 12 * 1024
MaximumMessageCharacters = 12 * 1024
};
static void

View File

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

View File

@@ -70,27 +70,27 @@ isPowerOfTen(T value)
struct MantissaRange
{
using rep = std::uint64_t;
enum mantissa_scale { small, large };
enum class MantissaScale { Small, Large };
explicit constexpr MantissaRange(mantissa_scale scale_)
: min(getMin(scale_)), log(logTen(min).value_or(-1)), scale(scale_)
explicit constexpr MantissaRange(MantissaScale scale)
: min(getMin(scale)), log(logTen(min).value_or(-1)), scale(scale)
{
}
rep min;
rep max{(min * 10) - 1};
int log;
mantissa_scale scale;
MantissaScale scale;
private:
static constexpr rep
getMin(mantissa_scale scale_)
getMin(MantissaScale scale)
{
switch (scale_)
switch (scale)
{
case small:
case MantissaScale::Small:
return 1'000'000'000'000'000ULL;
case large:
case MantissaScale::Large:
return 1'000'000'000'000'000'000ULL;
default:
// Since this can never be called outside a non-constexpr
@@ -214,26 +214,26 @@ class Number
public:
// The range for the exponent when normalized
constexpr static int minExponent = -32768;
constexpr static int maxExponent = 32768;
constexpr static int kMIN_EXPONENT = -32768;
constexpr static int kMAX_EXPONENT = 32768;
constexpr static internalrep maxRep = std::numeric_limits<rep>::max();
static_assert(maxRep == 9'223'372'036'854'775'807);
static_assert(-maxRep == std::numeric_limits<rep>::min() + 1);
constexpr static internalrep kMAX_REP = std::numeric_limits<rep>::max();
static_assert(kMAX_REP == 9'223'372'036'854'775'807);
static_assert(-kMAX_REP == std::numeric_limits<rep>::min() + 1);
// May need to make unchecked private
struct unchecked
struct Unchecked
{
explicit unchecked() = default;
explicit Unchecked() = default;
};
// Like unchecked, normalized is used with the ctors that take an
// internalrep mantissa. Unlike unchecked, those ctors will normalize the
// value.
// Only unit tests are expected to use this class
struct normalized
struct Normalized
{
explicit normalized() = default;
explicit Normalized() = default;
};
explicit constexpr Number() = default;
@@ -244,13 +244,13 @@ public:
bool negative,
internalrep mantissa,
int exponent,
unchecked) noexcept;
Unchecked) noexcept;
// Assume unsigned values are... unsigned. i.e. positive
explicit constexpr Number(internalrep mantissa, int exponent, unchecked) noexcept;
explicit constexpr Number(internalrep mantissa, int exponent, Unchecked) noexcept;
// Only unit tests are expected to use this ctor
explicit Number(bool negative, internalrep mantissa, int exponent, normalized);
explicit Number(bool negative, internalrep mantissa, int exponent, Normalized);
// Assume unsigned values are... unsigned. i.e. positive
explicit Number(internalrep mantissa, int exponent, normalized);
explicit Number(internalrep mantissa, int exponent, Normalized);
[[nodiscard]] constexpr rep
mantissa() const noexcept;
@@ -384,42 +384,44 @@ public:
root2(Number f);
// Thread local rounding control. Default is to_nearest
enum rounding_mode { to_nearest, towards_zero, downward, upward };
static rounding_mode
enum class RoundingMode { ToNearest, TowardsZero, Downward, Upward };
static RoundingMode
getround();
// Returns previously set mode
static rounding_mode
setround(rounding_mode mode);
static RoundingMode
setround(RoundingMode inMode);
/** 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::mantissa_scale
static MantissaRange::MantissaScale
getMantissaScale();
/** Changes which mantissa scale is used for normalization.
*
* If you think you need to call this outside of unit tests, no you don't.
*/
static void
setMantissaScale(MantissaRange::mantissa_scale scale);
setMantissaScale(MantissaRange::MantissaScale scale);
static internalrep
minMantissa()
{
return range_.get().min;
return kRANGE.get().min;
}
static internalrep
maxMantissa()
{
return range_.get().max;
return kRANGE.get().max;
}
static int
mantissaLog()
{
return range_.get().log;
return kRANGE.get().log;
}
/// oneSmall is needed because the ranges are private
@@ -440,28 +442,28 @@ public:
normalizeToRange(T minMantissa, T maxMantissa) const;
private:
static thread_local rounding_mode mode_;
static thread_local RoundingMode mode;
// The available ranges for mantissa
constexpr static MantissaRange smallRange{MantissaRange::small};
static_assert(isPowerOfTen(smallRange.min));
static_assert(smallRange.min == 1'000'000'000'000'000LL);
static_assert(smallRange.max == 9'999'999'999'999'999LL);
static_assert(smallRange.log == 15);
static_assert(smallRange.min < maxRep);
static_assert(smallRange.max < maxRep);
constexpr static MantissaRange largeRange{MantissaRange::large};
static_assert(isPowerOfTen(largeRange.min));
static_assert(largeRange.min == 1'000'000'000'000'000'000ULL);
static_assert(largeRange.max == internalrep(9'999'999'999'999'999'999ULL));
static_assert(largeRange.log == 18);
static_assert(largeRange.min < maxRep);
static_assert(largeRange.max > maxRep);
constexpr static MantissaRange kSMALL_RANGE{MantissaRange::MantissaScale::Small};
static_assert(isPowerOfTen(kSMALL_RANGE.min));
static_assert(kSMALL_RANGE.min == 1'000'000'000'000'000LL);
static_assert(kSMALL_RANGE.max == 9'999'999'999'999'999LL);
static_assert(kSMALL_RANGE.log == 15);
static_assert(kSMALL_RANGE.min < kMAX_REP);
static_assert(kSMALL_RANGE.max < kMAX_REP);
constexpr static MantissaRange kLARGE_RANGE{MantissaRange::MantissaScale::Large};
static_assert(isPowerOfTen(kLARGE_RANGE.min));
static_assert(kLARGE_RANGE.min == 1'000'000'000'000'000'000ULL);
static_assert(kLARGE_RANGE.max == internalrep(9'999'999'999'999'999'999ULL));
static_assert(kLARGE_RANGE.log == 18);
static_assert(kLARGE_RANGE.min < kMAX_REP);
static_assert(kLARGE_RANGE.max > kMAX_REP);
// The range for the mantissa when normalized.
// Use reference_wrapper to avoid making copies, and prevent accidentally
// changing the values inside the range.
static thread_local std::reference_wrapper<MantissaRange const> range_;
static thread_local std::reference_wrapper<MantissaRange const> kRANGE;
void
normalize();
@@ -469,7 +471,7 @@ private:
/** Normalize Number components to an arbitrary range.
*
* min/maxMantissa are parameters because this function is used by both
* normalize(), which reads from range_, and by normalizeToRange,
* normalize(), which reads from kRANGE, and by normalizeToRange,
* which is public and can accept an arbitrary range from the caller.
*/
template <class T>
@@ -485,8 +487,8 @@ private:
friend void
doNormalize(
bool& negative,
T& mantissa_,
int& exponent_,
T& mantissa,
int& exponent,
MantissaRange::rep const& minMantissa,
MantissaRange::rep const& maxMantissa);
@@ -509,31 +511,31 @@ private:
class Guard;
};
constexpr Number::Number(bool negative, internalrep mantissa, int exponent, unchecked) noexcept
constexpr Number::Number(bool negative, internalrep mantissa, int exponent, Unchecked) noexcept
: negative_(negative), mantissa_{mantissa}, exponent_{exponent}
{
}
constexpr Number::Number(internalrep mantissa, int exponent, unchecked) noexcept
: Number(false, mantissa, exponent, unchecked{})
constexpr Number::Number(internalrep mantissa, int exponent, Unchecked) noexcept
: Number(false, mantissa, exponent, Unchecked{})
{
}
constexpr static Number numZero{};
constexpr static Number kNUM_ZERO{};
inline Number::Number(bool negative, internalrep mantissa, int exponent, normalized)
: Number(negative, mantissa, exponent, unchecked{})
inline Number::Number(bool negative, internalrep mantissa, int exponent, Normalized)
: Number(negative, mantissa, exponent, Unchecked{})
{
normalize();
}
inline Number::Number(internalrep mantissa, int exponent, normalized)
: Number(false, mantissa, exponent, normalized{})
inline Number::Number(internalrep mantissa, int exponent, Normalized)
: Number(false, mantissa, exponent, Normalized{})
{
}
inline Number::Number(rep mantissa, int exponent)
: Number(mantissa < 0, externalToInternal(mantissa), exponent, normalized{})
: Number(mantissa < 0, externalToInternal(mantissa), exponent, Normalized{})
{
}
@@ -550,10 +552,10 @@ constexpr Number::rep
Number::mantissa() const noexcept
{
auto m = mantissa_;
if (m > maxRep)
if (m > kMAX_REP)
{
XRPL_ASSERT_PARTS(
!isnormal() || (m % 10 == 0 && m / 10 <= maxRep),
!isnormal() || (m % 10 == 0 && m / 10 <= kMAX_REP),
"xrpl::Number::mantissa",
"large normalized mantissa has no remainder");
m /= 10;
@@ -571,10 +573,10 @@ constexpr int
Number::exponent() const noexcept
{
auto e = exponent_;
if (mantissa_ > maxRep)
if (mantissa_ > kMAX_REP)
{
XRPL_ASSERT_PARTS(
!isnormal() || (mantissa_ % 10 == 0 && mantissa_ / 10 <= maxRep),
!isnormal() || (mantissa_ % 10 == 0 && mantissa_ / 10 <= kMAX_REP),
"xrpl::Number::exponent",
"large normalized mantissa has no remainder");
++e;
@@ -669,29 +671,29 @@ operator/(Number const& x, Number const& y)
inline Number
Number::min() noexcept
{
return Number{false, range_.get().min, minExponent, unchecked{}};
return Number{false, kRANGE.get().min, kMIN_EXPONENT, Unchecked{}};
}
inline Number
Number::max() noexcept
{
return Number{false, std::min(range_.get().max, maxRep), maxExponent, unchecked{}};
return Number{false, std::min(kRANGE.get().max, kMAX_REP), kMAX_EXPONENT, Unchecked{}};
}
inline Number
Number::lowest() noexcept
{
return Number{true, std::min(range_.get().max, maxRep), maxExponent, unchecked{}};
return Number{true, std::min(kRANGE.get().max, kMAX_REP), kMAX_EXPONENT, Unchecked{}};
}
inline bool
Number::isnormal() const noexcept
{
MantissaRange const& range = range_;
auto const abs_m = mantissa_;
MantissaRange const& range = kRANGE;
auto const absM = mantissa_;
return *this == Number{} ||
(range.min <= abs_m && abs_m <= range.max && (abs_m <= maxRep || abs_m % 10 == 0) &&
minExponent <= exponent_ && exponent_ <= maxExponent);
(range.min <= absM && absM <= range.max && (absM <= kMAX_REP || absM % 10 == 0) &&
kMIN_EXPONENT <= exponent_ && exponent_ <= kMAX_EXPONENT);
}
template <Integral64 T>
@@ -755,34 +757,34 @@ squelch(Number const& x, Number const& limit) noexcept
}
inline std::string
to_string(MantissaRange::mantissa_scale const& scale)
to_string(MantissaRange::MantissaScale const& scale)
{
switch (scale)
{
case MantissaRange::small:
case MantissaRange::MantissaScale::Small:
return "small";
case MantissaRange::large:
case MantissaRange::MantissaScale::Large:
return "large";
default:
throw std::runtime_error("Bad scale");
}
}
class saveNumberRoundMode
class SaveNumberRoundMode
{
Number::rounding_mode mode_;
Number::RoundingMode mode_;
public:
~saveNumberRoundMode()
~SaveNumberRoundMode()
{
Number::setround(mode_);
}
explicit saveNumberRoundMode(Number::rounding_mode mode) noexcept : mode_{mode}
explicit SaveNumberRoundMode(Number::RoundingMode mode) noexcept : mode_{mode}
{
}
saveNumberRoundMode(saveNumberRoundMode const&) = delete;
saveNumberRoundMode&
operator=(saveNumberRoundMode const&) = delete;
SaveNumberRoundMode(SaveNumberRoundMode const&) = delete;
SaveNumberRoundMode&
operator=(SaveNumberRoundMode const&) = delete;
};
// saveNumberRoundMode doesn't do quite enough for us. What we want is a
@@ -791,10 +793,10 @@ public:
// build it here.
class NumberRoundModeGuard
{
saveNumberRoundMode saved_;
SaveNumberRoundMode saved_;
public:
explicit NumberRoundModeGuard(Number::rounding_mode mode) noexcept
explicit NumberRoundModeGuard(Number::RoundingMode mode) noexcept
: saved_{Number::setround(mode)}
{
}
@@ -812,10 +814,10 @@ public:
*/
class NumberMantissaScaleGuard
{
MantissaRange::mantissa_scale const saved_;
MantissaRange::MantissaScale const saved_;
public:
explicit NumberMantissaScaleGuard(MantissaRange::mantissa_scale scale) noexcept
explicit NumberMantissaScaleGuard(MantissaRange::MantissaScale scale) noexcept
: saved_{Number::getMantissaScale()}
{
Number::setMantissaScale(scale);

View File

@@ -101,7 +101,7 @@ to_string(RangeSet<T> const& rs)
*/
template <class T>
[[nodiscard]] bool
from_string(RangeSet<T>& rs, std::string const& s)
fromString(RangeSet<T>& rs, std::string const& s)
{
std::vector<std::string> intervals;
std::vector<std::string> tokens;

View File

@@ -16,7 +16,7 @@ public:
/** Issue an asynchronous stop request. */
virtual void
stop_async() = 0;
stopAsync() = 0;
/** Issue a synchronous stop request. */
virtual void

View File

@@ -13,7 +13,7 @@ public:
explicit ResolverAsio() = default;
static std::unique_ptr<ResolverAsio>
New(boost::asio::io_context&, beast::Journal);
make(boost::asio::io_context&, beast::Journal);
};
} // namespace xrpl

View File

@@ -21,12 +21,12 @@ public:
}
[[nodiscard]] uint256 const&
as_uint256() const
asUint256() const
{
return hash_;
}
uint256&
as_uint256()
asUint256()
{
return hash_;
}
@@ -93,7 +93,7 @@ template <>
inline std::size_t
extract(SHAMapHash const& key)
{
return *reinterpret_cast<std::size_t const*>(key.as_uint256().data());
return *reinterpret_cast<std::size_t const*>(key.asUint256().data());
}
} // namespace xrpl

View File

@@ -73,7 +73,7 @@ public:
/** If this is a strong pointer, return the strong count. Otherwise return 0
*/
[[nodiscard]] std::size_t
use_count() const;
useCount() const;
/** Return true if there is a non-zero strong count. */
[[nodiscard]] bool

View File

@@ -57,10 +57,10 @@ template <class T>
std::shared_ptr<T> const&
SharedWeakCachePointer<T>::getStrong() const
{
static std::shared_ptr<T> const empty;
static std::shared_ptr<T> const kEMPTY;
if (auto p = std::get_if<std::shared_ptr<T>>(&combo_))
return *p;
return empty;
return kEMPTY;
}
template <class T>
@@ -86,7 +86,7 @@ SharedWeakCachePointer<T>::get() const
template <class T>
std::size_t
SharedWeakCachePointer<T>::use_count() const
SharedWeakCachePointer<T>::useCount() const
{
if (auto p = std::get_if<std::shared_ptr<T>>(&combo_))
return p->use_count();

View File

@@ -36,32 +36,32 @@ class SlabAllocator
struct SlabBlock
{
// A mutex to protect the freelist for this block:
std::mutex m_;
std::mutex m;
// A linked list of appropriately sized free buffers:
std::uint8_t* l_ = nullptr;
std::uint8_t* l = nullptr;
// The next memory block
SlabBlock* next_;
SlabBlock* next;
// The underlying memory block:
std::uint8_t const* const p_ = nullptr;
std::uint8_t const* const p = nullptr;
// The extent of the underlying memory block:
std::size_t const size_;
std::size_t const size;
SlabBlock(SlabBlock* next, std::uint8_t* data, std::size_t size, std::size_t item)
: next_(next), p_(data), size_(size)
: next(next), p(data), size(size)
{
// We don't need to grab the mutex here, since we're the only
// ones with access at this moment.
while (data + item <= p_ + size_)
while (data + item <= p + size)
{
// Use memcpy to avoid unaligned UB
// (will optimize to equivalent code)
std::memcpy(data, static_cast<void const*>(&l_), sizeof(std::uint8_t*));
l_ = data;
std::memcpy(data, static_cast<void const*>(&l), sizeof(std::uint8_t*));
l = data;
data += item;
}
}
@@ -81,9 +81,9 @@ class SlabAllocator
/** Determines whether the given pointer belongs to this allocator */
bool
own(std::uint8_t const* p) const noexcept
own(std::uint8_t const* pIn) const noexcept
{
return (p >= p_) && (p < p_ + size_);
return (pIn >= p) && (pIn < p + size);
}
std::uint8_t*
@@ -92,15 +92,14 @@ class SlabAllocator
std::uint8_t* ret = nullptr; // NOLINT(misc-const-correctness)
{
std::lock_guard const l(m_);
ret = l_;
std::scoped_lock const lock(m);
ret = l;
if (ret != nullptr)
{
// Use memcpy to avoid unaligned UB
// (will optimize to equivalent code)
std::memcpy(static_cast<void*>(&l_), ret, sizeof(std::uint8_t*));
std::memcpy(static_cast<void*>(&l), ret, sizeof(std::uint8_t*));
}
}
@@ -121,12 +120,12 @@ class SlabAllocator
{
XRPL_ASSERT(own(ptr), "xrpl::SlabAllocator::SlabBlock::deallocate : own input");
std::lock_guard const l(m_);
std::scoped_lock const lock(m);
// Use memcpy to avoid unaligned UB
// (will optimize to equivalent code)
std::memcpy(ptr, static_cast<void const*>(&l_), sizeof(std::uint8_t*));
l_ = ptr;
std::memcpy(ptr, static_cast<void const*>(&l), sizeof(std::uint8_t*));
l = ptr;
}
};
@@ -201,7 +200,7 @@ public:
if (auto ret = slab->allocate())
return ret;
slab = slab->next_;
slab = slab->next;
}
// No slab can satisfy our request, so we attempt to allocate a new
@@ -242,7 +241,7 @@ public:
// Link the new slab
while (!slabs_.compare_exchange_weak(
slab->next_, slab, std::memory_order_release, std::memory_order_relaxed))
slab->next, slab, std::memory_order_release, std::memory_order_relaxed))
{
; // Nothing to do
}
@@ -265,7 +264,7 @@ public:
"xrpl::SlabAllocator::SlabAllocator::deallocate : non-null "
"input");
for (auto slab = slabs_.load(); slab != nullptr; slab = slab->next_)
for (auto slab = slabs_.load(); slab != nullptr; slab = slab->next)
{
if (slab->own(ptr))
{
@@ -294,16 +293,16 @@ public:
friend class SlabAllocatorSet;
private:
std::size_t extra;
std::size_t alloc;
std::size_t align;
std::size_t extra_;
std::size_t alloc_;
std::size_t align_;
public:
constexpr SlabConfig(
std::size_t extra_,
std::size_t alloc_ = 0,
std::size_t align_ = alignof(Type))
: extra(extra_), alloc(alloc_), align(align_)
std::size_t extra,
std::size_t alloc = 0,
std::size_t align = alignof(Type))
: extra_(extra), alloc_(alloc), align_(align)
{
}
};
@@ -313,22 +312,22 @@ public:
// Ensure that the specified allocators are sorted from smallest to
// largest by size:
std::sort(std::begin(cfg), std::end(cfg), [](SlabConfig const& a, SlabConfig const& b) {
return a.extra < b.extra;
return a.extra_ < b.extra_;
});
// We should never have two slabs of the same size
if (std::adjacent_find(
std::begin(cfg), std::end(cfg), [](SlabConfig const& a, SlabConfig const& b) {
return a.extra == b.extra;
return a.extra_ == b.extra_;
}) != cfg.end())
{
throw std::runtime_error(
"SlabAllocatorSet<" + beast::type_name<Type>() + ">: duplicate slab size");
"SlabAllocatorSet<" + beast::typeName<Type>() + ">: duplicate slab size");
}
for (auto const& c : cfg)
{
auto& a = allocators_.emplace_back(c.extra, c.alloc, c.align);
auto& a = allocators_.emplace_back(c.extra_, c.alloc_, c.align_);
if (a.size() > maxSize_)
maxSize_ = a.size();

View File

@@ -110,7 +110,7 @@ public:
/** Shrinks the slice by moving its start forward by n characters. */
void
remove_prefix(std::size_t n)
removePrefix(std::size_t n)
{
data_ += n;
size_ -= n;
@@ -118,7 +118,7 @@ public:
/** Shrinks the slice by moving its end backward by n characters. */
void
remove_suffix(std::size_t n)
removeSuffix(std::size_t n)
{
size_ -= n;
}

View File

@@ -30,7 +30,7 @@ template <class Iterator>
std::optional<Blob>
strUnHex(std::size_t strSize, Iterator begin, Iterator end)
{
static constexpr std::array<int, 256> const digitLookupTable = []() {
static constexpr std::array<int, 256> const kDIGIT_LOOKUP_TABLE = []() {
std::array<int, 256> t{};
for (auto& x : t)
@@ -56,7 +56,7 @@ strUnHex(std::size_t strSize, Iterator begin, Iterator end)
if (strSize & 1)
{
int c = digitLookupTable[*iter++];
int c = kDIGIT_LOOKUP_TABLE[*iter++];
if (c < 0)
return {};
@@ -66,12 +66,12 @@ strUnHex(std::size_t strSize, Iterator begin, Iterator end)
while (iter != end)
{
int const cHigh = digitLookupTable[*iter++];
int const cHigh = kDIGIT_LOOKUP_TABLE[*iter++];
if (cHigh < 0)
return {};
int const cLow = digitLookupTable[*iter++];
int const cLow = kDIGIT_LOOKUP_TABLE[*iter++];
if (cLow < 0)
return {};
@@ -94,9 +94,9 @@ strViewUnHex(std::string_view strSrc)
return strUnHex(strSrc.size(), strSrc.cbegin(), strSrc.cend());
}
struct parsedURL
struct ParsedUrl
{
explicit parsedURL() = default;
explicit ParsedUrl() = default;
std::string scheme;
std::string username;
@@ -106,7 +106,7 @@ struct parsedURL
std::string path;
bool
operator==(parsedURL const& other) const
operator==(ParsedUrl const& other) const
{
return scheme == other.scheme && domain == other.domain && port == other.port &&
path == other.path;
@@ -114,13 +114,13 @@ struct parsedURL
};
bool
parseUrl(parsedURL& pUrl, std::string const& strUrl);
parseUrl(ParsedUrl& pUrl, std::string const& strUrl);
std::string
trim_whitespace(std::string str);
trimWhitespace(std::string str);
std::optional<std::uint64_t>
to_uint64(std::string const& s);
toUint64(std::string const& s);
/** Determines if the given string looks like a TOML-file hosting domain.

View File

@@ -35,7 +35,7 @@ template <
bool IsKeyCache = false,
class SharedWeakUnionPointerType = SharedWeakCachePointer<T>,
class SharedPointerType = std::shared_ptr<T>,
class Hash = hardened_hash<>,
class Hash = HardenedHash<>,
class KeyEqual = std::equal_to<Key>,
class Mutex = std::recursive_mutex>
class TaggedCache
@@ -44,7 +44,7 @@ public:
using mutex_type = Mutex;
using key_type = Key;
using mapped_type = T;
using clock_type = beast::abstract_clock<std::chrono::steady_clock>;
using clock_type = beast::AbstractClock<std::chrono::steady_clock>;
using shared_weak_combo_pointer_type = SharedWeakUnionPointerType;
using shared_pointer_type = SharedPointerType;
@@ -55,7 +55,7 @@ public:
clock_type::duration expiration,
clock_type& clock,
beast::Journal journal,
beast::insight::Collector::ptr const& collector = beast::insight::NullCollector::New());
beast::insight::Collector::ptr const& collector = beast::insight::NullCollector::make());
public:
/** Return the clock associated with the cache. */
@@ -86,7 +86,7 @@ public:
*/
template <class KeyComparable>
bool
touch_if_exists(KeyComparable const& key);
touchIfExists(KeyComparable const& key);
using SweptPointersVector = std::vector<SharedWeakUnionPointerType>;
@@ -115,10 +115,10 @@ public:
canonicalize(key_type const& key, SharedPointerType& data, R&& replaceCallback);
bool
canonicalize_replace_cache(key_type const& key, SharedPointerType const& data);
canonicalizeReplaceCache(key_type const& key, SharedPointerType const& data);
bool
canonicalize_replace_client(key_type const& key, SharedPointerType& data);
canonicalizeReplaceClient(key_type const& key, SharedPointerType& data);
SharedPointerType
fetch(key_type const& key);
@@ -166,10 +166,10 @@ public:
private:
SharedPointerType
initialFetch(key_type const& key, std::lock_guard<mutex_type> const& l);
initialFetch(key_type const& key, std::scoped_lock<mutex_type> const& l);
void
collect_metrics();
collectMetrics();
private:
struct Stats
@@ -179,9 +179,9 @@ private:
std::string const& prefix,
Handler const& handler,
beast::insight::Collector::ptr const& collector)
: hook(collector->make_hook(handler))
, size(collector->make_gauge(prefix, "size"))
, hit_rate(collector->make_gauge(prefix, "hit_rate"))
: hook(collector->makeHook(handler))
, size(collector->makeGauge(prefix, "size"))
, hit_rate(collector->makeGauge(prefix, "hit_rate"))
{
}
@@ -199,8 +199,7 @@ private:
public:
clock_type::time_point last_access;
explicit KeyOnlyEntry(clock_type::time_point const& last_access_)
: last_access(last_access_)
explicit KeyOnlyEntry(clock_type::time_point const& lastAccess) : last_access(lastAccess)
{
}
@@ -217,8 +216,8 @@ private:
shared_weak_combo_pointer_type ptr;
clock_type::time_point last_access;
ValueEntry(clock_type::time_point const& last_access_, shared_pointer_type const& ptr_)
: ptr(ptr_), last_access(last_access_)
ValueEntry(clock_type::time_point const& lastAccess, shared_pointer_type const& ptr)
: ptr(ptr), last_access(lastAccess)
{
}
@@ -261,42 +260,42 @@ private:
[[nodiscard]] std::thread
sweepHelper(
clock_type::time_point const& when_expire,
clock_type::time_point const& whenExpire,
[[maybe_unused]] clock_type::time_point const& now,
typename KeyValueCacheType::map_type& partition,
SweptPointersVector& stuffToSweep,
std::atomic<int>& allRemovals,
std::lock_guard<std::recursive_mutex> const&);
std::scoped_lock<std::recursive_mutex> const&);
[[nodiscard]] std::thread
sweepHelper(
clock_type::time_point const& when_expire,
clock_type::time_point const& whenExpire,
clock_type::time_point const& now,
typename KeyOnlyCacheType::map_type& partition,
SweptPointersVector&,
std::atomic<int>& allRemovals,
std::lock_guard<std::recursive_mutex> const&);
std::scoped_lock<std::recursive_mutex> const&);
beast::Journal m_journal;
clock_type& m_clock;
Stats m_stats;
beast::Journal journal_;
clock_type& clock_;
Stats stats_;
mutex_type mutable m_mutex;
mutex_type mutable mutex_;
// Used for logging
std::string m_name;
std::string name_;
// Desired number of cache entries (0 = ignore)
int const m_target_size;
int const target_size_;
// Desired maximum cache age
clock_type::duration const m_target_age;
clock_type::duration const target_age_;
// Number of items cached
int m_cache_count{0};
cache_type m_cache; // Hold strong reference to recent objects
std::uint64_t m_hits{0};
std::uint64_t m_misses{0};
int cache_count_{0};
cache_type cache_; // Hold strong reference to recent objects
std::uint64_t hits_{0};
std::uint64_t misses_{0};
};
} // namespace xrpl

View File

@@ -30,13 +30,12 @@ inline TaggedCache<
clock_type& clock,
beast::Journal journal,
beast::insight::Collector::ptr const& collector)
: m_journal(journal)
, m_clock(clock)
, m_stats(name, std::bind(&TaggedCache::collect_metrics, this), collector)
, m_name(name)
, m_target_size(size)
, m_target_age(expiration)
: journal_(journal)
, clock_(clock)
, stats_(name, std::bind(&TaggedCache::collectMetrics, this), collector)
, name_(name)
, target_size_(size)
, target_age_(expiration)
{
}
@@ -53,7 +52,7 @@ inline auto
TaggedCache<Key, T, IsKeyCache, SharedWeakUnionPointer, SharedPointerType, Hash, KeyEqual, Mutex>::
clock() -> clock_type&
{
return m_clock;
return clock_;
}
template <
@@ -69,8 +68,8 @@ inline std::size_t
TaggedCache<Key, T, IsKeyCache, SharedWeakUnionPointer, SharedPointerType, Hash, KeyEqual, Mutex>::
size() const
{
std::lock_guard lock(m_mutex);
return m_cache.size();
std::scoped_lock const lock(mutex_);
return cache_.size();
}
template <
@@ -86,8 +85,8 @@ inline int
TaggedCache<Key, T, IsKeyCache, SharedWeakUnionPointer, SharedPointerType, Hash, KeyEqual, Mutex>::
getCacheSize() const
{
std::lock_guard lock(m_mutex);
return m_cache_count;
std::scoped_lock const lock(mutex_);
return cache_count_;
}
template <
@@ -103,8 +102,8 @@ inline int
TaggedCache<Key, T, IsKeyCache, SharedWeakUnionPointer, SharedPointerType, Hash, KeyEqual, Mutex>::
getTrackSize() const
{
std::lock_guard lock(m_mutex);
return m_cache.size();
std::scoped_lock const lock(mutex_);
return cache_.size();
}
template <
@@ -120,9 +119,9 @@ inline float
TaggedCache<Key, T, IsKeyCache, SharedWeakUnionPointer, SharedPointerType, Hash, KeyEqual, Mutex>::
getHitRate()
{
std::lock_guard lock(m_mutex);
auto const total = static_cast<float>(m_hits + m_misses);
return m_hits * (100.0f / std::max(1.0f, total));
std::scoped_lock const lock(mutex_);
auto const total = static_cast<float>(hits_ + misses_);
return hits_ * (100.0f / std::max(1.0f, total));
}
template <
@@ -138,9 +137,9 @@ inline void
TaggedCache<Key, T, IsKeyCache, SharedWeakUnionPointer, SharedPointerType, Hash, KeyEqual, Mutex>::
clear()
{
std::lock_guard lock(m_mutex);
m_cache.clear();
m_cache_count = 0;
std::scoped_lock const lock(mutex_);
cache_.clear();
cache_count_ = 0;
}
template <
@@ -156,11 +155,11 @@ inline void
TaggedCache<Key, T, IsKeyCache, SharedWeakUnionPointer, SharedPointerType, Hash, KeyEqual, Mutex>::
reset()
{
std::lock_guard lock(m_mutex);
m_cache.clear();
m_cache_count = 0;
m_hits = 0;
m_misses = 0;
std::scoped_lock const lock(mutex_);
cache_.clear();
cache_count_ = 0;
hits_ = 0;
misses_ = 0;
}
template <
@@ -175,17 +174,17 @@ template <
template <class KeyComparable>
inline bool
TaggedCache<Key, T, IsKeyCache, SharedWeakUnionPointer, SharedPointerType, Hash, KeyEqual, Mutex>::
touch_if_exists(KeyComparable const& key)
touchIfExists(KeyComparable const& key)
{
std::lock_guard lock(m_mutex);
auto const iter(m_cache.find(key));
if (iter == m_cache.end())
std::scoped_lock const lock(mutex_);
auto const iter(cache_.find(key));
if (iter == cache_.end())
{
++m_stats.misses;
++stats_.misses;
return false;
}
iter->second.touch(m_clock.now());
++m_stats.hits;
iter->second.touch(clock_.now());
++stats_.hits;
return true;
}
@@ -205,53 +204,53 @@ TaggedCache<Key, T, IsKeyCache, SharedWeakUnionPointer, SharedPointerType, Hash,
// Keep references to all the stuff we sweep
// For performance, each worker thread should exit before the swept data
// is destroyed but still within the main cache lock.
std::vector<SweptPointersVector> allStuffToSweep(m_cache.partitions());
std::vector<SweptPointersVector> allStuffToSweep(cache_.partitions());
clock_type::time_point const now(m_clock.now());
clock_type::time_point when_expire;
clock_type::time_point const now(clock_.now());
clock_type::time_point whenExpire;
auto const start = std::chrono::steady_clock::now();
{
std::lock_guard lock(m_mutex);
std::scoped_lock const lock(mutex_);
if (m_target_size == 0 || (static_cast<int>(m_cache.size()) <= m_target_size))
if (target_size_ == 0 || (static_cast<int>(cache_.size()) <= target_size_))
{
when_expire = now - m_target_age;
whenExpire = now - target_age_;
}
else
{
when_expire = now - m_target_age * m_target_size / m_cache.size();
whenExpire = now - (target_age_ * target_size_ / cache_.size());
clock_type::duration const minimumAge(std::chrono::seconds(1));
if (when_expire > (now - minimumAge))
when_expire = now - minimumAge;
if (whenExpire > (now - minimumAge))
whenExpire = now - minimumAge;
JLOG(m_journal.trace())
<< m_name << " is growing fast " << m_cache.size() << " of " << m_target_size
<< " aging at " << (now - when_expire).count() << " of " << m_target_age.count();
JLOG(journal_.trace())
<< name_ << " is growing fast " << cache_.size() << " of " << target_size_
<< " aging at " << (now - whenExpire).count() << " of " << target_age_.count();
}
std::vector<std::thread> workers;
workers.reserve(m_cache.partitions());
workers.reserve(cache_.partitions());
std::atomic<int> allRemovals = 0;
for (std::size_t p = 0; p < m_cache.partitions(); ++p)
for (std::size_t p = 0; p < cache_.partitions(); ++p)
{
workers.push_back(sweepHelper(
when_expire, now, m_cache.map()[p], allStuffToSweep[p], allRemovals, lock));
whenExpire, now, cache_.map()[p], allStuffToSweep[p], allRemovals, lock));
}
for (std::thread& worker : workers)
worker.join();
m_cache_count -= allRemovals;
cache_count_ -= allRemovals;
}
// At this point allStuffToSweep will go out of scope outside the lock
// and decrement the reference count on each strong pointer.
JLOG(m_journal.debug()) << m_name << " TaggedCache sweep lock duration "
<< std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now() - start)
.count()
<< "ms";
JLOG(journal_.debug()) << name_ << " TaggedCache sweep lock duration "
<< std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now() - start)
.count()
<< "ms";
}
template <
@@ -267,13 +266,12 @@ inline bool
TaggedCache<Key, T, IsKeyCache, SharedWeakUnionPointer, SharedPointerType, Hash, KeyEqual, Mutex>::
del(key_type const& key, bool valid)
{
// Remove from cache, if !valid, remove from map too. Returns true if
// removed from cache
std::lock_guard lock(m_mutex);
// Remove from cache, if !valid, remove from map too. Returns true if removed from cache
std::scoped_lock const lock(mutex_);
auto cit = m_cache.find(key);
auto cit = cache_.find(key);
if (cit == m_cache.end())
if (cit == cache_.end())
return false;
Entry& entry = cit->second;
@@ -282,13 +280,13 @@ TaggedCache<Key, T, IsKeyCache, SharedWeakUnionPointer, SharedPointerType, Hash,
if (entry.isCached())
{
--m_cache_count;
--cache_count_;
entry.ptr.convertToWeak();
ret = true;
}
if (!valid || entry.isExpired())
m_cache.erase(cit);
cache_.erase(cit);
return ret;
}
@@ -309,22 +307,22 @@ TaggedCache<Key, T, IsKeyCache, SharedWeakUnionPointer, SharedPointerType, Hash,
{
// Return canonical value, store if needed, refresh in cache
// Return values: true=we had the data already
std::lock_guard lock(m_mutex);
std::scoped_lock const lock(mutex_);
auto cit = m_cache.find(key);
auto cit = cache_.find(key);
if (cit == m_cache.end())
if (cit == cache_.end())
{
m_cache.emplace(
cache_.emplace(
std::piecewise_construct,
std::forward_as_tuple(key),
std::forward_as_tuple(m_clock.now(), data));
++m_cache_count;
std::forward_as_tuple(clock_.now(), data));
++cache_count_;
return false;
}
Entry& entry = cit->second;
entry.touch(m_clock.now());
entry.touch(clock_.now());
auto shouldReplace = [&] {
if constexpr (std::is_invocable_r_v<bool, R>)
@@ -368,12 +366,12 @@ TaggedCache<Key, T, IsKeyCache, SharedWeakUnionPointer, SharedPointerType, Hash,
data = cachedData;
}
++m_cache_count;
++cache_count_;
return true;
}
entry.ptr = data;
++m_cache_count;
++cache_count_;
return false;
}
@@ -389,7 +387,7 @@ template <
class Mutex>
inline bool
TaggedCache<Key, T, IsKeyCache, SharedWeakUnionPointer, SharedPointerType, Hash, KeyEqual, Mutex>::
canonicalize_replace_cache(key_type const& key, SharedPointerType const& data)
canonicalizeReplaceCache(key_type const& key, SharedPointerType const& data)
{
return canonicalize(key, const_cast<SharedPointerType&>(data), []() { return true; });
}
@@ -405,7 +403,7 @@ template <
class Mutex>
inline bool
TaggedCache<Key, T, IsKeyCache, SharedWeakUnionPointer, SharedPointerType, Hash, KeyEqual, Mutex>::
canonicalize_replace_client(key_type const& key, SharedPointerType& data)
canonicalizeReplaceClient(key_type const& key, SharedPointerType& data)
{
return canonicalize(key, data, []() { return false; });
}
@@ -423,10 +421,10 @@ inline SharedPointerType
TaggedCache<Key, T, IsKeyCache, SharedWeakUnionPointer, SharedPointerType, Hash, KeyEqual, Mutex>::
fetch(key_type const& key)
{
std::lock_guard<mutex_type> l(m_mutex);
std::scoped_lock<mutex_type> const l(mutex_);
auto ret = initialFetch(key, l);
if (!ret)
++m_misses;
++misses_;
return ret;
}
@@ -451,12 +449,12 @@ TaggedCache<Key, T, IsKeyCache, SharedWeakUnionPointer, SharedPointerType, Hash,
if constexpr (std::is_same_v<std::shared_ptr<T>, SharedPointerType>)
{
auto p = std::make_shared<T>(std::cref(value));
return canonicalize_replace_client(key, p);
return canonicalizeReplaceClient(key, p);
}
if constexpr (std::is_same_v<intr_ptr::SharedPtr<T>, SharedPointerType>)
{
auto p = intr_ptr::make_shared<T>(std::cref(value));
return canonicalize_replace_client(key, p);
auto p = intr_ptr::makeShared<T>(std::cref(value));
return canonicalizeReplaceClient(key, p);
}
}
@@ -474,9 +472,9 @@ inline auto
TaggedCache<Key, T, IsKeyCache, SharedWeakUnionPointer, SharedPointerType, Hash, KeyEqual, Mutex>::
insert(key_type const& key) -> std::enable_if_t<IsKeyCache, ReturnType>
{
std::lock_guard lock(m_mutex);
clock_type::time_point const now(m_clock.now());
auto [it, inserted] = m_cache.emplace(
std::scoped_lock const lock(mutex_);
clock_type::time_point const now(clock_.now());
auto [it, inserted] = cache_.emplace(
std::piecewise_construct, std::forward_as_tuple(key), std::forward_as_tuple(now));
if (!inserted)
it->second.last_access = now;
@@ -519,7 +517,7 @@ inline auto
TaggedCache<Key, T, IsKeyCache, SharedWeakUnionPointer, SharedPointerType, Hash, KeyEqual, Mutex>::
peekMutex() -> mutex_type&
{
return m_mutex;
return mutex_;
}
template <
@@ -538,9 +536,9 @@ TaggedCache<Key, T, IsKeyCache, SharedWeakUnionPointer, SharedPointerType, Hash,
std::vector<key_type> v;
{
std::lock_guard lock(m_mutex);
v.reserve(m_cache.size());
for (auto const& _ : m_cache)
std::scoped_lock const lock(mutex_);
v.reserve(cache_.size());
for (auto const& _ : cache_)
v.push_back(_.first);
}
@@ -560,11 +558,11 @@ inline double
TaggedCache<Key, T, IsKeyCache, SharedWeakUnionPointer, SharedPointerType, Hash, KeyEqual, Mutex>::
rate() const
{
std::lock_guard lock(m_mutex);
auto const tot = m_hits + m_misses;
std::scoped_lock const lock(mutex_);
auto const tot = hits_ + misses_;
if (tot == 0)
return 0;
return double(m_hits) / tot;
return double(hits_) / tot;
}
template <
@@ -582,7 +580,7 @@ TaggedCache<Key, T, IsKeyCache, SharedWeakUnionPointer, SharedPointerType, Hash,
fetch(key_type const& digest, Handler const& h)
{
{
std::lock_guard l(m_mutex);
std::scoped_lock const l(mutex_);
if (auto ret = initialFetch(digest, l))
return ret;
}
@@ -591,11 +589,11 @@ TaggedCache<Key, T, IsKeyCache, SharedWeakUnionPointer, SharedPointerType, Hash,
if (!sle)
return {};
std::lock_guard l(m_mutex);
++m_misses;
auto const [it, inserted] = m_cache.emplace(digest, Entry(m_clock.now(), std::move(sle)));
std::scoped_lock const l(mutex_);
++misses_;
auto const [it, inserted] = cache_.emplace(digest, Entry(clock_.now(), std::move(sle)));
if (!inserted)
it->second.touch(m_clock.now());
it->second.touch(clock_.now());
return it->second.ptr.getStrong();
}
// End CachedSLEs functions.
@@ -611,29 +609,29 @@ template <
class Mutex>
inline SharedPointerType
TaggedCache<Key, T, IsKeyCache, SharedWeakUnionPointer, SharedPointerType, Hash, KeyEqual, Mutex>::
initialFetch(key_type const& key, std::lock_guard<mutex_type> const& l)
initialFetch(key_type const& key, std::scoped_lock<mutex_type> const& l)
{
auto cit = m_cache.find(key);
if (cit == m_cache.end())
auto cit = cache_.find(key);
if (cit == cache_.end())
return {};
Entry& entry = cit->second;
if (entry.isCached())
{
++m_hits;
entry.touch(m_clock.now());
++hits_;
entry.touch(clock_.now());
return entry.ptr.getStrong();
}
entry.ptr = entry.lock();
if (entry.isCached())
{
// independent of cache size, so not counted as a hit
++m_cache_count;
entry.touch(m_clock.now());
++cache_count_;
entry.touch(clock_.now());
return entry.ptr.getStrong();
}
m_cache.erase(cit);
cache_.erase(cit);
return {};
}
@@ -648,19 +646,19 @@ template <
class Mutex>
inline void
TaggedCache<Key, T, IsKeyCache, SharedWeakUnionPointer, SharedPointerType, Hash, KeyEqual, Mutex>::
collect_metrics()
collectMetrics()
{
m_stats.size.set(getCacheSize());
stats_.size.set(getCacheSize());
{
beast::insight::Gauge::value_type hit_rate(0);
beast::insight::Gauge::value_type hitRate(0);
{
std::lock_guard lock(m_mutex);
auto const total(m_hits + m_misses);
std::scoped_lock const lock(mutex_);
auto const total(hits_ + misses_);
if (total != 0)
hit_rate = (m_hits * 100) / total;
hitRate = (hits_ * 100) / total;
}
m_stats.hit_rate.set(hit_rate);
stats_.hit_rate.set(hitRate);
}
}
@@ -676,12 +674,12 @@ template <
inline std::thread
TaggedCache<Key, T, IsKeyCache, SharedWeakUnionPointer, SharedPointerType, Hash, KeyEqual, Mutex>::
sweepHelper(
clock_type::time_point const& when_expire,
clock_type::time_point const& whenExpire,
[[maybe_unused]] clock_type::time_point const& now,
typename KeyValueCacheType::map_type& partition,
SweptPointersVector& stuffToSweep,
std::atomic<int>& allRemovals,
std::lock_guard<std::recursive_mutex> const&)
std::scoped_lock<std::recursive_mutex> const&)
{
return std::thread([&, this]() {
int cacheRemovals = 0;
@@ -708,11 +706,11 @@ TaggedCache<Key, T, IsKeyCache, SharedWeakUnionPointer, SharedPointerType, Hash,
++cit;
}
}
else if (cit->second.last_access <= when_expire)
else if (cit->second.last_access <= whenExpire)
{
// strong, expired
++cacheRemovals;
if (cit->second.ptr.use_count() == 1)
if (cit->second.ptr.useCount() == 1)
{
stuffToSweep.emplace_back(std::move(cit->second.ptr));
++mapRemovals;
@@ -735,8 +733,8 @@ TaggedCache<Key, T, IsKeyCache, SharedWeakUnionPointer, SharedPointerType, Hash,
if (mapRemovals || cacheRemovals)
{
JLOG(m_journal.debug())
<< "TaggedCache partition sweep " << m_name << ": cache = " << partition.size()
JLOG(journal_.debug())
<< "TaggedCache partition sweep " << name_ << ": cache = " << partition.size()
<< "-" << cacheRemovals << ", map-=" << mapRemovals;
}
@@ -756,16 +754,18 @@ template <
inline std::thread
TaggedCache<Key, T, IsKeyCache, SharedWeakUnionPointer, SharedPointerType, Hash, KeyEqual, Mutex>::
sweepHelper(
clock_type::time_point const& when_expire,
clock_type::time_point const& whenExpire,
clock_type::time_point const& now,
typename KeyOnlyCacheType::map_type& partition,
SweptPointersVector&,
std::atomic<int>& allRemovals,
std::lock_guard<std::recursive_mutex> const&)
std::scoped_lock<std::recursive_mutex> const&)
{
return std::thread([&, this]() {
// NOLINTBEGIN https://github.com/XRPLF/rippled/issues/7056
int cacheRemovals = 0;
int mapRemovals = 0;
// NOLINTEND
// Keep references to all the stuff we sweep
// so that we can destroy them outside the lock.
@@ -778,7 +778,7 @@ TaggedCache<Key, T, IsKeyCache, SharedWeakUnionPointer, SharedPointerType, Hash,
cit->second.last_access = now;
++cit;
}
else if (cit->second.last_access <= when_expire)
else if (cit->second.last_access <= whenExpire)
{
cit = partition.erase(cit);
}
@@ -789,10 +789,10 @@ TaggedCache<Key, T, IsKeyCache, SharedWeakUnionPointer, SharedPointerType, Hash,
}
}
if (mapRemovals || cacheRemovals)
if (mapRemovals > 0 || cacheRemovals > 0)
{
JLOG(m_journal.debug())
<< "TaggedCache partition sweep " << m_name << ": cache = " << partition.size()
JLOG(journal_.debug())
<< "TaggedCache partition sweep " << name_ << ": cache = " << partition.size()
<< "-" << cacheRemovals << ", map-=" << mapRemovals;
}

View File

@@ -13,31 +13,31 @@ namespace xrpl {
template <class T>
std::enable_if_t<std::is_arithmetic_v<T>, std::string>
to_string(T t)
to_string(T t) // NOLINT(readability-identifier-naming)
{
return std::to_string(t);
}
inline std::string
to_string(bool b)
to_string(bool b) // NOLINT(readability-identifier-naming)
{
return b ? "true" : "false";
}
inline std::string
to_string(char c)
to_string(char c) // NOLINT(readability-identifier-naming)
{
return std::string(1, c);
}
inline std::string
to_string(std::string s)
to_string(std::string s) // NOLINT(readability-identifier-naming)
{
return s;
}
inline std::string
to_string(char const* s)
to_string(char const* s) // NOLINT(readability-identifier-naming)
{
return s;
}

View File

@@ -28,7 +28,7 @@ namespace xrpl {
template <
class Key,
class Value,
class Hash = beast::uhash<>,
class Hash = beast::Uhash<>,
class Pred = std::equal_to<Key>,
class Allocator = std::allocator<std::pair<Key const, Value>>>
using hash_map = std::unordered_map<Key, Value, Hash, Pred, Allocator>;
@@ -36,33 +36,33 @@ using hash_map = std::unordered_map<Key, Value, Hash, Pred, Allocator>;
template <
class Key,
class Value,
class Hash = beast::uhash<>,
class Hash = beast::Uhash<>,
class Pred = std::equal_to<Key>,
class Allocator = std::allocator<std::pair<Key const, Value>>>
using hash_multimap = std::unordered_multimap<Key, Value, Hash, Pred, Allocator>;
template <
class Value,
class Hash = beast::uhash<>,
class Hash = beast::Uhash<>,
class Pred = std::equal_to<Value>,
class Allocator = std::allocator<Value>>
using hash_set = std::unordered_set<Value, Hash, Pred, Allocator>;
template <
class Value,
class Hash = beast::uhash<>,
class Hash = beast::Uhash<>,
class Pred = std::equal_to<Value>,
class Allocator = std::allocator<Value>>
using hash_multiset = std::unordered_multiset<Value, Hash, Pred, Allocator>;
// hardened_hash containers
using strong_hash = beast::xxhasher;
using strong_hash = beast::Xxhasher;
template <
class Key,
class Value,
class Hash = hardened_hash<strong_hash>,
class Hash = HardenedHash<strong_hash>,
class Pred = std::equal_to<Key>,
class Allocator = std::allocator<std::pair<Key const, Value>>>
using hardened_hash_map = std::unordered_map<Key, Value, Hash, Pred, Allocator>;
@@ -70,29 +70,29 @@ using hardened_hash_map = std::unordered_map<Key, Value, Hash, Pred, Allocator>;
template <
class Key,
class Value,
class Hash = hardened_hash<strong_hash>,
class Hash = HardenedHash<strong_hash>,
class Pred = std::equal_to<Key>,
class Allocator = std::allocator<std::pair<Key const, Value>>>
using hardened_partitioned_hash_map = partitioned_unordered_map<Key, Value, Hash, Pred, Allocator>;
using hardened_partitioned_hash_map = PartitionedUnorderedMap<Key, Value, Hash, Pred, Allocator>;
template <
class Key,
class Value,
class Hash = hardened_hash<strong_hash>,
class Hash = HardenedHash<strong_hash>,
class Pred = std::equal_to<Key>,
class Allocator = std::allocator<std::pair<Key const, Value>>>
using hardened_hash_multimap = std::unordered_multimap<Key, Value, Hash, Pred, Allocator>;
template <
class Value,
class Hash = hardened_hash<strong_hash>,
class Hash = HardenedHash<strong_hash>,
class Pred = std::equal_to<Value>,
class Allocator = std::allocator<Value>>
using hardened_hash_set = std::unordered_set<Value, Hash, Pred, Allocator>;
template <
class Value,
class Hash = hardened_hash<strong_hash>,
class Hash = HardenedHash<strong_hash>,
class Pred = std::equal_to<Value>,
class Allocator = std::allocator<Value>>
using hardened_hash_multiset = std::unordered_multiset<Value, Hash, Pred, Allocator>;

View File

@@ -21,7 +21,8 @@ public:
using period = std::ratio<1>;
using duration = std::chrono::duration<rep, period>;
using time_point = std::chrono::time_point<UptimeClock>;
static constexpr bool is_steady = std::chrono::system_clock::is_steady;
static constexpr bool is_steady = // NOLINT(readability-identifier-naming)
std::chrono::system_clock::is_steady;
explicit UptimeClock() = default;
@@ -29,19 +30,19 @@ public:
now(); // seconds since xrpld program start
private:
static std::atomic<rep> now_;
static std::atomic<bool> stop_;
static std::atomic<rep> kNOW;
static std::atomic<bool> kSTOP;
struct update_thread : private std::thread
struct UpdateThread : private std::thread
{
~update_thread();
update_thread(update_thread&&) = default;
~UpdateThread();
UpdateThread(UpdateThread&&) = default;
using std::thread::thread;
};
static update_thread
start_clock();
static UpdateThread
startClock();
};
} // namespace xrpl

View File

@@ -13,7 +13,7 @@ namespace xrpl {
// Note: This algorithm is evolved from std::set_intersection.
template <class InputIter1, class InputIter2, class Action, class Comp>
void
generalized_set_intersection(
generalizedSetIntersection(
InputIter1 first1,
InputIter1 last1,
InputIter2 first2,
@@ -53,7 +53,7 @@ generalized_set_intersection(
// std::set_intersection.
template <class FwdIter1, class InputIter2, class Pred, class Comp>
FwdIter1
remove_if_intersect_or_match(
removeIfIntersectOrMatch(
FwdIter1 first1,
FwdIter1 last1,
InputIter2 first2,

View File

@@ -40,15 +40,15 @@
namespace xrpl {
std::string
base64_encode(std::uint8_t const* data, std::size_t len);
base64Encode(std::uint8_t const* data, std::size_t len);
inline std::string
base64_encode(std::string const& s)
base64Encode(std::string const& s)
{
return base64_encode(reinterpret_cast<std::uint8_t const*>(s.data()), s.size());
return base64Encode(reinterpret_cast<std::uint8_t const*>(s.data()), s.size());
}
std::string
base64_decode(std::string_view data);
base64Decode(std::string_view data);
} // namespace xrpl

View File

@@ -27,12 +27,12 @@ namespace xrpl {
namespace detail {
template <class Container, class = std::void_t<>>
struct is_contiguous_container : std::false_type
struct IsContiguousContainer : std::false_type
{
};
template <class Container>
struct is_contiguous_container<
struct IsContiguousContainer<
Container,
std::void_t<
decltype(std::declval<Container const>().size()),
@@ -42,7 +42,7 @@ struct is_contiguous_container<
};
template <>
struct is_contiguous_container<Slice> : std::true_type
struct IsContiguousContainer<Slice> : std::true_type
{
};
@@ -62,18 +62,18 @@ struct is_contiguous_container<Slice> : std::true_type
number of bits.
*/
template <std::size_t Bits, class Tag = void>
class base_uint
class BaseUint
{
static_assert((Bits % 32) == 0, "The length of a base_uint in bits must be a multiple of 32.");
static_assert(Bits >= 64, "The length of a base_uint in bits must be at least 64.");
static constexpr std::size_t WIDTH = Bits / 32;
static constexpr std::size_t kWIDTH = Bits / 32;
// This is really big-endian in byte order.
// We sometimes use std::uint32_t for speed.
std::array<std::uint32_t, WIDTH> data_;
std::array<std::uint32_t, kWIDTH> data_;
public:
//--------------------------------------------------------------------------
@@ -81,8 +81,8 @@ public:
// STL Container Interface
//
static std::size_t constexpr bytes = Bits / 8;
static_assert(sizeof(data_) == bytes, "");
static std::size_t constexpr kBYTES = Bits / 8;
static_assert(sizeof(data_) == kBYTES, "");
using size_type = std::size_t;
using difference_type = std::ptrdiff_t;
@@ -116,7 +116,7 @@ public:
iterator
end()
{
return data() + bytes;
return data() + kBYTES;
}
[[nodiscard]] const_iterator
begin() const
@@ -126,7 +126,7 @@ public:
[[nodiscard]] const_iterator
end() const
{
return data() + bytes;
return data() + kBYTES;
}
[[nodiscard]] const_iterator
cbegin() const
@@ -136,14 +136,14 @@ public:
[[nodiscard]] const_iterator
cend() const
{
return data() + bytes;
return data() + kBYTES;
}
/** Value hashing function.
The seed prevents crafted inputs from causing degenerate parent
containers.
*/
using hasher = hardened_hash<>;
using hasher = HardenedHash<>;
//--------------------------------------------------------------------------
@@ -160,16 +160,16 @@ private:
explicit VoidHelper() = default;
};
explicit base_uint(void const* data, VoidHelper)
explicit BaseUint(void const* data, VoidHelper)
{
memcpy(data_.data(), data, bytes);
memcpy(data_.data(), data, kBYTES);
}
// Helper function to initialize a base_uint from a std::string_view.
enum class ParseResult {
okay,
badLength,
badChar,
Okay,
BadLength,
BadChar,
};
constexpr Expected<decltype(data_), ParseResult>
@@ -180,7 +180,7 @@ private:
auto hexCharToUInt = [](char c, std::uint32_t shift, std::uint32_t& accum) -> ParseResult {
std::uint32_t nibble = 0xFFu;
if (c < '0' || c > 'f')
return ParseResult::badChar;
return ParseResult::BadChar;
if (c >= 'a')
{
@@ -196,11 +196,11 @@ private:
}
if (nibble > 0xFu)
return ParseResult::badChar;
return ParseResult::BadChar;
accum |= (nibble << shift);
return ParseResult::okay;
return ParseResult::Okay;
};
decltype(data_) ret{};
@@ -211,7 +211,7 @@ private:
}
if (sv.size() != size() * 2)
return Unexpected(ParseResult::badLength);
return Unexpected(ParseResult::BadLength);
std::size_t i = 0u;
auto in = sv.begin();
@@ -221,7 +221,7 @@ private:
for (std::uint32_t const shift : {4u, 0u, 12u, 8u, 20u, 16u, 28u, 24u})
{
if (auto const result = hexCharToUInt(*in++, shift, accum);
result != ParseResult::okay)
result != ParseResult::Okay)
return Unexpected(result);
}
ret[i++] = accum;
@@ -235,7 +235,7 @@ private:
auto const result = parseFromStringView(sv);
if (!result)
{
if (result.error() == ParseResult::badLength)
if (result.error() == ParseResult::BadLength)
Throw<std::invalid_argument>("invalid length for hex string");
Throw<std::range_error>("invalid hex character");
@@ -244,15 +244,15 @@ private:
}
public:
constexpr base_uint() : data_{}
constexpr BaseUint() : data_{}
{
}
constexpr base_uint(beast::Zero) : data_{}
constexpr BaseUint(beast::Zero) : data_{}
{
}
explicit base_uint(std::uint64_t b)
explicit BaseUint(std::uint64_t b)
{
*this = b;
}
@@ -260,7 +260,7 @@ public:
// This constructor is intended to be used at compile time since it might
// throw at runtime. Consider declaring this constructor consteval once
// we get to C++23.
explicit constexpr base_uint(std::string_view sv) noexcept(false)
explicit constexpr BaseUint(std::string_view sv) noexcept(false)
: data_(parseFromStringViewThrows(sv))
{
}
@@ -268,9 +268,9 @@ public:
template <
class Container,
class = std::enable_if_t<
detail::is_contiguous_container<Container>::value &&
detail::IsContiguousContainer<Container>::value &&
std::is_trivially_copyable_v<typename Container::value_type>>>
explicit base_uint(Container const& c)
explicit BaseUint(Container const& c)
{
XRPL_ASSERT(
c.size() * sizeof(typename Container::value_type) == size(),
@@ -280,9 +280,9 @@ public:
template <class Container>
std::enable_if_t<
detail::is_contiguous_container<Container>::value &&
detail::IsContiguousContainer<Container>::value &&
std::is_trivially_copyable_v<typename Container::value_type>,
base_uint&>
BaseUint&>
operator=(Container const& c)
{
XRPL_ASSERT(
@@ -295,14 +295,14 @@ public:
/* Construct from a raw pointer.
The buffer pointed to by `data` must be at least Bits/8 bytes.
*/
static base_uint
static BaseUint
fromVoid(void const* data)
{
return base_uint(data, VoidHelper());
return BaseUint(data, VoidHelper());
}
template <class T>
static std::optional<base_uint>
static std::optional<BaseUint>
fromVoidChecked(T const& from)
{
if (from.size() != size())
@@ -313,7 +313,7 @@ public:
[[nodiscard]] constexpr int
signum() const
{
for (int i = 0; i < WIDTH; i++)
for (int i = 0; i < kWIDTH; i++)
{
if (data_[i] != 0)
return 1;
@@ -325,24 +325,24 @@ public:
bool
operator!() const
{
return *this == beast::zero;
return *this == beast::kZERO;
}
constexpr base_uint
constexpr BaseUint
operator~() const
{
base_uint ret;
BaseUint ret;
for (int i = 0; i < WIDTH; i++)
for (int i = 0; i < kWIDTH; i++)
ret.data_[i] = ~data_[i];
return ret;
}
base_uint&
BaseUint&
operator=(std::uint64_t uHost)
{
*this = beast::zero;
*this = beast::kZERO;
// NOLINTBEGIN(cppcoreguidelines-pro-type-member-init)
union
{
@@ -352,43 +352,43 @@ public:
// NOLINTEND(cppcoreguidelines-pro-type-member-init)
// Put in least significant bits.
ul = boost::endian::native_to_big(uHost);
data_[WIDTH - 2] = u[0];
data_[WIDTH - 1] = u[1];
data_[kWIDTH - 2] = u[0];
data_[kWIDTH - 1] = u[1];
return *this;
}
base_uint&
operator^=(base_uint const& b)
BaseUint&
operator^=(BaseUint const& b)
{
for (int i = 0; i < WIDTH; i++)
for (int i = 0; i < kWIDTH; i++)
data_[i] ^= b.data_[i];
return *this;
}
base_uint&
operator&=(base_uint const& b)
BaseUint&
operator&=(BaseUint const& b)
{
for (int i = 0; i < WIDTH; i++)
for (int i = 0; i < kWIDTH; i++)
data_[i] &= b.data_[i];
return *this;
}
base_uint&
operator|=(base_uint const& b)
BaseUint&
operator|=(BaseUint const& b)
{
for (int i = 0; i < WIDTH; i++)
for (int i = 0; i < kWIDTH; i++)
data_[i] |= b.data_[i];
return *this;
}
base_uint&
BaseUint&
operator++()
{
// prefix operator
for (int i = WIDTH - 1; i >= 0; --i)
for (int i = kWIDTH - 1; i >= 0; --i)
{
data_[i] = boost::endian::native_to_big(boost::endian::big_to_native(data_[i]) + 1);
if (data_[i] != 0)
@@ -398,20 +398,20 @@ public:
return *this;
}
base_uint
BaseUint
operator++(int)
{
// postfix operator
base_uint const ret = *this;
BaseUint const ret = *this;
++(*this);
return ret;
}
base_uint&
BaseUint&
operator--()
{
for (int i = WIDTH - 1; i >= 0; --i)
for (int i = kWIDTH - 1; i >= 0; --i)
{
auto prev = data_[i];
data_[i] = boost::endian::native_to_big(boost::endian::big_to_native(data_[i]) - 1);
@@ -423,36 +423,36 @@ public:
return *this;
}
base_uint
BaseUint
operator--(int)
{
// postfix operator
base_uint const ret = *this;
BaseUint const ret = *this;
--(*this);
return ret;
}
[[nodiscard]] base_uint
[[nodiscard]] BaseUint
next() const
{
auto ret = *this;
return ++ret;
}
[[nodiscard]] base_uint
[[nodiscard]] BaseUint
prev() const
{
auto ret = *this;
return --ret;
}
base_uint&
operator+=(base_uint const& b)
BaseUint&
operator+=(BaseUint const& b)
{
std::uint64_t carry = 0;
for (int i = WIDTH - 1; i >= 0; i--)
for (int i = kWIDTH - 1; i >= 0; i--)
{
std::uint64_t const n = carry + boost::endian::big_to_native(data_[i]) +
boost::endian::big_to_native(b.data_[i]);
@@ -466,7 +466,7 @@ public:
template <class Hasher>
friend void
hash_append(Hasher& h, base_uint const& a) noexcept
hash_append(Hasher& h, BaseUint const& a) noexcept
{
// Do not allow any endian transformations on this memory
h(a.data_.data(), sizeof(a.data_));
@@ -506,10 +506,10 @@ public:
constexpr static std::size_t
size()
{
return bytes;
return kBYTES;
}
base_uint<Bits, Tag>&
BaseUint<Bits, Tag>&
operator=(beast::Zero)
{
data_.fill(0);
@@ -520,28 +520,28 @@ public:
[[nodiscard]] bool
isZero() const
{
return *this == beast::zero;
return *this == beast::kZERO;
}
[[nodiscard]] bool
isNonZero() const
{
return *this != beast::zero;
return *this != beast::kZERO;
}
void
zero()
{
*this = beast::zero;
*this = beast::kZERO;
}
};
using uint128 = base_uint<128>;
using uint160 = base_uint<160>;
using uint256 = base_uint<256>;
using uint192 = base_uint<192>;
using uint128 = BaseUint<128>;
using uint160 = BaseUint<160>;
using uint256 = BaseUint<256>;
using uint192 = BaseUint<192>;
template <std::size_t Bits, class Tag>
[[nodiscard]] constexpr std::strong_ordering
operator<=>(base_uint<Bits, Tag> const& lhs, base_uint<Bits, Tag> const& rhs)
operator<=>(BaseUint<Bits, Tag> const& lhs, BaseUint<Bits, Tag> const& rhs)
{
// This comparison might seem wrong on a casual inspection because it
// compares data internally stored as std::uint32_t byte-by-byte. But
@@ -562,7 +562,7 @@ operator<=>(base_uint<Bits, Tag> const& lhs, base_uint<Bits, Tag> const& rhs)
template <std::size_t Bits, typename Tag>
[[nodiscard]] constexpr bool
operator==(base_uint<Bits, Tag> const& lhs, base_uint<Bits, Tag> const& rhs)
operator==(BaseUint<Bits, Tag> const& lhs, BaseUint<Bits, Tag> const& rhs)
{
return (lhs <=> rhs) == 0;
}
@@ -570,59 +570,59 @@ operator==(base_uint<Bits, Tag> const& lhs, base_uint<Bits, Tag> const& rhs)
//------------------------------------------------------------------------------
template <std::size_t Bits, class Tag>
constexpr bool
operator==(base_uint<Bits, Tag> const& a, std::uint64_t b)
operator==(BaseUint<Bits, Tag> const& a, std::uint64_t b)
{
return a == base_uint<Bits, Tag>(b);
return a == BaseUint<Bits, Tag>(b);
}
//------------------------------------------------------------------------------
template <std::size_t Bits, class Tag>
constexpr base_uint<Bits, Tag>
operator^(base_uint<Bits, Tag> const& a, base_uint<Bits, Tag> const& b)
constexpr BaseUint<Bits, Tag>
operator^(BaseUint<Bits, Tag> const& a, BaseUint<Bits, Tag> const& b)
{
return base_uint<Bits, Tag>(a) ^= b;
return BaseUint<Bits, Tag>(a) ^= b;
}
template <std::size_t Bits, class Tag>
constexpr base_uint<Bits, Tag>
operator&(base_uint<Bits, Tag> const& a, base_uint<Bits, Tag> const& b)
constexpr BaseUint<Bits, Tag>
operator&(BaseUint<Bits, Tag> const& a, BaseUint<Bits, Tag> const& b)
{
return base_uint<Bits, Tag>(a) &= b;
return BaseUint<Bits, Tag>(a) &= b;
}
template <std::size_t Bits, class Tag>
constexpr base_uint<Bits, Tag>
operator|(base_uint<Bits, Tag> const& a, base_uint<Bits, Tag> const& b)
constexpr BaseUint<Bits, Tag>
operator|(BaseUint<Bits, Tag> const& a, BaseUint<Bits, Tag> const& b)
{
return base_uint<Bits, Tag>(a) |= b;
return BaseUint<Bits, Tag>(a) |= b;
}
template <std::size_t Bits, class Tag>
constexpr base_uint<Bits, Tag>
operator+(base_uint<Bits, Tag> const& a, base_uint<Bits, Tag> const& b)
constexpr BaseUint<Bits, Tag>
operator+(BaseUint<Bits, Tag> const& a, BaseUint<Bits, Tag> const& b)
{
return base_uint<Bits, Tag>(a) += b;
return BaseUint<Bits, Tag>(a) += b;
}
//------------------------------------------------------------------------------
template <std::size_t Bits, class Tag>
inline std::string
to_string(base_uint<Bits, Tag> const& a)
to_string(BaseUint<Bits, Tag> const& a)
{
return strHex(a.cbegin(), a.cend());
}
template <std::size_t Bits, class Tag>
inline std::string
to_short_string(base_uint<Bits, Tag> const& a)
toShortString(BaseUint<Bits, Tag> const& a)
{
static_assert(base_uint<Bits, Tag>::bytes > 4, "For 4 bytes or less, use a native type");
static_assert(BaseUint<Bits, Tag>::kBYTES > 4, "For 4 bytes or less, use a native type");
return strHex(a.cbegin(), a.cbegin() + 4) + "...";
}
template <std::size_t Bits, class Tag>
inline std::ostream&
operator<<(std::ostream& out, base_uint<Bits, Tag> const& u)
operator<<(std::ostream& out, BaseUint<Bits, Tag> const& u)
{
return out << to_string(u);
}
@@ -650,9 +650,9 @@ static_assert(sizeof(uint256) == 256 / 8, "There should be no padding bytes");
namespace beast {
template <std::size_t Bits, class Tag>
struct is_uniquely_represented<xrpl::base_uint<Bits, Tag>> : public std::true_type
struct IsUniquelyRepresented<xrpl::BaseUint<Bits, Tag>> : public std::true_type
{
explicit is_uniquely_represented() = default;
explicit IsUniquelyRepresented() = default;
};
} // namespace beast

View File

@@ -30,10 +30,10 @@ using weeks = std::chrono::duration<int, std::ratio_multiply<days::period, std::
= seconds(946684800)
*/
constexpr static std::chrono::seconds epoch_offset =
constexpr static std::chrono::seconds kEPOCH_OFFSET =
date::sys_days{date::year{2000} / 1 / 1} - date::sys_days{date::year{1970} / 1 / 1};
static_assert(epoch_offset.count() == 946684800);
static_assert(kEPOCH_OFFSET.count() == 946684800);
class NetClock
{
@@ -45,7 +45,7 @@ public:
using duration = std::chrono::duration<rep, period>;
using time_point = std::chrono::time_point<NetClock>;
static bool const is_steady = false;
static bool const is_steady = false; // NOLINT(readability-identifier-naming)
};
template <class Duration>
@@ -60,42 +60,42 @@ to_string(NetClock::time_point tp)
{
// 2000-01-01 00:00:00 UTC is 946684800s from 1970-01-01 00:00:00 UTC
using namespace std::chrono;
return to_string(system_clock::time_point{tp.time_since_epoch() + epoch_offset});
return to_string(system_clock::time_point{tp.time_since_epoch() + kEPOCH_OFFSET});
}
template <class Duration>
std::string
to_string_iso(date::sys_time<Duration> tp)
toStringIso(date::sys_time<Duration> tp)
{
using namespace std::chrono;
return date::format("%FT%TZ", tp);
}
inline std::string
to_string_iso(NetClock::time_point tp)
toStringIso(NetClock::time_point tp)
{
// 2000-01-01 00:00:00 UTC is 946684800s from 1970-01-01 00:00:00 UTC
// Note, NetClock::duration is seconds, as checked by static_assert
static_assert(std::is_same_v<NetClock::duration::period, std::ratio<1>>);
return to_string_iso(date::sys_time<NetClock::duration>{tp.time_since_epoch() + epoch_offset});
return toStringIso(date::sys_time<NetClock::duration>{tp.time_since_epoch() + kEPOCH_OFFSET});
}
/** A clock for measuring elapsed time.
The epoch is unspecified.
*/
using Stopwatch = beast::abstract_clock<std::chrono::steady_clock>;
using Stopwatch = beast::AbstractClock<std::chrono::steady_clock>;
/** A manual Stopwatch for unit tests. */
using TestStopwatch = beast::manual_clock<std::chrono::steady_clock>;
using TestStopwatch = beast::ManualClock<std::chrono::steady_clock>;
/** Returns an instance of a wall clock. */
inline Stopwatch&
stopwatch()
{
using Clock = beast::basic_seconds_clock;
using Clock = beast::BasicSecondsClock;
using Facade = Clock::Clock;
return beast::get_abstract_clock<Facade, Clock>();
return beast::getAbstractClock<Facade, Clock>();
}
} // namespace xrpl

View File

@@ -17,7 +17,7 @@ namespace xrpl {
/** Generates and logs a call stack */
void
LogThrow(std::string const& title);
logThrow(std::string const& title);
/** Rethrow the exception currently being handled.
@@ -30,9 +30,9 @@ LogThrow(std::string const& title);
triggering false positives, since it throws.
*/
[[noreturn]] XRPL_NO_SANITIZE_ADDRESS inline void
Rethrow()
rethrow()
{
LogThrow("Re-throwing exception");
logThrow("Re-throwing exception");
throw;
}
@@ -52,12 +52,12 @@ Throw(Args&&... args)
std::is_convertible_v<E*, std::exception*>, "Exception must derive from std::exception.");
E e(std::forward<Args>(args)...);
LogThrow(std::string("Throwing exception of type " + beast::type_name<E>() + ": ") + e.what());
logThrow(std::string("Throwing exception of type " + beast::typeName<E>() + ": ") + e.what());
throw std::move(e);
}
/** Called when faulty logic causes a broken invariant. */
[[noreturn]] void
LogicError(std::string const& how) noexcept;
logicError(std::string const& how) noexcept;
} // namespace xrpl

View File

@@ -16,24 +16,24 @@ using seed_pair = std::pair<std::uint64_t, std::uint64_t>;
template <bool = true>
seed_pair
make_seed_pair() noexcept
makeSeedPair() noexcept
{
struct state_t
struct StateT
{
std::mutex mutex;
std::random_device rng;
std::mt19937_64 gen;
std::uniform_int_distribution<std::uint64_t> dist;
state_t() : gen(rng())
StateT() : gen(rng())
{
}
// state_t(state_t const&) = delete;
// state_t& operator=(state_t const&) = delete;
};
static state_t state;
std::lock_guard const lock(state.mutex);
return {state.dist(state.gen), state.dist(state.gen)};
static StateT kSTATE;
std::scoped_lock const lock(kSTATE.mutex);
return {kSTATE.dist(kSTATE.gen), kSTATE.dist(kSTATE.gen)};
}
} // namespace detail
@@ -68,22 +68,22 @@ make_seed_pair() noexcept
see https://131002.net/siphash/#at
*/
template <class HashAlgorithm = beast::xxhasher>
class hardened_hash
template <class HashAlgorithm = beast::Xxhasher>
class HardenedHash
{
private:
detail::seed_pair m_seeds{detail::make_seed_pair<>()};
detail::seed_pair seeds_{detail::makeSeedPair<>()};
public:
using result_type = typename HashAlgorithm::result_type;
hardened_hash() = default;
HardenedHash() = default;
template <class T>
result_type
operator()(T const& t) const noexcept
{
HashAlgorithm h(m_seeds.first, m_seeds.second);
HashAlgorithm h(seeds_.first, seeds_.second);
hash_append(h, t);
return static_cast<result_type>(h);
}

View File

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

View File

@@ -5,7 +5,7 @@
#include <optional>
namespace xrpl {
auto constexpr muldiv_max = std::numeric_limits<std::uint64_t>::max();
auto constexpr kMULDIV_MAX = std::numeric_limits<std::uint64_t>::max();
/** Return value*mul/div accurately.
Computes the result of the multiplication and division in

View File

@@ -24,7 +24,7 @@ template <>
inline std::size_t
extract(std::string const& key)
{
return ::beast::uhash<>{}(key);
return ::beast::Uhash<>{}(key);
}
template <
@@ -33,7 +33,7 @@ template <
typename Hash,
typename Pred = std::equal_to<Key>,
typename Alloc = std::allocator<std::pair<Key const, Value>>>
class partitioned_unordered_map
class PartitionedUnorderedMap
{
std::size_t partitions_;
@@ -53,46 +53,46 @@ public:
using map_type = std::unordered_map<key_type, mapped_type, hasher, key_equal, allocator_type>;
using partition_map_type = std::vector<map_type>;
struct iterator
struct Iterator
{
using iterator_category = std::forward_iterator_tag;
partition_map_type* map_{nullptr};
typename partition_map_type::iterator ait_{};
typename map_type::iterator mit_;
partition_map_type* map{nullptr};
typename partition_map_type::iterator ait{};
typename map_type::iterator mit;
iterator() = default;
Iterator() = default;
iterator(partition_map_type* map) : map_(map)
Iterator(partition_map_type* m) : map(m)
{
}
reference
operator*() const
{
return *mit_;
return *mit;
}
pointer
operator->() const
{
return &(*mit_);
return &(*mit);
}
void
inc()
{
++mit_;
while (mit_ == ait_->end())
++mit;
while (mit == ait->end())
{
++ait_;
if (ait_ == map_->end())
++ait;
if (ait == map->end())
return;
mit_ = ait_->begin();
mit = ait->begin();
}
}
// ++it
iterator&
Iterator&
operator++()
{
inc();
@@ -100,75 +100,75 @@ public:
}
// it++
iterator
Iterator
operator++(int)
{
iterator tmp(*this);
Iterator tmp(*this);
inc();
return tmp;
}
friend bool
operator==(iterator const& lhs, iterator const& rhs)
operator==(Iterator const& lhs, Iterator const& rhs)
{
return lhs.map_ == rhs.map_ && lhs.ait_ == rhs.ait_ && lhs.mit_ == rhs.mit_;
return lhs.map == rhs.map && lhs.ait == rhs.ait && lhs.mit == rhs.mit;
}
friend bool
operator!=(iterator const& lhs, iterator const& rhs)
operator!=(Iterator const& lhs, Iterator const& rhs)
{
return !(lhs == rhs);
}
};
struct const_iterator
struct ConstIterator
{
using iterator_category = std::forward_iterator_tag;
partition_map_type* map_{nullptr};
typename partition_map_type::iterator ait_{};
typename map_type::iterator mit_;
partition_map_type* map{nullptr};
typename partition_map_type::iterator ait{};
typename map_type::iterator mit;
const_iterator() = default;
ConstIterator() = default;
const_iterator(partition_map_type* map) : map_(map)
ConstIterator(partition_map_type* m) : map(m)
{
}
const_iterator(iterator const& orig)
ConstIterator(Iterator const& orig)
{
map_ = orig.map_;
ait_ = orig.ait_;
mit_ = orig.mit_;
map = orig.map;
ait = orig.ait;
mit = orig.mit;
}
const_reference
operator*() const
{
return *mit_;
return *mit;
}
const_pointer
operator->() const
{
return &(*mit_);
return &(*mit);
}
void
inc()
{
++mit_;
while (mit_ == ait_->end())
++mit;
while (mit == ait->end())
{
++ait_;
if (ait_ == map_->end())
++ait;
if (ait == map->end())
return;
mit_ = ait_->begin();
mit = ait->begin();
}
}
// ++it
const_iterator&
ConstIterator&
operator++()
{
inc();
@@ -176,22 +176,22 @@ public:
}
// it++
const_iterator
ConstIterator
operator++(int)
{
const_iterator tmp(*this);
ConstIterator tmp(*this);
inc();
return tmp;
}
friend bool
operator==(const_iterator const& lhs, const_iterator const& rhs)
operator==(ConstIterator const& lhs, ConstIterator const& rhs)
{
return lhs.map_ == rhs.map_ && lhs.ait_ == rhs.ait_ && lhs.mit_ == rhs.mit_;
return lhs.map == rhs.map && lhs.ait == rhs.ait && lhs.mit == rhs.mit;
}
friend bool
operator!=(const_iterator const& lhs, const_iterator const& rhs)
operator!=(ConstIterator const& lhs, ConstIterator const& rhs)
{
return !(lhs == rhs);
}
@@ -208,26 +208,26 @@ private:
static void
end(T& it)
{
it.ait_ = it.map_->end();
it.mit_ = it.map_->back().end();
it.ait = it.map->end();
it.mit = it.map->back().end();
}
template <class T>
static void
begin(T& it)
{
for (it.ait_ = it.map_->begin(); it.ait_ != it.map_->end(); ++it.ait_)
for (it.ait = it.map->begin(); it.ait != it.map->end(); ++it.ait)
{
if (it.ait_->begin() == it.ait_->end())
if (it.ait->begin() == it.ait->end())
continue;
it.mit_ = it.ait_->begin();
it.mit = it.ait->begin();
return;
}
end(it);
}
public:
partitioned_unordered_map(std::optional<std::size_t> partitions = std::nullopt)
PartitionedUnorderedMap(std::optional<std::size_t> partitions = std::nullopt)
{
// Set partitions to the number of hardware threads if the parameter
// is either empty or set to 0.
@@ -252,45 +252,45 @@ public:
return map_;
}
iterator
Iterator
begin()
{
iterator it(&map_);
Iterator it(&map_);
begin(it);
return it;
}
const_iterator
ConstIterator
cbegin() const
{
const_iterator it(&map_);
ConstIterator it(&map_);
begin(it);
return it;
}
const_iterator
ConstIterator
begin() const
{
return cbegin();
}
iterator
Iterator
end()
{
iterator it(&map_);
Iterator it(&map_);
end(it);
return it;
}
const_iterator
ConstIterator
cend() const
{
const_iterator it(&map_);
ConstIterator it(&map_);
end(it);
return it;
}
const_iterator
ConstIterator
end() const
{
return cend();
@@ -301,50 +301,50 @@ private:
void
find(key_type const& key, T& it) const
{
it.ait_ = it.map_->begin() + partitioner(key);
it.mit_ = it.ait_->find(key);
if (it.mit_ == it.ait_->end())
it.ait = it.map->begin() + partitioner(key);
it.mit = it.ait->find(key);
if (it.mit == it.ait->end())
end(it);
}
public:
iterator
Iterator
find(key_type const& key)
{
iterator it(&map_);
Iterator it(&map_);
find(key, it);
return it;
}
const_iterator
ConstIterator
find(key_type const& key) const
{
const_iterator it(&map_);
ConstIterator it(&map_);
find(key, it);
return it;
}
template <class T, class U>
std::pair<iterator, bool>
std::pair<Iterator, bool>
emplace(std::piecewise_construct_t const&, T&& keyTuple, U&& valueTuple)
{
auto const& key = std::get<0>(keyTuple);
iterator it(&map_);
it.ait_ = it.map_->begin() + partitioner(key);
auto [eit, inserted] = it.ait_->emplace(
Iterator it(&map_);
it.ait = it.map->begin() + partitioner(key);
auto [eit, inserted] = it.ait->emplace(
std::piecewise_construct, std::forward<T>(keyTuple), std::forward<U>(valueTuple));
it.mit_ = eit;
it.mit = eit;
return {it, inserted};
}
template <class T, class U>
std::pair<iterator, bool>
std::pair<Iterator, bool>
emplace(T&& key, U&& val)
{
iterator it(&map_);
it.ait_ = it.map_->begin() + partitioner(key);
auto [eit, inserted] = it.ait_->emplace(std::forward<T>(key), std::forward<U>(val));
it.mit_ = eit;
Iterator it(&map_);
it.ait = it.map->begin() + partitioner(key);
auto [eit, inserted] = it.ait->emplace(std::forward<T>(key), std::forward<U>(val));
it.mit = eit;
return {it, inserted};
}
@@ -355,19 +355,19 @@ public:
p.clear();
}
iterator
erase(const_iterator position)
Iterator
erase(ConstIterator position)
{
iterator it(&map_);
it.ait_ = position.ait_;
it.mit_ = position.ait_->erase(position.mit_);
Iterator it(&map_);
it.ait = position.ait;
it.mit = position.ait->erase(position.mit);
while (it.mit_ == it.ait_->end())
while (it.mit == it.ait->end())
{
++it.ait_;
if (it.ait_ == it.map_->end())
++it.ait;
if (it.ait == it.map->end())
break;
it.mit_ = it.ait_->begin();
it.mit = it.ait->begin();
}
return it;

View File

@@ -44,30 +44,30 @@ using is_engine = std::is_invocable_r<Result, Engine>;
will be randomly seeded.
*/
inline beast::xor_shift_engine&
default_prng()
defaultPrng()
{
// This is used to seed the thread-specific PRNGs on demand
static beast::xor_shift_engine seeder = [] {
static beast::xor_shift_engine kSEEDER = [] {
std::random_device rng;
std::uniform_int_distribution<std::uint64_t> distribution{1};
return beast::xor_shift_engine(distribution(rng));
}();
// This protects the seeder
static std::mutex m;
static std::mutex kM;
// The thread-specific PRNGs:
thread_local beast::xor_shift_engine engine = [] {
thread_local beast::xor_shift_engine kENGINE = [] {
std::uint64_t seed = 0;
{
std::lock_guard const lk(m);
std::scoped_lock const lk(kM);
std::uniform_int_distribution<std::uint64_t> distribution{1};
seed = distribution(seeder);
seed = distribution(kSEEDER);
}
return beast::xor_shift_engine{seed};
}();
return engine;
return kENGINE;
}
/** Return a uniformly distributed random integer.
@@ -92,7 +92,7 @@ default_prng()
/** @{ */
template <class Engine, class Integral>
std::enable_if_t<std::is_integral_v<Integral> && detail::is_engine<Engine>::value, Integral>
rand_int(Engine& engine, Integral min, Integral max)
randInt(Engine& engine, Integral min, Integral max)
{
XRPL_ASSERT(max > min, "xrpl::rand_int : max over min inputs");
@@ -104,37 +104,37 @@ rand_int(Engine& engine, Integral min, Integral max)
template <class Integral>
std::enable_if_t<std::is_integral_v<Integral>, Integral>
rand_int(Integral min, Integral max)
randInt(Integral min, Integral max)
{
return rand_int(default_prng(), min, max);
return randInt(defaultPrng(), min, max);
}
template <class Engine, class Integral>
std::enable_if_t<std::is_integral_v<Integral> && detail::is_engine<Engine>::value, Integral>
rand_int(Engine& engine, Integral max)
randInt(Engine& engine, Integral max)
{
return rand_int(engine, Integral(0), max);
return randInt(engine, Integral(0), max);
}
template <class Integral>
std::enable_if_t<std::is_integral_v<Integral>, Integral>
rand_int(Integral max)
randInt(Integral max)
{
return rand_int(default_prng(), max);
return randInt(defaultPrng(), max);
}
template <class Integral, class Engine>
std::enable_if_t<std::is_integral_v<Integral> && detail::is_engine<Engine>::value, Integral>
rand_int(Engine& engine)
randInt(Engine& engine)
{
return rand_int(engine, std::numeric_limits<Integral>::max());
return randInt(engine, std::numeric_limits<Integral>::max());
}
template <class Integral = int>
std::enable_if_t<std::is_integral_v<Integral>, Integral>
rand_int()
randInt()
{
return rand_int(default_prng(), std::numeric_limits<Integral>::max());
return randInt(defaultPrng(), std::numeric_limits<Integral>::max());
}
/** @} */
@@ -145,17 +145,17 @@ std::enable_if_t<
(std::is_same_v<Byte, unsigned char> || std::is_same_v<Byte, std::uint8_t>) &&
detail::is_engine<Engine>::value,
Byte>
rand_byte(Engine& engine)
randByte(Engine& engine)
{
return static_cast<Byte>(rand_int<Engine, std::uint32_t>(
return static_cast<Byte>(randInt<Engine, std::uint32_t>(
engine, std::numeric_limits<Byte>::min(), std::numeric_limits<Byte>::max()));
}
template <class Byte = std::uint8_t>
std::enable_if_t<(std::is_same_v<Byte, unsigned char> || std::is_same_v<Byte, std::uint8_t>), Byte>
rand_byte()
randByte()
{
return rand_byte<Byte>(default_prng());
return randByte<Byte>(defaultPrng());
}
/** @} */
@@ -163,15 +163,15 @@ rand_byte()
/** @{ */
template <class Engine>
inline bool
rand_bool(Engine& engine)
randBool(Engine& engine)
{
return rand_int(engine, 1) == 1;
return randInt(engine, 1) == 1;
}
inline bool
rand_bool()
randBool()
{
return rand_bool(default_prng());
return randBool(defaultPrng());
}
/** @} */

View File

@@ -18,29 +18,29 @@ concept SafeToCast = (std::is_integral_v<Src> && std::is_integral_v<Dest>) &&
template <class Dest, class Src>
constexpr std::enable_if_t<std::is_integral_v<Dest> && std::is_integral_v<Src>, Dest>
safe_cast(Src s) noexcept
safeCast(Src s) noexcept
{
static_assert(
std::is_signed_v<Dest> || std::is_unsigned_v<Src>, "Cannot cast signed to unsigned");
constexpr unsigned not_same = std::is_signed_v<Dest> != std::is_signed_v<Src>;
constexpr unsigned kNOT_SAME = std::is_signed_v<Dest> != std::is_signed_v<Src>;
static_assert(
sizeof(Dest) >= sizeof(Src) + not_same,
sizeof(Dest) >= sizeof(Src) + kNOT_SAME,
"Destination is too small to hold all values of source");
return static_cast<Dest>(s);
}
template <class Dest, class Src>
constexpr std::enable_if_t<std::is_enum_v<Dest> && std::is_integral_v<Src>, Dest>
safe_cast(Src s) noexcept
safeCast(Src s) noexcept
{
return static_cast<Dest>(safe_cast<std::underlying_type_t<Dest>>(s));
return static_cast<Dest>(safeCast<std::underlying_type_t<Dest>>(s));
}
template <class Dest, class Src>
constexpr std::enable_if_t<std::is_integral_v<Dest> && std::is_enum_v<Src>, Dest>
safe_cast(Src s) noexcept
safeCast(Src s) noexcept
{
return safe_cast<Dest>(static_cast<std::underlying_type_t<Src>>(s));
return safeCast<Dest>(static_cast<std::underlying_type_t<Src>>(s));
}
// unsafe_cast explicitly flags a static_cast as not necessarily able to hold
@@ -49,7 +49,7 @@ safe_cast(Src s) noexcept
template <class Dest, class Src>
constexpr std::enable_if_t<std::is_integral_v<Dest> && std::is_integral_v<Src>, Dest>
unsafe_cast(Src s) noexcept
unsafeCast(Src s) noexcept
{
static_assert(
!SafeToCast<Src, Dest>,
@@ -60,22 +60,22 @@ unsafe_cast(Src s) noexcept
template <class Dest, class Src>
constexpr std::enable_if_t<std::is_enum_v<Dest> && std::is_integral_v<Src>, Dest>
unsafe_cast(Src s) noexcept
unsafeCast(Src s) noexcept
{
return static_cast<Dest>(unsafe_cast<std::underlying_type_t<Dest>>(s));
return static_cast<Dest>(unsafeCast<std::underlying_type_t<Dest>>(s));
}
template <class Dest, class Src>
constexpr std::enable_if_t<std::is_integral_v<Dest> && std::is_enum_v<Src>, Dest>
unsafe_cast(Src s) noexcept
unsafeCast(Src s) noexcept
{
return unsafe_cast<Dest>(static_cast<std::underlying_type_t<Src>>(s));
return unsafeCast<Dest>(static_cast<std::underlying_type_t<Src>>(s));
}
template <class Dest, class Src>
requires std::is_pointer_v<Dest>
inline Dest
safe_downcast(Src* s) noexcept
safeDowncast(Src* s) noexcept
{
#ifdef NDEBUG
return static_cast<Dest>(s); // NOLINT(cppcoreguidelines-pro-type-static-cast-downcast)
@@ -89,7 +89,7 @@ safe_downcast(Src* s) noexcept
template <class Dest, class Src>
requires std::is_lvalue_reference_v<Dest>
inline Dest
safe_downcast(Src& s) noexcept
safeDowncast(Src& s) noexcept
{
#ifndef NDEBUG
XRPL_ASSERT(

View File

@@ -22,19 +22,19 @@ namespace xrpl {
// to enforce this restriction.
template <class EF>
class scope_exit
class ScopeExit
{
EF exit_function_;
bool execute_on_destruction_{true};
public:
~scope_exit()
~ScopeExit()
{
if (execute_on_destruction_)
exit_function_();
}
scope_exit(scope_exit&& rhs) noexcept(
ScopeExit(ScopeExit&& rhs) noexcept(
std::is_nothrow_move_constructible_v<EF> || std::is_nothrow_copy_constructible_v<EF>)
: exit_function_{std::forward<EF>(rhs.exit_function_)}
, execute_on_destruction_{rhs.execute_on_destruction_}
@@ -42,14 +42,14 @@ public:
rhs.release();
}
scope_exit&
operator=(scope_exit&&) = delete;
ScopeExit&
operator=(ScopeExit&&) = delete;
template <class EFP>
explicit scope_exit(
explicit ScopeExit(
EFP&& f,
std::enable_if_t<
!std::is_same_v<std::remove_cv_t<EFP>, scope_exit> &&
!std::is_same_v<std::remove_cv_t<EFP>, ScopeExit> &&
std::is_constructible_v<EF, EFP>>* = 0) noexcept
: exit_function_{std::forward<EFP>(f)}
{
@@ -64,23 +64,23 @@ public:
};
template <class EF>
scope_exit(EF) -> scope_exit<EF>;
ScopeExit(EF) -> ScopeExit<EF>;
template <class EF>
class scope_fail
class ScopeFail
{
EF exit_function_;
bool execute_on_destruction_{true};
int uncaught_on_creation_{std::uncaught_exceptions()};
public:
~scope_fail()
~ScopeFail()
{
if (execute_on_destruction_ && std::uncaught_exceptions() > uncaught_on_creation_)
exit_function_();
}
scope_fail(scope_fail&& rhs) noexcept(
ScopeFail(ScopeFail&& rhs) noexcept(
std::is_nothrow_move_constructible_v<EF> || std::is_nothrow_copy_constructible_v<EF>)
: exit_function_{std::forward<EF>(rhs.exit_function_)}
, execute_on_destruction_{rhs.execute_on_destruction_}
@@ -89,14 +89,14 @@ public:
rhs.release();
}
scope_fail&
operator=(scope_fail&&) = delete;
ScopeFail&
operator=(ScopeFail&&) = delete;
template <class EFP>
explicit scope_fail(
explicit ScopeFail(
EFP&& f,
std::enable_if_t<
!std::is_same_v<std::remove_cv_t<EFP>, scope_fail> &&
!std::is_same_v<std::remove_cv_t<EFP>, ScopeFail> &&
std::is_constructible_v<EF, EFP>>* = 0) noexcept
: exit_function_{std::forward<EFP>(f)}
{
@@ -111,23 +111,23 @@ public:
};
template <class EF>
scope_fail(EF) -> scope_fail<EF>;
ScopeFail(EF) -> ScopeFail<EF>;
template <class EF>
class scope_success
class ScopeSuccess
{
EF exit_function_;
bool execute_on_destruction_{true};
int uncaught_on_creation_{std::uncaught_exceptions()};
public:
~scope_success() noexcept(noexcept(exit_function_()))
~ScopeSuccess() noexcept(noexcept(exit_function_()))
{
if (execute_on_destruction_ && std::uncaught_exceptions() <= uncaught_on_creation_)
exit_function_();
}
scope_success(scope_success&& rhs) noexcept(
ScopeSuccess(ScopeSuccess&& rhs) noexcept(
std::is_nothrow_move_constructible_v<EF> || std::is_nothrow_copy_constructible_v<EF>)
: exit_function_{std::forward<EF>(rhs.exit_function_)}
, execute_on_destruction_{rhs.execute_on_destruction_}
@@ -136,14 +136,14 @@ public:
rhs.release();
}
scope_success&
operator=(scope_success&&) = delete;
ScopeSuccess&
operator=(ScopeSuccess&&) = delete;
template <class EFP>
explicit scope_success(
explicit ScopeSuccess(
EFP&& f,
std::enable_if_t<
!std::is_same_v<std::remove_cv_t<EFP>, scope_success> &&
!std::is_same_v<std::remove_cv_t<EFP>, ScopeSuccess> &&
std::is_constructible_v<EF, EFP>>* =
0) noexcept(std::is_nothrow_constructible_v<EF, EFP> || std::is_nothrow_constructible_v<EF, EFP&>)
: exit_function_{std::forward<EFP>(f)}
@@ -158,7 +158,7 @@ public:
};
template <class EF>
scope_success(EF) -> scope_success<EF>;
ScopeSuccess(EF) -> ScopeSuccess<EF>;
/**
Automatically unlocks and re-locks a unique_lock object.
@@ -198,29 +198,29 @@ scope_success(EF) -> scope_success<EF>;
*/
template <class Mutex>
class scope_unlock
class ScopeUnlock
{
std::unique_lock<Mutex>* plock;
std::unique_lock<Mutex>* plock_;
public:
explicit scope_unlock(std::unique_lock<Mutex>& lock) noexcept(true) : plock(&lock)
explicit ScopeUnlock(std::unique_lock<Mutex>& lock) noexcept(true) : plock_(&lock)
{
XRPL_ASSERT(plock->owns_lock(), "xrpl::scope_unlock::scope_unlock : mutex must be locked");
plock->unlock();
XRPL_ASSERT(plock_->owns_lock(), "xrpl::scope_unlock::scope_unlock : mutex must be locked");
plock_->unlock();
}
// Immovable type
scope_unlock(scope_unlock const&) = delete;
scope_unlock&
operator=(scope_unlock const&) = delete;
ScopeUnlock(ScopeUnlock const&) = delete;
ScopeUnlock&
operator=(ScopeUnlock const&) = delete;
~scope_unlock() noexcept(true)
~ScopeUnlock() noexcept(true)
{
plock->lock();
plock_->lock();
}
};
template <class Mutex>
scope_unlock(std::unique_lock<Mutex>&) -> scope_unlock<Mutex>;
ScopeUnlock(std::unique_lock<Mutex>&) -> ScopeUnlock<Mutex>;
} // namespace xrpl

View File

@@ -26,7 +26,7 @@ namespace detail {
specific amount of time, to prevent this.
*/
inline void
spin_pause() noexcept
spinPause() noexcept
{
#ifdef __aarch64__
asm volatile("yield");
@@ -71,7 +71,7 @@ spin_pause() noexcept
https://en.cppreference.com/w/cpp/named_req/Lockable
*/
template <class T>
class packed_spinlock
class PackedSpinlock
{
// clang-format off
static_assert(std::is_unsigned_v<T>);
@@ -87,9 +87,9 @@ private:
T const mask_;
public:
packed_spinlock(packed_spinlock const&) = delete;
packed_spinlock&
operator=(packed_spinlock const&) = delete;
PackedSpinlock(PackedSpinlock const&) = delete;
PackedSpinlock&
operator=(PackedSpinlock const&) = delete;
/** A single spinlock packed inside the specified atomic
@@ -99,8 +99,7 @@ public:
@note For performance reasons, you should strive to have `lock` be
on a cacheline by itself.
*/
packed_spinlock(std::atomic<T>& lock, int index)
: bits_(lock), mask_(static_cast<T>(1) << index)
PackedSpinlock(std::atomic<T>& lock, int index) : bits_(lock), mask_(static_cast<T>(1) << index)
{
XRPL_ASSERT(
index >= 0 && (mask_ != 0),
@@ -108,7 +107,7 @@ public:
}
[[nodiscard]] bool
try_lock()
try_lock() // NOLINT(readability-identifier-naming)
{
return (bits_.fetch_or(mask_, std::memory_order_acquire) & mask_) == 0;
}
@@ -123,7 +122,7 @@ public:
// of contention by avoiding writes that would definitely not
// result in the lock being acquired.
while ((bits_.load(std::memory_order_relaxed) & mask_) != 0)
detail::spin_pause();
detail::spinPause();
}
}
@@ -147,7 +146,7 @@ public:
https://en.cppreference.com/w/cpp/named_req/Lockable
*/
template <class T>
class spinlock
class Spinlock
{
static_assert(std::is_unsigned_v<T>);
static_assert(std::atomic<T>::is_always_lock_free);
@@ -156,9 +155,9 @@ private:
std::atomic<T>& lock_;
public:
spinlock(spinlock const&) = delete;
spinlock&
operator=(spinlock const&) = delete;
Spinlock(Spinlock const&) = delete;
Spinlock&
operator=(Spinlock const&) = delete;
/** Grabs the
@@ -167,12 +166,12 @@ public:
@note For performance reasons, you should strive to have `lock` be
on a cacheline by itself.
*/
spinlock(std::atomic<T>& lock) : lock_(lock)
Spinlock(std::atomic<T>& lock) : lock_(lock)
{
}
[[nodiscard]] bool
try_lock()
try_lock() // NOLINT(readability-identifier-naming)
{
T expected = 0;
@@ -193,7 +192,7 @@ public:
// of contention by avoiding writes that would definitely not
// result in the lock being acquired.
while (lock_.load(std::memory_order_relaxed) != 0)
detail::spin_pause();
detail::spinPause();
}
}

View File

@@ -23,171 +23,171 @@ namespace xrpl {
allowed arithmetic operations.
*/
template <class Int, class Tag>
class tagged_integer : boost::totally_ordered<
tagged_integer<Int, Tag>,
boost::integer_arithmetic<
tagged_integer<Int, Tag>,
boost::bitwise<
tagged_integer<Int, Tag>,
boost::unit_steppable<
tagged_integer<Int, Tag>,
boost::shiftable<tagged_integer<Int, Tag>>>>>>
class TaggedInteger : boost::totally_ordered<
TaggedInteger<Int, Tag>,
boost::integer_arithmetic<
TaggedInteger<Int, Tag>,
boost::bitwise<
TaggedInteger<Int, Tag>,
boost::unit_steppable<
TaggedInteger<Int, Tag>,
boost::shiftable<TaggedInteger<Int, Tag>>>>>>
{
private:
Int m_value;
Int value_;
public:
using value_type = Int;
using tag_type = Tag;
tagged_integer() = default;
TaggedInteger() = default;
template <
class OtherInt,
class = std::enable_if_t<std::is_integral_v<OtherInt> && sizeof(OtherInt) <= sizeof(Int)>>
explicit constexpr tagged_integer(OtherInt value) noexcept : m_value(value)
explicit constexpr TaggedInteger(OtherInt value) noexcept : value_(value)
{
static_assert(sizeof(tagged_integer) == sizeof(Int), "tagged_integer is adding padding");
static_assert(sizeof(TaggedInteger) == sizeof(Int), "tagged_integer is adding padding");
}
bool
operator<(tagged_integer const& rhs) const noexcept
operator<(TaggedInteger const& rhs) const noexcept
{
return m_value < rhs.m_value;
return value_ < rhs.value_;
}
bool
operator==(tagged_integer const& rhs) const noexcept
operator==(TaggedInteger const& rhs) const noexcept
{
return m_value == rhs.m_value;
return value_ == rhs.value_;
}
tagged_integer&
operator+=(tagged_integer const& rhs) noexcept
TaggedInteger&
operator+=(TaggedInteger const& rhs) noexcept
{
m_value += rhs.m_value;
value_ += rhs.value_;
return *this;
}
tagged_integer&
operator-=(tagged_integer const& rhs) noexcept
TaggedInteger&
operator-=(TaggedInteger const& rhs) noexcept
{
m_value -= rhs.m_value;
value_ -= rhs.value_;
return *this;
}
tagged_integer&
operator*=(tagged_integer const& rhs) noexcept
TaggedInteger&
operator*=(TaggedInteger const& rhs) noexcept
{
m_value *= rhs.m_value;
value_ *= rhs.value_;
return *this;
}
tagged_integer&
operator/=(tagged_integer const& rhs) noexcept
TaggedInteger&
operator/=(TaggedInteger const& rhs) noexcept
{
m_value /= rhs.m_value;
value_ /= rhs.value_;
return *this;
}
tagged_integer&
operator%=(tagged_integer const& rhs) noexcept
TaggedInteger&
operator%=(TaggedInteger const& rhs) noexcept
{
m_value %= rhs.m_value;
value_ %= rhs.value_;
return *this;
}
tagged_integer&
operator|=(tagged_integer const& rhs) noexcept
TaggedInteger&
operator|=(TaggedInteger const& rhs) noexcept
{
m_value |= rhs.m_value;
value_ |= rhs.value_;
return *this;
}
tagged_integer&
operator&=(tagged_integer const& rhs) noexcept
TaggedInteger&
operator&=(TaggedInteger const& rhs) noexcept
{
m_value &= rhs.m_value;
value_ &= rhs.value_;
return *this;
}
tagged_integer&
operator^=(tagged_integer const& rhs) noexcept
TaggedInteger&
operator^=(TaggedInteger const& rhs) noexcept
{
m_value ^= rhs.m_value;
value_ ^= rhs.value_;
return *this;
}
tagged_integer&
operator<<=(tagged_integer const& rhs) noexcept
TaggedInteger&
operator<<=(TaggedInteger const& rhs) noexcept
{
m_value <<= rhs.m_value;
value_ <<= rhs.value_;
return *this;
}
tagged_integer&
operator>>=(tagged_integer const& rhs) noexcept
TaggedInteger&
operator>>=(TaggedInteger const& rhs) noexcept
{
m_value >>= rhs.m_value;
value_ >>= rhs.value_;
return *this;
}
tagged_integer
TaggedInteger
operator~() const noexcept
{
return tagged_integer{~m_value};
return TaggedInteger{~value_};
}
tagged_integer
TaggedInteger
operator+() const noexcept
{
return *this;
}
tagged_integer
TaggedInteger
operator-() const noexcept
{
return tagged_integer{-m_value};
return TaggedInteger{-value_};
}
tagged_integer&
TaggedInteger&
operator++() noexcept
{
++m_value;
++value_;
return *this;
}
tagged_integer&
TaggedInteger&
operator--() noexcept
{
--m_value;
--value_;
return *this;
}
explicit
operator Int() const noexcept
{
return m_value;
return value_;
}
friend std::ostream&
operator<<(std::ostream& s, tagged_integer const& t)
operator<<(std::ostream& s, TaggedInteger const& t)
{
s << t.m_value;
s << t.value_;
return s;
}
friend std::istream&
operator>>(std::istream& s, tagged_integer& t)
operator>>(std::istream& s, TaggedInteger& t)
{
s >> t.m_value;
s >> t.value_;
return s;
}
friend std::string
to_string(tagged_integer const& t)
to_string(TaggedInteger const& t)
{
return std::to_string(t.m_value);
return std::to_string(t.value_);
}
};
@@ -195,10 +195,10 @@ public:
namespace beast {
template <class Int, class Tag, class HashAlgorithm>
struct is_contiguously_hashable<xrpl::tagged_integer<Int, Tag>, HashAlgorithm>
: public is_contiguously_hashable<Int, HashAlgorithm>
struct IsContiguouslyHashable<xrpl::TaggedInteger<Int, Tag>, HashAlgorithm>
: public IsContiguouslyHashable<Int, HashAlgorithm>
{
explicit is_contiguously_hashable() = default;
explicit IsContiguouslyHashable() = default;
};
} // namespace beast

View File

@@ -15,44 +15,44 @@ namespace beast {
/** Measures handler latency on an io_context queue. */
template <class Clock>
class io_latency_probe
class IoLatencyProbe
{
private:
using duration = typename Clock::duration;
using time_point = typename Clock::time_point;
std::recursive_mutex m_mutex;
std::condition_variable_any m_cond;
std::size_t m_count{1};
duration const m_period;
boost::asio::io_context& m_ios;
boost::asio::basic_waitable_timer<std::chrono::steady_clock> m_timer;
bool m_cancel{false};
std::recursive_mutex mutex_;
std::condition_variable_any cond_;
std::size_t count_{1};
duration const period_;
boost::asio::io_context& ios_;
boost::asio::basic_waitable_timer<std::chrono::steady_clock> timer_;
bool cancel_{false};
public:
io_latency_probe(duration const& period, boost::asio::io_context& ios)
: m_period(period), m_ios(ios), m_timer(m_ios)
IoLatencyProbe(duration const& period, boost::asio::io_context& ios)
: period_(period), ios_(ios), timer_(ios_)
{
}
~io_latency_probe()
~IoLatencyProbe()
{
std::unique_lock<decltype(m_mutex)> lock(m_mutex);
std::unique_lock<decltype(mutex_)> lock(mutex_);
cancel(lock, true);
}
/** Return the io_context associated with the latency probe. */
/** @{ */
boost::asio::io_context&
get_io_context()
getIoContext()
{
return m_ios;
return ios_;
}
[[nodiscard]] boost::asio::io_context const&
get_io_context() const
getIoContext() const
{
return m_ios;
return ios_;
}
/** @} */
@@ -63,14 +63,14 @@ public:
void
cancel()
{
std::unique_lock<decltype(m_mutex)> lock(m_mutex);
std::unique_lock<decltype(mutex_)> lock(mutex_);
cancel(lock, true);
}
void
cancel_async()
cancelAsync()
{
std::unique_lock<decltype(m_mutex)> lock(m_mutex);
std::unique_lock<decltype(mutex_)> lock(mutex_);
cancel(lock, false);
}
/** @} */
@@ -81,13 +81,13 @@ public:
*/
template <class Handler>
void
sample_one(Handler&& handler)
sampleOne(Handler&& handler)
{
std::lock_guard const lock(m_mutex);
if (m_cancel)
std::scoped_lock const lock(mutex_);
if (cancel_)
throw std::logic_error("io_latency_probe is canceled");
boost::asio::post(
m_ios, sample_op<Handler>(std::forward<Handler>(handler), Clock::now(), false, this));
ios_, SampleOp<Handler>(std::forward<Handler>(handler), Clock::now(), false, this));
}
/** Initiate continuous i/o latency sampling.
@@ -98,125 +98,123 @@ public:
void
sample(Handler&& handler)
{
std::lock_guard const lock(m_mutex);
if (m_cancel)
std::scoped_lock const lock(mutex_);
if (cancel_)
throw std::logic_error("io_latency_probe is canceled");
boost::asio::post(
m_ios, sample_op<Handler>(std::forward<Handler>(handler), Clock::now(), true, this));
ios_, SampleOp<Handler>(std::forward<Handler>(handler), Clock::now(), true, this));
}
private:
void
cancel(std::unique_lock<decltype(m_mutex)>& lock, bool wait)
cancel(std::unique_lock<decltype(mutex_)>& lock, bool wait)
{
if (!m_cancel)
if (!cancel_)
{
--m_count;
m_cancel = true;
--count_;
cancel_ = true;
}
if (wait)
m_cond.wait(lock, [this] { return this->m_count == 0; });
cond_.wait(lock, [this] { return this->count_ == 0; });
}
void
addref()
{
std::lock_guard const lock(m_mutex);
++m_count;
std::scoped_lock const lock(mutex_);
++count_;
}
void
release()
{
std::lock_guard const lock(m_mutex);
if (--m_count == 0)
m_cond.notify_all();
std::scoped_lock const lock(mutex_);
if (--count_ == 0)
cond_.notify_all();
}
template <class Handler>
struct sample_op
struct SampleOp
{
Handler m_handler;
time_point m_start;
bool m_repeat;
io_latency_probe* m_probe;
Handler handler;
time_point start;
bool repeat;
IoLatencyProbe* probe;
sample_op(
SampleOp(
Handler const& handler,
time_point const& start,
bool repeat,
io_latency_probe* probe)
: m_handler(handler), m_start(start), m_repeat(repeat), m_probe(probe)
IoLatencyProbe* probe)
: handler(handler), start(start), repeat(repeat), probe(probe)
{
XRPL_ASSERT(
m_probe,
probe,
"beast::io_latency_probe::sample_op::sample_op : non-null "
"probe input");
m_probe->addref();
probe->addref();
}
sample_op(sample_op&& from) noexcept
: m_handler(std::move(from.m_handler))
, m_start(from.m_start)
, m_repeat(from.m_repeat)
, m_probe(from.m_probe)
SampleOp(SampleOp&& from) noexcept
: handler(std::move(from.handler))
, start(from.start)
, repeat(from.repeat)
, probe(from.probe)
{
XRPL_ASSERT(
m_probe,
probe,
"beast::io_latency_probe::sample_op::sample_op(sample_op&&) : "
"non-null probe input");
from.m_probe = nullptr;
from.probe = nullptr;
}
sample_op(sample_op const&) = delete;
sample_op
operator=(sample_op const&) = delete;
sample_op&
operator=(sample_op&&) = delete;
SampleOp(SampleOp const&) = delete;
SampleOp
operator=(SampleOp const&) = delete;
SampleOp&
operator=(SampleOp&&) = delete;
~sample_op()
~SampleOp()
{
if (m_probe)
m_probe->release();
if (probe)
probe->release();
}
void
operator()() const
{
if (m_probe == nullptr)
if (probe == nullptr)
return;
typename Clock::time_point const now(Clock::now());
typename Clock::duration const elapsed(now - m_start);
typename Clock::duration const elapsed(now - start);
m_handler(elapsed);
handler(elapsed);
{
std::lock_guard const lock(m_probe->m_mutex);
if (m_probe->m_cancel)
std::scoped_lock const lock(probe->mutex_);
if (probe->cancel_)
return;
}
if (m_repeat)
if (repeat)
{
// Calculate when we want to sample again, and
// adjust for the expected latency.
//
typename Clock::time_point const when(now + m_probe->m_period - (2 * elapsed));
typename Clock::time_point const when(now + probe->period_ - (2 * elapsed));
if (when <= now)
{
// The latency is too high to maintain the desired
// period so don't bother with a timer.
//
boost::asio::post(
m_probe->m_ios, sample_op<Handler>(m_handler, now, m_repeat, m_probe));
boost::asio::post(probe->ios_, SampleOp<Handler>(handler, now, repeat, probe));
}
else
{
m_probe->m_timer.expires_after(when - now);
m_probe->m_timer.async_wait(
sample_op<Handler>(m_handler, now, m_repeat, m_probe));
probe->timer_.expires_after(when - now);
probe->timer_.async_wait(SampleOp<Handler>(handler, now, repeat, probe));
}
}
}
@@ -224,11 +222,10 @@ private:
void
operator()(boost::system::error_code const& ec)
{
if (m_probe == nullptr)
if (probe == nullptr)
return;
typename Clock::time_point const now(Clock::now());
boost::asio::post(
m_probe->m_ios, sample_op<Handler>(m_handler, now, m_repeat, m_probe));
boost::asio::post(probe->ios_, SampleOp<Handler>(handler, now, repeat, probe));
}
};
};

View File

@@ -31,7 +31,7 @@ namespace beast {
http://en.cppreference.com/w/cpp/concept/Clock
*/
template <class Clock>
class abstract_clock
class AbstractClock
{
public:
using rep = typename Clock::rep;
@@ -40,11 +40,11 @@ public:
using time_point = typename Clock::time_point;
using clock_type = Clock;
static bool const is_steady = Clock::is_steady;
static bool const is_steady = Clock::is_steady; // NOLINT(readability-identifier-naming)
virtual ~abstract_clock() = default;
abstract_clock() = default;
abstract_clock(abstract_clock const&) = default;
virtual ~AbstractClock() = default;
AbstractClock() = default;
AbstractClock(AbstractClock const&) = default;
/** Returns the current time. */
[[nodiscard]] virtual time_point
@@ -56,12 +56,12 @@ public:
namespace detail {
template <class Facade, class Clock>
struct abstract_clock_wrapper : public abstract_clock<Facade>
struct AbstractClockWrapper : public AbstractClock<Facade>
{
explicit abstract_clock_wrapper() = default;
explicit AbstractClockWrapper() = default;
using typename abstract_clock<Facade>::duration;
using typename abstract_clock<Facade>::time_point;
using typename AbstractClock<Facade>::duration;
using typename AbstractClock<Facade>::time_point;
[[nodiscard]] time_point
now() const override
@@ -80,11 +80,11 @@ struct abstract_clock_wrapper : public abstract_clock<Facade>
@tparam Clock The actual concrete clock to use.
*/
template <class Facade, class Clock = Facade>
abstract_clock<Facade>&
get_abstract_clock()
AbstractClock<Facade>&
getAbstractClock()
{
static detail::abstract_clock_wrapper<Facade, Clock> clock;
return clock;
static detail::AbstractClockWrapper<Facade, Clock> kCLOCK;
return kCLOCK;
}
} // namespace beast

View File

@@ -13,19 +13,20 @@ namespace beast {
@tparam Clock A type meeting these requirements:
http://en.cppreference.com/w/cpp/concept/Clock
*/
class basic_seconds_clock
class BasicSecondsClock
{
public:
using Clock = std::chrono::steady_clock;
explicit basic_seconds_clock() = default;
explicit BasicSecondsClock() = default;
using rep = typename Clock::rep;
using period = typename Clock::period;
using duration = typename Clock::duration;
using time_point = typename Clock::time_point;
static bool const is_steady = Clock::is_steady;
static bool const is_steady = // NOLINT(readability-identifier-naming)
Clock::is_steady;
static time_point
now();

View File

@@ -17,18 +17,18 @@ namespace beast {
http://en.cppreference.com/w/cpp/concept/Clock
*/
template <class Clock>
class manual_clock : public abstract_clock<Clock>
class ManualClock : public AbstractClock<Clock>
{
public:
using typename abstract_clock<Clock>::rep;
using typename abstract_clock<Clock>::duration;
using typename abstract_clock<Clock>::time_point;
using typename AbstractClock<Clock>::rep;
using typename AbstractClock<Clock>::duration;
using typename AbstractClock<Clock>::time_point;
private:
time_point now_;
public:
explicit manual_clock(time_point const& now = time_point(duration(0))) : now_(now)
explicit ManualClock(time_point const& now = time_point(duration(0))) : now_(now)
{
}
@@ -44,16 +44,16 @@ public:
{
XRPL_ASSERT(
!Clock::is_steady || when >= now_,
"beast::manual_clock::set(time_point) : forward input");
"beast::ManualClock::set(time_point) : forward input");
now_ = when;
}
/** Convenience for setting the time in seconds from epoch. */
template <class Integer>
void
set(Integer seconds_from_epoch)
set(Integer secondsFromEpoch)
{
set(time_point(duration(std::chrono::seconds(seconds_from_epoch))));
set(time_point(duration(std::chrono::seconds(secondsFromEpoch))));
}
/** Advance the clock by a duration. */
@@ -63,12 +63,12 @@ public:
{
XRPL_ASSERT(
!Clock::is_steady || (now_ + elapsed) >= now_,
"beast::manual_clock::advance(duration) : forward input");
"beast::ManualClock::advance(duration) : forward input");
now_ += elapsed;
}
/** Convenience for advancing the clock by one second. */
manual_clock&
ManualClock&
operator++()
{
advance(std::chrono::seconds(1));

View File

@@ -5,9 +5,9 @@
namespace beast {
template <class T>
struct is_aged_container : std::false_type
struct IsAgedContainer : std::false_type
{
explicit is_aged_container() = default;
explicit IsAgedContainer() = default;
};
} // namespace beast

View File

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

View File

@@ -14,6 +14,6 @@ template <
class Clock = std::chrono::steady_clock,
class Compare = std::less<Key>,
class Allocator = std::allocator<std::pair<Key const, T>>>
using aged_map = detail::aged_ordered_container<false, true, Key, T, Clock, Compare, Allocator>;
using aged_map = detail::AgedOrderedContainer<false, true, Key, T, Clock, Compare, Allocator>;
} // namespace beast

View File

@@ -14,6 +14,6 @@ template <
class Clock = std::chrono::steady_clock,
class Compare = std::less<Key>,
class Allocator = std::allocator<std::pair<Key const, T>>>
using aged_multimap = detail::aged_ordered_container<true, true, Key, T, Clock, Compare, Allocator>;
using aged_multimap = detail::AgedOrderedContainer<true, true, Key, T, Clock, Compare, Allocator>;
} // namespace beast

View File

@@ -14,5 +14,6 @@ template <
class Compare = std::less<Key>,
class Allocator = std::allocator<Key>>
using aged_multiset =
detail::aged_ordered_container<true, false, Key, void, Clock, Compare, Allocator>;
detail::AgedOrderedContainer<true, false, Key, void, Clock, Compare, Allocator>;
} // namespace beast

View File

@@ -13,6 +13,6 @@ template <
class Clock = std::chrono::steady_clock,
class Compare = std::less<Key>,
class Allocator = std::allocator<Key>>
using aged_set = detail::aged_ordered_container<false, false, Key, void, Clock, Compare, Allocator>;
using aged_set = detail::AgedOrderedContainer<false, false, Key, void, Clock, Compare, Allocator>;
} // namespace beast

View File

@@ -16,5 +16,6 @@ template <
class KeyEqual = std::equal_to<Key>,
class Allocator = std::allocator<std::pair<Key const, T>>>
using aged_unordered_map =
detail::aged_unordered_container<false, true, Key, T, Clock, Hash, KeyEqual, Allocator>;
detail::AgedUnorderedContainer<false, true, Key, T, Clock, Hash, KeyEqual, Allocator>;
} // namespace beast

View File

@@ -16,5 +16,6 @@ template <
class KeyEqual = std::equal_to<Key>,
class Allocator = std::allocator<std::pair<Key const, T>>>
using aged_unordered_multimap =
detail::aged_unordered_container<true, true, Key, T, Clock, Hash, KeyEqual, Allocator>;
detail::AgedUnorderedContainer<true, true, Key, T, Clock, Hash, KeyEqual, Allocator>;
} // namespace beast

View File

@@ -15,6 +15,6 @@ template <
class KeyEqual = std::equal_to<Key>,
class Allocator = std::allocator<Key>>
using aged_unordered_multiset =
detail::aged_unordered_container<true, false, Key, void, Clock, Hash, KeyEqual, Allocator>;
detail::AgedUnorderedContainer<true, false, Key, void, Clock, Hash, KeyEqual, Allocator>;
} // namespace beast

View File

@@ -15,5 +15,6 @@ template <
class KeyEqual = std::equal_to<Key>,
class Allocator = std::allocator<Key>>
using aged_unordered_set =
detail::aged_unordered_container<false, false, Key, void, Clock, Hash, KeyEqual, Allocator>;
detail::AgedUnorderedContainer<false, false, Key, void, Clock, Hash, KeyEqual, Allocator>;
} // namespace beast

View File

@@ -3,10 +3,10 @@
namespace beast::detail {
// Extracts the key portion of value
template <bool maybe_map>
struct aged_associative_container_extract_t
template <bool MaybeMap>
struct AgedAssociativeContainerExtractT
{
explicit aged_associative_container_extract_t() = default;
explicit AgedAssociativeContainerExtractT() = default;
template <class Value>
decltype(Value::first) const&
@@ -17,9 +17,9 @@ struct aged_associative_container_extract_t
};
template <>
struct aged_associative_container_extract_t<false>
struct AgedAssociativeContainerExtractT<false>
{
explicit aged_associative_container_extract_t() = default;
explicit AgedAssociativeContainerExtractT() = default;
template <class Value>
Value const&

View File

@@ -12,137 +12,136 @@ class aged_ordered_container;
namespace detail {
// If Iterator is SCARY then this iterator will be as well.
template <bool is_const, class Iterator>
class aged_container_iterator
template <bool IsConst, class Iterator>
class AgedContainerIterator
{
public:
using iterator_category = typename std::iterator_traits<Iterator>::iterator_category;
using value_type = std::conditional_t<
is_const,
typename Iterator::value_type::stashed::value_type const,
typename Iterator::value_type::stashed::value_type>;
IsConst,
typename Iterator::value_type::Stashed::value_type const,
typename Iterator::value_type::Stashed::value_type>;
using difference_type = typename std::iterator_traits<Iterator>::difference_type;
using pointer = value_type*;
using reference = value_type&;
using time_point = typename Iterator::value_type::stashed::time_point;
using time_point = typename Iterator::value_type::Stashed::time_point;
aged_container_iterator() = default;
AgedContainerIterator() = default;
// Disable constructing a const_iterator from a non-const_iterator.
// Converting between reverse and non-reverse iterators should be explicit.
template <
bool other_is_const,
bool OtherIsConst,
class OtherIterator,
class = std::enable_if_t<
(!other_is_const || is_const) &&
(!OtherIsConst || IsConst) &&
!static_cast<bool>(std::is_same_v<Iterator, OtherIterator>)>>
explicit aged_container_iterator(
aged_container_iterator<other_is_const, OtherIterator> const& other)
: m_iter(other.m_iter)
explicit AgedContainerIterator(AgedContainerIterator<OtherIsConst, OtherIterator> const& other)
: iter_(other.iter_)
{
}
// Disable constructing a const_iterator from a non-const_iterator.
template <bool other_is_const, class = std::enable_if_t<!other_is_const || is_const>>
aged_container_iterator(aged_container_iterator<other_is_const, Iterator> const& other)
: m_iter(other.m_iter)
template <bool OtherIsConst, class = std::enable_if_t<!OtherIsConst || IsConst>>
AgedContainerIterator(AgedContainerIterator<OtherIsConst, Iterator> const& other)
: iter_(other.iter_)
{
}
// Disable assigning a const_iterator to a non-const iterator
template <bool other_is_const, class OtherIterator>
template <bool OtherIsConst, class OtherIterator>
auto
operator=(aged_container_iterator<other_is_const, OtherIterator> const& other)
-> std::enable_if_t<!other_is_const || is_const, aged_container_iterator&>
operator=(AgedContainerIterator<OtherIsConst, OtherIterator> const& other)
-> std::enable_if_t<!OtherIsConst || IsConst, AgedContainerIterator&>
{
m_iter = other.m_iter;
iter_ = other.iter_;
return *this;
}
template <bool other_is_const, class OtherIterator>
template <bool OtherIsConst, class OtherIterator>
bool
operator==(aged_container_iterator<other_is_const, OtherIterator> const& other) const
operator==(AgedContainerIterator<OtherIsConst, OtherIterator> const& other) const
{
return m_iter == other.m_iter;
return iter_ == other.iter_;
}
template <bool other_is_const, class OtherIterator>
template <bool OtherIsConst, class OtherIterator>
bool
operator!=(aged_container_iterator<other_is_const, OtherIterator> const& other) const
operator!=(AgedContainerIterator<OtherIsConst, OtherIterator> const& other) const
{
return m_iter != other.m_iter;
return iter_ != other.iter_;
}
aged_container_iterator&
AgedContainerIterator&
operator++()
{
++m_iter;
++iter_;
return *this;
}
aged_container_iterator
AgedContainerIterator
operator++(int)
{
aged_container_iterator const prev(*this);
++m_iter;
AgedContainerIterator const prev(*this);
++iter_;
return prev;
}
aged_container_iterator&
AgedContainerIterator&
operator--()
{
--m_iter;
--iter_;
return *this;
}
aged_container_iterator
AgedContainerIterator
operator--(int)
{
aged_container_iterator const prev(*this);
--m_iter;
AgedContainerIterator const prev(*this);
--iter_;
return prev;
}
reference
operator*() const
{
return m_iter->value;
return iter_->value;
}
pointer
operator->() const
{
return &m_iter->value;
return &iter_->value;
}
[[nodiscard]] time_point const&
when() const
{
return m_iter->when;
return iter_->when;
}
private:
template <bool, bool, class, class, class, class, class>
friend class aged_ordered_container;
friend class AgedOrderedContainer;
template <bool, bool, class, class, class, class, class, class>
friend class aged_unordered_container;
friend class AgedUnorderedContainer;
template <bool, class>
friend class aged_container_iterator;
friend class AgedContainerIterator;
template <class OtherIterator>
aged_container_iterator(OtherIterator iter) : m_iter(std::move(iter))
AgedContainerIterator(OtherIterator iter) : iter_(std::move(iter))
{
}
[[nodiscard]] Iterator const&
iterator() const
{
return m_iter;
return iter_;
}
Iterator m_iter;
Iterator iter_;
};
} // namespace detail

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -14,25 +14,25 @@
namespace beast::detail {
template <class T>
struct is_empty_base_optimization_derived
struct IsEmptyBaseOptimizationDerived
: std::integral_constant<bool, std::is_empty_v<T> && !boost::is_final<T>::value>
{
};
template <class T, int UniqueID = 0, bool isDerived = is_empty_base_optimization_derived<T>::value>
class empty_base_optimization : private T
template <class T, int UniqueID = 0, bool IsDerived = IsEmptyBaseOptimizationDerived<T>::value>
class EmptyBaseOptimization : private T
{
public:
empty_base_optimization() = default;
empty_base_optimization(empty_base_optimization&&) = default;
empty_base_optimization(empty_base_optimization const&) = default;
empty_base_optimization&
operator=(empty_base_optimization&&) = default;
empty_base_optimization&
operator=(empty_base_optimization const&) = default;
EmptyBaseOptimization() = default;
EmptyBaseOptimization(EmptyBaseOptimization&&) = default;
EmptyBaseOptimization(EmptyBaseOptimization const&) = default;
EmptyBaseOptimization&
operator=(EmptyBaseOptimization&&) = default;
EmptyBaseOptimization&
operator=(EmptyBaseOptimization const&) = default;
template <class Arg1, class... ArgN>
explicit empty_base_optimization(Arg1&& arg1, ArgN&&... argn)
explicit EmptyBaseOptimization(Arg1&& arg1, ArgN&&... argn)
: T(std::forward<Arg1>(arg1), std::forward<ArgN>(argn)...)
{
}
@@ -53,21 +53,21 @@ public:
//------------------------------------------------------------------------------
template <class T, int UniqueID>
class empty_base_optimization<T, UniqueID, false>
class EmptyBaseOptimization<T, UniqueID, false>
{
T t_;
public:
empty_base_optimization() = default;
empty_base_optimization(empty_base_optimization&&) = default;
empty_base_optimization(empty_base_optimization const&) = default;
empty_base_optimization&
operator=(empty_base_optimization&&) = default;
empty_base_optimization&
operator=(empty_base_optimization const&) = default;
EmptyBaseOptimization() = default;
EmptyBaseOptimization(EmptyBaseOptimization&&) = default;
EmptyBaseOptimization(EmptyBaseOptimization const&) = default;
EmptyBaseOptimization&
operator=(EmptyBaseOptimization&&) = default;
EmptyBaseOptimization&
operator=(EmptyBaseOptimization const&) = default;
template <class Arg1, class... ArgN>
explicit empty_base_optimization(Arg1&& arg1, ArgN&&... argn)
explicit EmptyBaseOptimization(Arg1&& arg1, ArgN&&... argn)
: t_(std::forward<Arg1>(arg1), std::forward<ArgN>(argn)...)
{
}

View File

@@ -21,7 +21,7 @@ setCurrentThreadName(std::string_view newThreadName);
// On Linux, thread names are limited to 16 bytes including the null terminator.
// Maximum number of characters is therefore 15.
constexpr std::size_t maxThreadNameLength = 15;
constexpr std::size_t kMAX_THREAD_NAME_LENGTH = 15;
/** Sets the name of the caller thread with compile-time size checking.
@tparam N The size of the string literal including null terminator
@@ -34,7 +34,7 @@ template <std::size_t N>
void
setCurrentThreadName(char const (&newThreadName)[N])
{
static_assert(N <= maxThreadNameLength + 1, "Thread name cannot exceed 15 characters");
static_assert(N <= kMAX_THREAD_NAME_LENGTH + 1, "Thread name cannot exceed 15 characters");
setCurrentThreadName(std::string_view(newThreadName, N - 1));
}

View File

@@ -45,8 +45,8 @@ class ListNode
template <typename>
friend class ListIterator;
ListNode* m_next = nullptr;
ListNode* m_prev = nullptr;
ListNode* next_ = nullptr;
ListNode* prev_ = nullptr;
};
//------------------------------------------------------------------------------
@@ -62,12 +62,12 @@ public:
using reference = value_type&;
using size_type = std::size_t;
ListIterator(N* node = nullptr) noexcept : m_node(node)
ListIterator(N* node = nullptr) noexcept : node_(node)
{
}
template <typename M>
ListIterator(ListIterator<M> const& other) noexcept : m_node(other.m_node)
ListIterator(ListIterator<M> const& other) noexcept : node_(other.node_)
{
}
@@ -75,7 +75,7 @@ public:
bool
operator==(ListIterator<M> const& other) const noexcept
{
return m_node == other.m_node;
return node_ == other.node_;
}
template <typename M>
@@ -131,22 +131,22 @@ private:
[[nodiscard]] reference
dereference() const noexcept
{
return static_cast<reference>(*m_node);
return static_cast<reference>(*node_);
}
void
increment() noexcept
{
m_node = m_node->m_next;
node_ = node_->next_;
}
void
decrement() noexcept
{
m_node = m_node->m_prev;
node_ = node_->prev_;
}
N* m_node;
N* node_;
};
} // namespace detail
@@ -161,11 +161,11 @@ private:
struct Object : List <Object>::Node
{
explicit Object (int value) : m_value (value)
explicit Object (int value) : value_ (value)
{
}
int m_value;
int value_;
};
@endcode
@@ -190,7 +190,7 @@ private:
@code
for (List <Object>::iterator iter = list.begin(); iter != list.end; ++iter)
std::cout << iter->m_value;
std::cout << iter->value_;
@endcode
@@ -199,10 +199,10 @@ private:
@code
BOOST_FOREACH (Object& object, list) // boost only
std::cout << object.m_value;
std::cout << object.value_;
for (Object& object : list) // C++11 only
std::cout << object.m_value;
std::cout << object.value_;
@endcode
@@ -275,8 +275,8 @@ public:
/** Create an empty list. */
List()
{
m_head.m_prev = nullptr; // identifies the head
m_tail.m_next = nullptr; // identifies the tail
head_.prev_ = nullptr; // identifies the head
tail_.next_ = nullptr; // identifies the tail
clear();
}
@@ -297,7 +297,7 @@ public:
[[nodiscard]] size_type
size() const noexcept
{
return m_size;
return size_;
}
/** Obtain a reference to the first element.
@@ -307,7 +307,7 @@ public:
reference
front() noexcept
{
return element_from(m_head.m_next);
return element_from(head_.next_);
}
/** Obtain a const reference to the first element.
@@ -317,7 +317,7 @@ public:
[[nodiscard]] const_reference
front() const noexcept
{
return element_from(m_head.m_next);
return element_from(head_.next_);
}
/** Obtain a reference to the last element.
@@ -327,7 +327,7 @@ public:
reference
back() noexcept
{
return element_from(m_tail.m_prev);
return element_from(tail_.prev_);
}
/** Obtain a const reference to the last element.
@@ -337,7 +337,7 @@ public:
[[nodiscard]] const_reference
back() const noexcept
{
return element_from(m_tail.m_prev);
return element_from(tail_.prev_);
}
/** Obtain an iterator to the beginning of the list.
@@ -346,7 +346,7 @@ public:
iterator
begin() noexcept
{
return iterator(m_head.m_next);
return iterator(head_.next_);
}
/** Obtain a const iterator to the beginning of the list.
@@ -355,7 +355,7 @@ public:
[[nodiscard]] const_iterator
begin() const noexcept
{
return const_iterator(m_head.m_next);
return const_iterator(head_.next_);
}
/** Obtain a const iterator to the beginning of the list.
@@ -364,7 +364,7 @@ public:
[[nodiscard]] const_iterator
cbegin() const noexcept
{
return const_iterator(m_head.m_next);
return const_iterator(head_.next_);
}
/** Obtain a iterator to the end of the list.
@@ -373,7 +373,7 @@ public:
iterator
end() noexcept
{
return iterator(&m_tail);
return iterator(&tail_);
}
/** Obtain a const iterator to the end of the list.
@@ -382,7 +382,7 @@ public:
[[nodiscard]] const_iterator
end() const noexcept
{
return const_iterator(&m_tail);
return const_iterator(&tail_);
}
/** Obtain a const iterator to the end of the list
@@ -391,7 +391,7 @@ public:
[[nodiscard]] const_iterator
cend() const noexcept
{
return const_iterator(&m_tail);
return const_iterator(&tail_);
}
/** Clear the list.
@@ -400,9 +400,9 @@ public:
void
clear() noexcept
{
m_head.m_next = &m_tail;
m_tail.m_prev = &m_head;
m_size = 0;
head_.next_ = &tail_;
tail_.prev_ = &head_;
size_ = 0;
}
/** Insert an element.
@@ -415,11 +415,11 @@ public:
insert(iterator pos, T& element) noexcept
{
Node* node = static_cast<Node*>(&element);
node->m_next = &*pos;
node->m_prev = node->m_next->m_prev;
node->m_next->m_prev = node;
node->m_prev->m_next = node;
++m_size;
node->next_ = &*pos;
node->prev_ = node->next_->prev_;
node->next_->prev_ = node;
node->prev_->next_ = node;
++size_;
return iterator(node);
}
@@ -434,11 +434,11 @@ public:
if (!other.empty())
{
Node* before = &*pos;
other.m_head.m_next->m_prev = before->m_prev;
before->m_prev->m_next = other.m_head.m_next;
other.m_tail.m_prev->m_next = before;
before->m_prev = other.m_tail.m_prev;
m_size += other.m_size;
other.head_.next_->prev_ = before->prev_;
before->prev_->next_ = other.head_.next_;
other.tail_.prev_->next_ = before;
before->prev_ = other.tail_.prev_;
size_ += other.size_;
other.clear();
}
}
@@ -453,9 +453,9 @@ public:
{
Node const* node = &*pos;
++pos;
node->m_next->m_prev = node->m_prev;
node->m_prev->m_next = node->m_next;
--m_size;
node->next_->prev_ = node->prev_;
node->prev_->next_ = node->next_;
--size_;
return pos;
}
@@ -464,7 +464,7 @@ public:
@param element The element to insert.
*/
iterator
push_front(T& element) noexcept
pushFront(T& element) noexcept
{
return insert(begin(), element);
}
@@ -474,7 +474,7 @@ public:
@return A reference to the popped element.
*/
T&
pop_front() noexcept
popFront() noexcept
{
T& element(front());
erase(begin());
@@ -486,7 +486,7 @@ public:
@param element The element to append.
*/
iterator
push_back(T& element) noexcept
pushBack(T& element) noexcept
{
return insert(end(), element);
}
@@ -496,7 +496,7 @@ public:
@return A reference to the popped element.
*/
T&
pop_back() noexcept
popBack() noexcept
{
T& element(back());
erase(--end());
@@ -539,7 +539,7 @@ public:
@return An iterator to the element.
*/
iterator
iterator_to(T& element) const noexcept
iteratorTo(T& element) const noexcept
{
return iterator(static_cast<Node*>(&element));
}
@@ -550,28 +550,28 @@ public:
@return A const iterator to the element.
*/
[[nodiscard]] const_iterator
const_iterator_to(T const& element) const noexcept
constIteratorTo(T const& element) const noexcept
{
return const_iterator(static_cast<Node const*>(&element));
}
private:
reference
element_from(Node* node) noexcept
elementFrom(Node* node) noexcept
{
return *(static_cast<pointer>(node));
}
const_reference
element_from(Node const* node) const noexcept
elementFrom(Node const* node) const noexcept
{
return *(static_cast<const_pointer>(node));
}
private:
size_type m_size = 0u;
Node m_head;
Node m_tail;
size_type size_ = 0u;
Node head_;
Node tail_;
};
} // namespace beast

View File

@@ -26,27 +26,27 @@ public:
LockFreeStackIterator() = default;
LockFreeStackIterator(NodePtr node) : m_node(node)
LockFreeStackIterator(NodePtr node) : node_(node)
{
}
template <bool OtherIsConst>
explicit LockFreeStackIterator(LockFreeStackIterator<Container, OtherIsConst> const& other)
: m_node(other.m_node)
: node_(other.node_)
{
}
LockFreeStackIterator&
operator=(NodePtr node)
{
m_node = node;
node_ = node;
return static_cast<LockFreeStackIterator&>(*this);
}
LockFreeStackIterator&
operator++()
{
m_node = m_node->m_next.load();
node_ = node_->next_.load();
return static_cast<LockFreeStackIterator&>(*this);
}
@@ -54,14 +54,14 @@ public:
operator++(int)
{
LockFreeStackIterator result(*this);
m_node = m_node->m_next;
node_ = node_->next_;
return result;
}
NodePtr
node() const
{
return m_node;
return node_;
}
reference
@@ -73,11 +73,11 @@ public:
pointer
operator->() const
{
return static_cast<pointer>(m_node);
return static_cast<pointer>(node_);
}
private:
NodePtr m_node{};
NodePtr node_{};
};
//------------------------------------------------------------------------------
@@ -121,11 +121,11 @@ public:
class Node
{
public:
Node() : m_next(nullptr)
Node() : next_(nullptr)
{
}
explicit Node(Node* next) : m_next(next)
explicit Node(Node* next) : next_(next)
{
}
@@ -139,7 +139,7 @@ public:
template <class Container, bool IsConst>
friend class LockFreeStackIterator;
std::atomic<Node*> m_next;
std::atomic<Node*> next_;
};
public:
@@ -153,7 +153,7 @@ public:
using iterator = LockFreeStackIterator<LockFreeStack<Element, Tag>, false>;
using const_iterator = LockFreeStackIterator<LockFreeStack<Element, Tag>, true>;
LockFreeStack() : m_end(nullptr), m_head(&m_end)
LockFreeStack() : end_(nullptr), head_(&end_)
{
}
@@ -165,7 +165,7 @@ public:
[[nodiscard]] bool
empty() const
{
return m_head.load() == &m_end;
return head_.load() == &end_;
}
/** Push a node onto the stack.
@@ -181,16 +181,16 @@ public:
*/
// VFALCO NOTE Fix this, shouldn't it be a reference like intrusive list?
bool
push_front(Node* node)
pushFront(Node* node)
{
bool first = false;
Node* old_head = m_head.load(std::memory_order_relaxed);
Node* oldHead = head_.load(std::memory_order_relaxed);
do
{
first = (old_head == &m_end);
node->m_next = old_head;
} while (!m_head.compare_exchange_strong(
old_head, node, std::memory_order_release, std::memory_order_relaxed));
first = (oldHead == &end_);
node->next_ = oldHead;
} while (!head_.compare_exchange_strong(
oldHead, node, std::memory_order_release, std::memory_order_relaxed));
return first;
}
@@ -204,17 +204,17 @@ public:
was empty.
*/
Element*
pop_front()
popFront()
{
Node* node = m_head.load();
Node* new_head = nullptr;
Node* node = head_.load();
Node* newHead = nullptr;
do
{
if (node == &m_end)
if (node == &end_)
return nullptr;
new_head = node->m_next.load();
} while (!m_head.compare_exchange_strong(
node, new_head, std::memory_order_release, std::memory_order_relaxed));
newHead = node->next_.load();
} while (!head_.compare_exchange_strong(
node, newHead, std::memory_order_release, std::memory_order_relaxed));
return static_cast<Element*>(node);
}
@@ -228,43 +228,43 @@ public:
iterator
begin()
{
return iterator(m_head.load());
return iterator(head_.load());
}
iterator
end()
{
return iterator(&m_end);
return iterator(&end_);
}
[[nodiscard]] const_iterator
begin() const
{
return const_iterator(m_head.load());
return const_iterator(head_.load());
}
[[nodiscard]] const_iterator
end() const
{
return const_iterator(&m_end);
return const_iterator(&end_);
}
[[nodiscard]] const_iterator
cbegin() const
{
return const_iterator(m_head.load());
return const_iterator(head_.load());
}
[[nodiscard]] const_iterator
cend() const
{
return const_iterator(&m_end);
return const_iterator(&end_);
}
/** @} */
private:
Node m_end;
std::atomic<Node*> m_head;
Node end_;
std::atomic<Node*> head_;
};
} // namespace beast

View File

@@ -24,7 +24,7 @@ namespace detail {
template <class T>
/*constexpr*/
inline void
reverse_bytes(T& t)
reverseBytes(T& t)
{
unsigned char* bytes =
static_cast<unsigned char*>(std::memmove(std::addressof(t), std::addressof(t), sizeof(T)));
@@ -35,14 +35,14 @@ reverse_bytes(T& t)
template <class T>
/*constexpr*/
inline void
maybe_reverse_bytes(T& t, std::false_type)
maybeReverseBytes(T& t, std::false_type)
{
}
template <class T>
/*constexpr*/
inline void
maybe_reverse_bytes(T& t, std::true_type)
maybeReverseBytes(T& t, std::true_type)
{
reverse_bytes(t);
}
@@ -50,15 +50,15 @@ maybe_reverse_bytes(T& t, std::true_type)
template <class T, class Hasher>
/*constexpr*/
inline void
maybe_reverse_bytes(T& t, Hasher&)
maybeReverseBytes(T& t, Hasher&)
{
maybe_reverse_bytes(
t, std::integral_constant<bool, Hasher::endian != boost::endian::order::native>{});
maybeReverseBytes(
t, std::integral_constant<bool, Hasher::kENDIAN != boost::endian::order::native>{});
}
} // namespace detail
// is_uniquely_represented<T>
// IsUniquelyRepresented<T>
// A type T is contiguously hashable if for all combinations of two values of
// a type, say x and y, if x == y, then it must also be true that
@@ -66,78 +66,78 @@ maybe_reverse_bytes(T& t, Hasher&)
// then x and y have the same bit pattern representation.
template <class T>
struct is_uniquely_represented
struct IsUniquelyRepresented
: public std::integral_constant<
bool,
std::is_integral_v<T> || std::is_enum_v<T> || std::is_pointer_v<T>>
{
explicit is_uniquely_represented() = default;
explicit IsUniquelyRepresented() = default;
};
template <class T>
struct is_uniquely_represented<T const> : public is_uniquely_represented<T>
struct IsUniquelyRepresented<T const> : public IsUniquelyRepresented<T>
{
explicit is_uniquely_represented() = default;
explicit IsUniquelyRepresented() = default;
};
template <class T>
struct is_uniquely_represented<T volatile> : public is_uniquely_represented<T>
struct IsUniquelyRepresented<T volatile> : public IsUniquelyRepresented<T>
{
explicit is_uniquely_represented() = default;
explicit IsUniquelyRepresented() = default;
};
template <class T>
struct is_uniquely_represented<T const volatile> : public is_uniquely_represented<T>
struct IsUniquelyRepresented<T const volatile> : public IsUniquelyRepresented<T>
{
explicit is_uniquely_represented() = default;
explicit IsUniquelyRepresented() = default;
};
// is_uniquely_represented<std::pair<T, U>>
// IsUniquelyRepresented<std::pair<T, U>>
template <class T, class U>
struct is_uniquely_represented<std::pair<T, U>>
struct IsUniquelyRepresented<std::pair<T, U>>
: public std::integral_constant<
bool,
is_uniquely_represented<T>::value && is_uniquely_represented<U>::value &&
IsUniquelyRepresented<T>::value && IsUniquelyRepresented<U>::value &&
sizeof(T) + sizeof(U) == sizeof(std::pair<T, U>)>
{
explicit is_uniquely_represented() = default;
explicit IsUniquelyRepresented() = default;
};
// is_uniquely_represented<std::tuple<T...>>
// IsUniquelyRepresented<std::tuple<T...>>
template <class... T>
struct is_uniquely_represented<std::tuple<T...>>
struct IsUniquelyRepresented<std::tuple<T...>>
: public std::integral_constant<
bool,
std::conjunction_v<is_uniquely_represented<T>...> &&
std::conjunction_v<IsUniquelyRepresented<T>...> &&
sizeof(std::tuple<T...>) == (sizeof(T) + ...)>
{
explicit is_uniquely_represented() = default;
explicit IsUniquelyRepresented() = default;
};
// is_uniquely_represented<T[N]>
// IsUniquelyRepresented<T[N]>
template <class T, std::size_t N>
struct is_uniquely_represented<T[N]> : public is_uniquely_represented<T>
struct IsUniquelyRepresented<T[N]> : public IsUniquelyRepresented<T>
{
explicit is_uniquely_represented() = default;
explicit IsUniquelyRepresented() = default;
};
// is_uniquely_represented<std::array<T, N>>
// IsUniquelyRepresented<std::array<T, N>>
template <class T, std::size_t N>
struct is_uniquely_represented<std::array<T, N>>
struct IsUniquelyRepresented<std::array<T, N>>
: public std::integral_constant<
bool,
is_uniquely_represented<T>::value && sizeof(T) * N == sizeof(std::array<T, N>)>
IsUniquelyRepresented<T>::value && sizeof(T) * N == sizeof(std::array<T, N>)>
{
explicit is_uniquely_represented() = default;
explicit IsUniquelyRepresented() = default;
};
/** Metafunction returning `true` if the type can be hashed in one call.
For `is_contiguously_hashable<T>::value` to be true, then for every
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.
@@ -150,23 +150,23 @@ struct is_uniquely_represented<std::array<T, N>>
*/
/** @{ */
template <class T, class HashAlgorithm>
struct is_contiguously_hashable
struct IsContiguouslyHashable
: public std::integral_constant<
bool,
is_uniquely_represented<T>::value &&
(sizeof(T) == 1 || HashAlgorithm::endian == boost::endian::order::native)>
IsUniquelyRepresented<T>::value &&
(sizeof(T) == 1 || HashAlgorithm::kENDIAN == boost::endian::order::native)>
{
explicit is_contiguously_hashable() = default;
explicit IsContiguouslyHashable() = default;
};
template <class T, std::size_t N, class HashAlgorithm>
struct is_contiguously_hashable<T[N], HashAlgorithm>
struct IsContiguouslyHashable<T[N], HashAlgorithm>
: public std::integral_constant<
bool,
is_uniquely_represented<T[N]>::value &&
IsUniquelyRepresented<T[N]>::value &&
(sizeof(T) == 1 || HashAlgorithm::endian == boost::endian::order::native)>
{
explicit is_contiguously_hashable() = default;
explicit IsContiguouslyHashable() = default;
};
/** @} */
@@ -200,7 +200,7 @@ struct is_contiguously_hashable<T[N], HashAlgorithm>
// scalars
template <class Hasher, class T>
inline std::enable_if_t<is_contiguously_hashable<T, Hasher>::value>
inline std::enable_if_t<IsContiguouslyHashable<T, Hasher>::value>
hash_append(Hasher& h, T const& t) noexcept
{
// NOLINTNEXTLINE(bugprone-sizeof-expression)
@@ -209,11 +209,11 @@ hash_append(Hasher& h, T const& t) noexcept
template <class Hasher, class T>
inline std::enable_if_t<
!is_contiguously_hashable<T, Hasher>::value &&
!IsContiguouslyHashable<T, Hasher>::value &&
(std::is_integral_v<T> || std::is_pointer_v<T> || std::is_enum_v<T>)>
hash_append(Hasher& h, T t) noexcept
{
detail::reverse_bytes(t);
detail::reverseBytes(t);
h(std::addressof(t), sizeof(t));
}
@@ -223,7 +223,7 @@ hash_append(Hasher& h, T t) noexcept
{
if (t == 0)
t = 0;
detail::maybe_reverse_bytes(t, h);
detail::maybeReverseBytes(t, h);
h(&t, sizeof(t));
}
@@ -232,42 +232,42 @@ inline void
hash_append(Hasher& h, std::nullptr_t) noexcept
{
void const* p = nullptr;
detail::maybe_reverse_bytes(p, h);
detail::maybeReverseBytes(p, h);
h(&p, sizeof(p));
}
// Forward declarations for ADL purposes
template <class Hasher, class T, std::size_t N>
std::enable_if_t<!is_contiguously_hashable<T, Hasher>::value>
std::enable_if_t<!IsContiguouslyHashable<T, Hasher>::value>
hash_append(Hasher& h, T (&a)[N]) noexcept;
template <class Hasher, class CharT, class Traits, class Alloc>
std::enable_if_t<!is_contiguously_hashable<CharT, Hasher>::value>
std::enable_if_t<!IsContiguouslyHashable<CharT, Hasher>::value>
hash_append(Hasher& h, std::basic_string<CharT, Traits, Alloc> const& s) noexcept;
template <class Hasher, class CharT, class Traits, class Alloc>
std::enable_if_t<is_contiguously_hashable<CharT, Hasher>::value>
std::enable_if_t<IsContiguouslyHashable<CharT, Hasher>::value>
hash_append(Hasher& h, std::basic_string<CharT, Traits, Alloc> const& s) noexcept;
template <class Hasher, class T, class U>
std::enable_if_t<!is_contiguously_hashable<std::pair<T, U>, Hasher>::value>
std::enable_if_t<!IsContiguouslyHashable<std::pair<T, U>, Hasher>::value>
hash_append(Hasher& h, std::pair<T, U> const& p) noexcept;
template <class Hasher, class T, class Alloc>
std::enable_if_t<!is_contiguously_hashable<T, Hasher>::value>
std::enable_if_t<!IsContiguouslyHashable<T, Hasher>::value>
hash_append(Hasher& h, std::vector<T, Alloc> const& v) noexcept;
template <class Hasher, class T, class Alloc>
std::enable_if_t<is_contiguously_hashable<T, Hasher>::value>
std::enable_if_t<IsContiguouslyHashable<T, Hasher>::value>
hash_append(Hasher& h, std::vector<T, Alloc> const& v) noexcept;
template <class Hasher, class T, std::size_t N>
std::enable_if_t<!is_contiguously_hashable<std::array<T, N>, Hasher>::value>
std::enable_if_t<!IsContiguouslyHashable<std::array<T, N>, Hasher>::value>
hash_append(Hasher& h, std::array<T, N> const& a) noexcept;
template <class Hasher, class... T>
std::enable_if_t<!is_contiguously_hashable<std::tuple<T...>, Hasher>::value>
std::enable_if_t<!IsContiguouslyHashable<std::tuple<T...>, Hasher>::value>
hash_append(Hasher& h, std::tuple<T...> const& t) noexcept;
template <class Hasher, class Key, class T, class Hash, class Pred, class Alloc>
@@ -279,10 +279,10 @@ void
hash_append(Hasher& h, std::unordered_set<Key, Hash, Pred, Alloc> const& s);
template <class Hasher, class Key, class Compare, class Alloc>
std::enable_if_t<!is_contiguously_hashable<Key, Hasher>::value>
std::enable_if_t<!IsContiguouslyHashable<Key, Hasher>::value>
hash_append(Hasher& h, boost::container::flat_set<Key, Compare, Alloc> const& v) noexcept;
template <class Hasher, class Key, class Compare, class Alloc>
std::enable_if_t<is_contiguously_hashable<Key, Hasher>::value>
std::enable_if_t<IsContiguouslyHashable<Key, Hasher>::value>
hash_append(Hasher& h, boost::container::flat_set<Key, Compare, Alloc> const& v) noexcept;
template <class Hasher, class T0, class T1, class... T>
void
@@ -291,7 +291,7 @@ hash_append(Hasher& h, T0 const& t0, T1 const& t1, T const&... t) noexcept;
// c-array
template <class Hasher, class T, std::size_t N>
std::enable_if_t<!is_contiguously_hashable<T, Hasher>::value>
std::enable_if_t<!IsContiguouslyHashable<T, Hasher>::value>
hash_append(Hasher& h, T (&a)[N]) noexcept
{
for (auto const& t : a)
@@ -301,7 +301,7 @@ hash_append(Hasher& h, T (&a)[N]) noexcept
// basic_string
template <class Hasher, class CharT, class Traits, class Alloc>
inline std::enable_if_t<!is_contiguously_hashable<CharT, Hasher>::value>
inline std::enable_if_t<!IsContiguouslyHashable<CharT, Hasher>::value>
hash_append(Hasher& h, std::basic_string<CharT, Traits, Alloc> const& s) noexcept
{
for (auto c : s)
@@ -310,7 +310,7 @@ hash_append(Hasher& h, std::basic_string<CharT, Traits, Alloc> const& s) noexcep
}
template <class Hasher, class CharT, class Traits, class Alloc>
inline std::enable_if_t<is_contiguously_hashable<CharT, Hasher>::value>
inline std::enable_if_t<IsContiguouslyHashable<CharT, Hasher>::value>
hash_append(Hasher& h, std::basic_string<CharT, Traits, Alloc> const& s) noexcept
{
h(s.data(), s.size() * sizeof(CharT));
@@ -320,7 +320,7 @@ hash_append(Hasher& h, std::basic_string<CharT, Traits, Alloc> const& s) noexcep
// pair
template <class Hasher, class T, class U>
inline std::enable_if_t<!is_contiguously_hashable<std::pair<T, U>, Hasher>::value>
inline std::enable_if_t<!IsContiguouslyHashable<std::pair<T, U>, Hasher>::value>
hash_append(Hasher& h, std::pair<T, U> const& p) noexcept
{
hash_append(h, p.first, p.second);
@@ -329,7 +329,7 @@ hash_append(Hasher& h, std::pair<T, U> const& p) noexcept
// vector
template <class Hasher, class T, class Alloc>
inline std::enable_if_t<!is_contiguously_hashable<T, Hasher>::value>
inline std::enable_if_t<!IsContiguouslyHashable<T, Hasher>::value>
hash_append(Hasher& h, std::vector<T, Alloc> const& v) noexcept
{
for (auto const& t : v)
@@ -338,7 +338,7 @@ hash_append(Hasher& h, std::vector<T, Alloc> const& v) noexcept
}
template <class Hasher, class T, class Alloc>
inline std::enable_if_t<is_contiguously_hashable<T, Hasher>::value>
inline std::enable_if_t<IsContiguouslyHashable<T, Hasher>::value>
hash_append(Hasher& h, std::vector<T, Alloc> const& v) noexcept
{
h(v.data(), v.size() * sizeof(T));
@@ -348,7 +348,7 @@ hash_append(Hasher& h, std::vector<T, Alloc> const& v) noexcept
// array
template <class Hasher, class T, std::size_t N>
std::enable_if_t<!is_contiguously_hashable<std::array<T, N>, Hasher>::value>
std::enable_if_t<!IsContiguouslyHashable<std::array<T, N>, Hasher>::value>
hash_append(Hasher& h, std::array<T, N> const& a) noexcept
{
for (auto const& t : a)
@@ -356,14 +356,14 @@ hash_append(Hasher& h, std::array<T, N> const& a) noexcept
}
template <class Hasher, class Key, class Compare, class Alloc>
std::enable_if_t<!is_contiguously_hashable<Key, Hasher>::value>
std::enable_if_t<!IsContiguouslyHashable<Key, Hasher>::value>
hash_append(Hasher& h, boost::container::flat_set<Key, Compare, Alloc> const& v) noexcept
{
for (auto const& t : v)
hash_append(h, t);
}
template <class Hasher, class Key, class Compare, class Alloc>
std::enable_if_t<is_contiguously_hashable<Key, Hasher>::value>
std::enable_if_t<IsContiguouslyHashable<Key, Hasher>::value>
hash_append(Hasher& h, boost::container::flat_set<Key, Compare, Alloc> const& v) noexcept
{
h(&(v.begin()), v.size() * sizeof(Key));
@@ -373,13 +373,13 @@ hash_append(Hasher& h, boost::container::flat_set<Key, Compare, Alloc> const& v)
namespace detail {
inline void
for_each_item(...) noexcept
forEachItem(...) noexcept
{
}
template <class Hasher, class T>
inline int
hash_one(Hasher& h, T const& t) noexcept
hashOne(Hasher& h, T const& t) noexcept
{
hash_append(h, t);
return 0;
@@ -395,7 +395,7 @@ tuple_hash(Hasher& h, std::tuple<T...> const& t, std::index_sequence<I...>) noex
} // namespace detail
template <class Hasher, class... T>
inline std::enable_if_t<!is_contiguously_hashable<std::tuple<T...>, Hasher>::value>
inline std::enable_if_t<!IsContiguouslyHashable<std::tuple<T...>, Hasher>::value>
hash_append(Hasher& h, std::tuple<T...> const& t) noexcept
{
detail::tuple_hash(h, t, std::index_sequence_for<T...>{});

View File

@@ -6,10 +6,10 @@
namespace beast {
// Universal hash function
template <class Hasher = xxhasher>
struct uhash
template <class Hasher = Xxhasher>
struct Uhash
{
uhash() = default;
Uhash() = default;
using result_type = typename Hasher::result_type;

View File

@@ -12,7 +12,7 @@
namespace beast {
class xxhasher
class Xxhasher
{
public:
using result_type = std::size_t;
@@ -21,9 +21,9 @@ private:
static_assert(sizeof(std::size_t) == 8, "requires 64-bit std::size_t");
// Have an internal buffer to avoid the streaming API
// A 64-byte buffer should to be big enough for us
static constexpr std::size_t INTERNAL_BUFFER_SIZE = 64;
static constexpr std::size_t kINTERNAL_BUFFER_SIZE = 64;
alignas(64) std::array<std::uint8_t, INTERNAL_BUFFER_SIZE> buffer_{};
alignas(64) std::array<std::uint8_t, kINTERNAL_BUFFER_SIZE> buffer_{};
std::span<std::uint8_t> readBuffer_;
std::span<std::uint8_t> writeBuffer_;
@@ -102,18 +102,18 @@ private:
}
public:
static constexpr auto const endian = boost::endian::order::native;
static constexpr auto const kENDIAN = boost::endian::order::native;
xxhasher(xxhasher const&) = delete;
xxhasher&
operator=(xxhasher const&) = delete;
Xxhasher(Xxhasher const&) = delete;
Xxhasher&
operator=(Xxhasher const&) = delete;
xxhasher()
Xxhasher()
{
resetBuffers();
}
~xxhasher() noexcept
~Xxhasher() noexcept
{
if (state_ != nullptr)
{
@@ -122,13 +122,13 @@ public:
}
template <class Seed, std::enable_if_t<std::is_unsigned_v<Seed>>* = nullptr>
explicit xxhasher(Seed seed) : seed_(seed)
explicit Xxhasher(Seed seed) : seed_(seed)
{
resetBuffers();
}
template <class Seed, std::enable_if_t<std::is_unsigned_v<Seed>>* = nullptr>
xxhasher(Seed seed, Seed) : seed_(seed)
Xxhasher(Seed seed, Seed) : seed_(seed)
{
resetBuffers();
}

View File

@@ -42,13 +42,13 @@ public:
/** @{ */
template <class Handler>
Hook
make_hook(Handler handler)
makeHook(Handler handler)
{
return make_hook(HookImpl::HandlerType(handler));
return makeHook(HookImpl::HandlerType(handler));
}
virtual Hook
make_hook(HookImpl::HandlerType const& handler) = 0;
makeHook(HookImpl::HandlerType const& handler) = 0;
/** @} */
/** Create a counter with the specified name.
@@ -56,14 +56,14 @@ public:
*/
/** @{ */
virtual Counter
make_counter(std::string const& name) = 0;
makeCounter(std::string const& name) = 0;
Counter
make_counter(std::string const& prefix, std::string const& name)
makeCounter(std::string const& prefix, std::string const& name)
{
if (prefix.empty())
return make_counter(name);
return make_counter(prefix + "." + name);
return makeCounter(name);
return makeCounter(prefix + "." + name);
}
/** @} */
@@ -72,14 +72,14 @@ public:
*/
/** @{ */
virtual Event
make_event(std::string const& name) = 0;
makeEvent(std::string const& name) = 0;
Event
make_event(std::string const& prefix, std::string const& name)
makeEvent(std::string const& prefix, std::string const& name)
{
if (prefix.empty())
return make_event(name);
return make_event(prefix + "." + name);
return makeEvent(name);
return makeEvent(prefix + "." + name);
}
/** @} */
@@ -88,14 +88,14 @@ public:
*/
/** @{ */
virtual Gauge
make_gauge(std::string const& name) = 0;
makeGauge(std::string const& name) = 0;
Gauge
make_gauge(std::string const& prefix, std::string const& name)
makeGauge(std::string const& prefix, std::string const& name)
{
if (prefix.empty())
return make_gauge(name);
return make_gauge(prefix + "." + name);
return makeGauge(name);
return makeGauge(prefix + "." + name);
}
/** @} */
@@ -104,14 +104,14 @@ public:
*/
/** @{ */
virtual Meter
make_meter(std::string const& name) = 0;
makeMeter(std::string const& name) = 0;
Meter
make_meter(std::string const& prefix, std::string const& name)
makeMeter(std::string const& prefix, std::string const& name)
{
if (prefix.empty())
return make_meter(name);
return make_meter(prefix + "." + name);
return makeMeter(name);
return makeMeter(prefix + "." + name);
}
/** @} */
};

View File

@@ -29,7 +29,7 @@ public:
factory function in the Collector interface.
@see Collector.
*/
explicit Counter(std::shared_ptr<CounterImpl> const& impl) : m_impl(impl)
explicit Counter(std::shared_ptr<CounterImpl> const& impl) : impl_(impl)
{
}
@@ -38,8 +38,8 @@ public:
void
increment(value_type amount) const
{
if (m_impl)
m_impl->increment(amount);
if (impl_)
impl_->increment(amount);
}
Counter const&
@@ -85,7 +85,7 @@ public:
}
private:
std::shared_ptr<CounterImpl> m_impl;
std::shared_ptr<CounterImpl> impl_;
};
} // namespace beast::insight

View File

@@ -31,7 +31,7 @@ public:
factory function in the Collector interface.
@see Collector.
*/
explicit Event(std::shared_ptr<EventImpl> const& impl) : m_impl(impl)
explicit Event(std::shared_ptr<EventImpl> const& impl) : impl_(impl)
{
}
@@ -41,18 +41,18 @@ public:
notify(std::chrono::duration<Rep, Period> const& value) const
{
using namespace std::chrono;
if (m_impl)
m_impl->notify(ceil<value_type>(value));
if (impl_)
impl_->notify(ceil<value_type>(value));
}
[[nodiscard]] std::shared_ptr<EventImpl> const&
impl() const
{
return m_impl;
return impl_;
}
private:
std::shared_ptr<EventImpl> m_impl;
std::shared_ptr<EventImpl> impl_;
};
} // namespace beast::insight

View File

@@ -31,7 +31,7 @@ public:
factory function in the Collector interface.
@see Collector.
*/
explicit Gauge(std::shared_ptr<GaugeImpl> const& impl) : m_impl(impl)
explicit Gauge(std::shared_ptr<GaugeImpl> const& impl) : impl_(impl)
{
}
@@ -44,8 +44,8 @@ public:
void
set(value_type value) const
{
if (m_impl)
m_impl->set(value);
if (impl_)
impl_->set(value);
}
Gauge const&
@@ -61,8 +61,8 @@ public:
void
increment(difference_type amount) const
{
if (m_impl)
m_impl->increment(amount);
if (impl_)
impl_->increment(amount);
}
Gauge const&
@@ -111,11 +111,11 @@ public:
[[nodiscard]] std::shared_ptr<GaugeImpl> const&
impl() const
{
return m_impl;
return impl_;
}
private:
std::shared_ptr<GaugeImpl> m_impl;
std::shared_ptr<GaugeImpl> impl_;
};
} // namespace beast::insight

View File

@@ -29,6 +29,6 @@ public:
/** Create a group container that uses the specified collector. */
std::unique_ptr<Groups>
make_Groups(Collector::ptr const& collector);
makeGroups(Collector::ptr const& collector);
} // namespace beast::insight

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