Compare commits

...

555 Commits

Author SHA1 Message Date
Vinnie Falco
9a0e806f78 Set version to 0.26.1 2014-07-28 12:05:01 -07:00
Vinnie Falco
20c9632996 Enable asynchronous handling of HTTP-RPC (RIPD-390)
* Activate async code path
* Tidy up HTTP server code
* Use shared_ptr in HTTP server
* Remove check for unspecified IP
* Remove hairtrigger
* Fix missing HTTP authorization check
* Fix multisocket flags in RPC-HTTP server
* Fix authorization failure when no credentials required
* Addresses RIPD-159, RIPD-161, RIPD-390
2014-07-28 12:05:01 -07:00
Vinnie Falco
65a628ca88 Add HTTPHeaders::build_map 2014-07-28 12:05:00 -07:00
Vinnie Falco
d82dbba096 Make bind_handler variadic ctor explicit 2014-07-28 12:05:00 -07:00
Nik Bougalis
704d7451a0 Fix auth handling during OfferCreate (RIPD-414) 2014-07-25 11:42:42 -07:00
Vinnie Falco
9fa5e39872 Set version to 0.26.0 2014-07-22 09:59:45 -07:00
Vinnie Falco
ace53fa405 Set version to 0.26.0-rc2 2014-07-21 10:39:48 -07:00
Vinnie Falco
3c06980107 Merge branch 'release' into develop 2014-07-21 10:25:23 -07:00
Vinnie Falco
1f26fbb5af Set version to 0.26.0-rc1 2014-07-21 10:00:16 -07:00
Howard Hinnant
84c6622122 Fix bugs, typo in SHAMapNodeID 2014-07-18 17:45:51 -07:00
Miguel Portilla
63f099f2f6 Fix book_offers limit parameter (RIPD-295)
Conflicts:
	src/ripple/module/app/misc/NetworkOPs.cpp
2014-07-18 10:37:45 -07:00
Nicholas Dudfield
373ce72984 Update freeze tests
* Conditionally skip freeze enforcement tests
* Honour remote.fee_cushion setting
* Workaround ripple-lib regression
* Don't use mocha features from wrong version
2014-07-18 10:35:06 -07:00
JoelKatz
4cf29455e4 Freeze flags: (RIPD-394)
* Define all flags
 * Set/clear bits in transactors
 * Frozen line counts towards reserve, is non-default
 * Report trust line state
2014-07-18 10:35:06 -07:00
David Schwartz
07db5d497c Remove SHAMapNodeID from SHAMapTreeNode (RIPD-347)
This resolves the "right data, wrong ID" issue in the
tree node cache.
2014-07-18 10:35:06 -07:00
JoelKatz
f1bb0afc4e Improve transaction fee and execution logic (RIPD-323):
* tecINSUFF_FEE if balance doesn't cover fee
* Ensure transaction recovery is deterministic
* Reduce transaction retries
2014-07-18 10:35:06 -07:00
Vinnie Falco
d791fe3013 Fix msvc static initialization in SHAMapNodeID 2014-07-17 20:05:39 -07:00
Miguel Portilla
c16e22a5c6 Fix book_offers limit parameter (RIPD-295) 2014-07-17 18:01:20 -07:00
Miguel Portilla
db7a720445 Fix static initializers in RippleSSLContext (RIPD-375) 2014-07-17 18:01:19 -07:00
Miguel Portilla
6c09a02099 Workaround gcc bug with static_initializer default ctor 2014-07-17 18:00:43 -07:00
Howard Hinnant
1b3356cafd Remove calls to SHAMapNode::getID (RIPD-347):
Calls in SHAMap::getCache and SHAMap::canonicalize are
purposefully left in place at this time (to be removed
later).
2014-07-17 15:58:03 -07:00
Scott Schurr
5869902f2c Tidy up Resource::Manager (RIPD-362):
* Style improvements
* More documentation
2014-07-17 14:18:18 -07:00
Howard Hinnant
28898031f0 Eliminate spurious SHAMap::getFetchPack failure (RIPD-379) 2014-07-17 10:38:07 -07:00
Vinnie Falco
1ce0f94638 Define OPENSSL_NO_SSL2 2014-07-17 10:18:37 -07:00
Vinnie Falco
f876ad973f Fix static_initializer: …
* Prevents double construction, invalid access
* Unit test works on MSVC and non MSVC
2014-07-16 16:43:17 -07:00
Tom Ritchford
6014b13234 Use Books in Ledger. 2014-07-15 21:16:42 -07:00
Vinnie Falco
3e9c702c47 Support stream composition of testcase names 2014-07-15 18:23:01 -07:00
Vinnie Falco
3ff919ccf1 Fix version to say 'rippled' 2014-07-15 13:03:40 -07:00
evhub
8dc0844c79 Fix VSProject item sorting (again)
Conflicts:
	src/beast/site_scons/site_tools/VSProject.py
2014-07-15 12:51:57 -07:00
David Schwartz
a2764b68ca Rate-limit SSL client renegotiation (RIPD-360) 2014-07-14 10:42:29 -07:00
Tom Ritchford
bbbae072ea Simplify initialization of Pathfinder using C++11 constructs. 2014-07-14 10:04:27 -07:00
evhub
b4735b5931 Fix VSProject item sorting:
* Use object type in the sort key
* Call _key recursively over containers
* Prevent passing of iterators to xsorted
* Fix VSProject generator with new sorting
2014-07-14 10:04:07 -07:00
Tom Ritchford
418638ad16 Serialization code improvements:
* Add generics to eliminate duplicate code in STHash
* Use generics in Serializer and callers
2014-07-11 12:00:49 -07:00
Scott Schurr
9fb09d3109 Pass and use time_point in DecayingSample ctor (RIPD-359)
Switches a number of places in Resource::Logic to use abstract_clock::now()
which returns a time_point.  Unfortunately Resource::Logic tracks time
locally also, but with ints, not time_point.  So Resource::Logic uses a
delicate mix of abstract_clock::now() and abstract_clock::elapsed() with
this commit.  That inconsistency could be addressed in a second commit.
2014-07-11 12:00:39 -07:00
Tom Ritchford
d7e08f96a5 Various tidying:
* Fix unused variable warnings.
* Clean unused items from TER.
* Improvement to LES use of shared_ptr.
2014-07-10 15:11:33 -07:00
JoelKatz
4d49d272eb Fix account_tx resume (RIPD-314) 2014-07-10 15:11:33 -07:00
JoelKatz
faa6890950 Find 'sabfd' paths (RIPD-335)
This permits USD/GW1 to be bridged to USD/GW2 by BTC/GW3 or
USD/GW1 to be bridged to BTC/GW2 by CNY/GW3.
2014-07-10 15:11:33 -07:00
David Schwartz
9c390f6da4 Impose a local limit on path lengths (RIPD-350) 2014-07-10 15:09:06 -07:00
Scott Schurr
6842277977 Add documentation for ledger entries (RIPD-361) 2014-07-10 15:08:07 -07:00
Mark Travis
ddf68d464d Set version to 0.25.2 2014-07-07 12:41:46 -07:00
JoelKatz
b2f19e8dc6 Find 'sabfd' paths
This permits USD/GW1 to be bridged to USD/GW2 by BTC/GW3 or
USD/GW1 to be bridged to BTC/GW2 by CNY/GW3. See RIPD-335.
2014-07-07 12:41:46 -07:00
David Schwartz
5714b42975 Impose a local limit on path lengths 2014-07-07 11:42:24 -07:00
David Schwartz
c4e9c49c10 Set version to 0.25.2-rc2 2014-07-07 11:33:26 -07:00
Mark Travis
9210efb051 In JSON, output unprintable currency codes as hex 2014-07-07 11:33:26 -07:00
Tom Ritchford
b9f1b05625 Use swapWith to save CPU; edit comment. 2014-07-07 11:33:26 -07:00
sublimator
828c2e3c71 Restore checkpointed ledger under all paths in PathFind. 2014-07-07 11:33:12 -07:00
Nik Bougalis
10150a7352 Patch Boost to suppress warnings on clang 2014-07-06 15:17:58 -07:00
Scott Schurr
baaa45f8c7 SHAMap Documentation 2014-07-06 14:57:59 -07:00
Tom Ritchford
322af30d6a Pathfinding Documentation 2014-07-06 14:57:59 -07:00
Tom Ritchford
206efbf30d Rename RippleAsset to Issue and RippleBook to Book:
* Split STAmount out of SerializedTypes.h
* New concept of "Issue consistency": when either both or neither of its
  currency and account are XRP.
* Stop checking for consistency of Issue in its constructor.
* Clarification of mIsNative logic in STAmount.
* Usual cleanups.
2014-07-06 14:57:59 -07:00
Tom Ritchford
a96dee85d2 Remove recursions from computeLiquidity 2014-07-06 14:57:58 -07:00
Vinnie Falco
d307568cbc Update rocksdb unity file 2014-07-03 17:49:17 -07:00
Vinnie Falco
0ee27b143c Merge commit '7bfb4a9ba5a2822f7d9ef7122b1388aea4be9404' as 'src/rocksdb' 2014-07-03 17:49:00 -07:00
Vinnie Falco
7bfb4a9ba5 Squashed 'src/rocksdb/' content from commit 78b8a7d
git-subtree-dir: src/rocksdb
git-subtree-split: 78b8a7d908
2014-07-03 17:49:00 -07:00
Vinnie Falco
110c73fc8d Remove rockdb subtree 2014-07-03 17:43:48 -07:00
Vinnie Falco
424d9b8385 Add preliminary Structured Overlay docs 2014-07-03 14:34:38 -07:00
Vinnie Falco
1b48ccc868 Fix base log partition severity 2014-07-03 11:57:14 -07:00
Howard Hinnant
fac82204b6 Remove boost::hash_value() overloads.
This addresses https://ripplelabs.atlassian.net/browse/RIPD-102
2014-07-02 15:33:11 -07:00
David Schwartz
61f114e655 Cleanup confusion of ledger base versus ledger header
The "ledger header" is the chunk of data that hashes to the
ledger's hash. It contains the sequence number, parent hash,
hash of the previous ledger, hash of the root node of the
state tree, and so on.

The term "ledger base" refers to a particular type of query
and response used in the ledger fetch process that includes
the ledger header but may also contain other information
such as the root node of the state tree.
2014-07-02 15:33:10 -07:00
MarkusTeufelberger
24410bf1bb Update Sconstruct 2014-07-01 19:12:47 -07:00
Vinnie Falco
aa24969eee Add README.md for ledger process 2014-07-01 12:42:41 -07:00
David Schwartz
a5297d13c4 Add new memo restrictions 2014-07-01 12:13:47 -07:00
David Schwartz
b06bdb83cb Fix a case where we put an extra node in the SHAMapDiff 2014-07-01 12:13:13 -07:00
David Schwartz
d06092212f Tighten up some serialization checks 2014-06-30 16:53:38 -07:00
David Schwartz
914778eae1 In JSON, output unprintable currency codes as hex 2014-06-30 16:40:53 -07:00
Nicholas Dudfield
e14c700c60 New integration tests:
* New tests for autobridging and freeze
* Discrepancy detection tests
* Don't let Mocha suppress load time errors
2014-06-28 18:27:33 -07:00
wltsmrz
0848e348bb Update ripple-lib integration tests 2014-06-28 13:17:31 -07:00
Vinnie Falco
3d5ae42660 Structured Overlay support:
* Add Peer Protocol detector
* Add RIPPLE_SINGLE_IO_SERVICE_THREAD setting
* Preliminary HTTP header parsing logic (disabled)
2014-06-26 18:24:50 -07:00
Vinnie Falco
f207b6b4c9 Improvements to HTTP parsing 2014-06-26 17:41:12 -07:00
David Schwartz
ed2c5078ad Tighten up some serialization checks 2014-06-26 17:16:34 -07:00
sublimator
aec792f5b8 Restore checkpointed ledger under all paths in PathFind. 2014-06-26 17:16:34 -07:00
Nik Bougalis
17d64de3d5 During playback close ledger before accepting 2014-06-26 17:16:34 -07:00
Tom Ritchford
f6bea08535 Update state during pathfinding 2014-06-26 17:16:33 -07:00
Tom Ritchford
feab6c39b3 New types Account, Currency, Directory:
* New tagged uint types.
* Extract to_string functions from header to hide dependencies.
* Include what you use and C++11 for cleanups.
2014-06-26 17:16:30 -07:00
Nik Bougalis
e999c76882 Autobridging:
* Remove legacy OfferCreate transactor
* Misc. cleanups on LedgerEntrySet
* Fix a subtle bug with arithmetic operations on Quality
* Sanity check offers after taking
2014-06-26 12:03:52 -07:00
Miguel Portilla
686cc599a2 Add ASIO strand to StatsDCollector 2014-06-26 12:03:51 -07:00
Vinnie Falco
92983556a0 Fix bug in VSProject when no LIBPATH in env 2014-06-26 12:03:51 -07:00
Scott Schurr
837872c3f3 Move static treeNodeCache from SHAMap to the Application
These changes address two JIRA issues:

 - 291 unittest reported leaked objects
 - 292 SHAMap::treeNodeCache should be a dependency injection

The treeNodeCache was a static member of SHAMap.  It's now a
non-static member of the Application accessed through
getTreeNodeCache().  That addressed JIRA 291

The SHAMap constructors were adjusted so the treeNodeCache is
passed in to the constructor.  That addresses JIRA 292,  It required
that any code constructing a SHAMap needed to be edited to pass
the new parameter to the constructed SHAMap.

In the mean time, SHAMap was examined for dead/unused code and
interfaces that could be made private.  Dead and unused interfaces
were removed and methods that could be private were made private.
2014-06-26 11:10:51 -07:00
Tom Ritchford
55222dc5d1 New types Account, Currency, Directory:
* New tagged uint types.
* Extract to_string functions from header to hide dependencies.
* Include what you use and C++11 for cleanups.
2014-06-24 11:11:25 -07:00
David Schwartz
adce6ae851 Ledger loading cleanups:
* Fix close time settings for ledger load
* More info in ledger_request and inbound ledger JSON replies
2014-06-23 20:19:53 -07:00
Howard Hinnant
9dc32cb791 SHAMap refactoring:
* Rename SHAMapNode to SHAMapNodeID.
* Cleanups
2014-06-23 20:19:53 -07:00
Howard Hinnant
23dc08c925 Improve Journal logging framework:
* Allow partition log levels to be adjusted
* Cleanups
2014-06-23 20:19:53 -07:00
Vinnie Falco
488a44b88e Fix case-sensitivity for NOLOGO in booltable 2014-06-18 17:04:31 -07:00
evhub
530bdf975e Fix VSProject generation issues with SConstruct:
* Always describe the Visual Studio targets
* Prevent checking nonexistant enviro vars
* Prevent pkg-config protobuf env vars if not clang/gcc
* Don't use any pkg-config enviro vars unless clang/gcc
* Make all VSProject/config directories windows-style
* Prevent beastobjc.mm from showing up in vcxproj
* Remove duplicate \src\protobuf\src
* Consistent quoting
2014-06-18 16:41:34 -07:00
evhub
d7a6627a1f Fixes to VSProject generator:
* Canonical sorting for all platforms
* Fix incorrect path separator
* Filter predefined duplicate environment switches
2014-06-18 16:38:26 -07:00
Vinnie Falco
d6066183b9 Refactor Overlay for Structured Network support:
* Move overlay up one directory
* Add abstract_protocol_handler, message_stream
* Add peer_protocol_detector
* Tidy up some declarations
* Use strand::running_in_this_thread instead of bool
* Update README.md
* Replace protocol message read loop:
  - Process data in arbitrary size chunks
  - message_stream extracts individual messages
  - peer_protocol_detector identifies the handshake
  - abstract_protocol_handler used for dispatching messages
* Remove unused protocol message types:
  - mtACCOUNT
  - mtCONTACT
  - mtERROR
  - mtGET_ACCOUNT
  - mtGET_CONTACTS
  - mtGET_VALIDATIONS
  - mtSEARCH_TRANSACTION
  - mtUNUSED_FIELD

Conflicts:
	src/ripple/module/app/main/Application.cpp
	src/ripple/module/app/misc/NetworkOPs.cpp
	src/ripple/module/app/peers/PeerSet.cpp
2014-06-18 15:17:18 -07:00
Vinnie Falco
3e2c3ba035 Add missing beast includes 2014-06-18 14:07:18 -07:00
Tom Ritchford
e24cba8c35 Better types and more comments in RippleCalc.
* Better automatic conversions to and from tagged uint160 varints.
* Start using tagged variants of uint160 for Currency, Account.
* Comments from 2014/6/11 RippleCalc session.
2014-06-18 12:38:06 -07:00
Tom Ritchford
a23013abc1 Tidy up rpc module:
* Move directory up to ripple/module/rpc
* Use C++11 idioms and best practices
2014-06-18 12:37:53 -07:00
evhub
27a4f44de5 Process switches with regex in VSProject generator:
* Handles "DisableSpecificWarnings" switches
2014-06-16 19:01:28 -07:00
Vinnie Falco
4e07dbbefc Fix state check in PeerImp::recvHello 2014-06-16 18:14:25 -07:00
David Schwartz
dcf4ad2c21 Ledger load and ledger replay fixes:
* Stash the loaded ledger where consensus can find it.
 * When loading a ledger for startup, try the backend too
 * Apply replay transactions to a mutable snapshot
2014-06-16 17:29:11 -07:00
Nik Bougalis
04dd861fe3 Cleanup:
* Remove is_bit_set and use regular bitwise operations instead.
* Remove the function-like macro "nothing".
2014-06-16 17:29:11 -07:00
Vinnie Falco
c8ee6c6f6d Use std::thread instead of boost::thread 2014-06-16 16:18:10 -07:00
Vinnie Falco
a57e4263d7 Fix MSVC workaround in basic_seconds_clock 2014-06-16 16:18:09 -07:00
Vinnie Falco
3d58f0d941 Add static_initializer 2014-06-16 16:18:09 -07:00
Vinnie Falco
a52c9232c4 Tidy up basics module:
* Move directory up
* Remove unity includes and "include what you use"
2014-06-15 18:51:05 -07:00
Vinnie Falco
7a059c7a73 Remove ScopedPointer, ContainerDeletePolicy 2014-06-15 18:35:12 -07:00
Vinnie Falco
506910147f Tidy up includes:
* Replace boost with std equivalents:
  - bind, ref, cref, function, placeholders
* More "include what you use"
* Remove unnecessary includes
2014-06-15 18:26:50 -07:00
Vinnie Falco
cf3eb24eb0 Move nodestore to its own module 2014-06-15 12:50:44 -07:00
Vinnie Falco
d965b23b2a Add missing beast includes 2014-06-15 12:37:52 -07:00
Vinnie Falco
f660743065 Remove unused SHAMap::getItem 2014-06-13 14:00:17 -07:00
David Schwartz
4559bd9030 Improve the way we declare a close time consensus 2014-06-12 10:20:48 -07:00
David Schwartz
3ac98fb101 SyncUnorderedMap cleanup 2014-06-12 10:14:47 -07:00
David Schwartz
aff52db289 Re-use the serializer 2014-06-12 10:14:47 -07:00
David Schwartz
ea27dfe08d Find 'sbfd' paths. 2014-06-12 09:41:52 -07:00
Tom Ritchford
27620af1bf Further cleanups of RippleCalc.
* Rename many variables.
* Make most of PathState private.
* Extract out common Node::isAccount() code.
* Rename bConsumed to allLiquidityConsumed_.
* Extract out code into PathState::clear().
2014-06-09 12:57:26 -07:00
Tom Ritchford
bf116308d4 Add newer validators to validators-example.txt 2014-06-09 12:41:27 -07:00
Tom Ritchford
3fb27d98ab Clean up LookupLedger and resolve issue 278.
* Use beast::zero to resolve issue 278.
* Rename variables and simplify logic.
* Restrict to 80 columns.
2014-06-09 12:40:38 -07:00
Tom Ritchford
7e45c17730 Rename ledger_get to ledger_request. 2014-06-09 12:37:24 -07:00
Tom Ritchford
626533d4a7 Clean up RPC messages from Main 2014-06-09 12:37:23 -07:00
Tom Ritchford
39719f4c17 Rearrange branch in accordance with new practices. 2014-06-09 12:37:23 -07:00
JoelKatz
526bd88dc4 Add ledger_get RPC command to fetch a ledger from the network
Conflicts:
	Builds/VisualStudio2013/RippleD.vcxproj
	Builds/VisualStudio2013/RippleD.vcxproj.filters
	Builds/VisualStudio2013/RippleD2.vcxproj
	Builds/VisualStudio2013/RippleD2.vcxproj.filters
	src/ripple_rpc/impl/Handlers.cpp
2014-06-09 12:37:22 -07:00
Vinnie Falco
37201ecaa6 Include BeastConfig.h from the root include path 2014-06-09 12:35:16 -07:00
Vinnie Falco
02ed879837 Update VS project file 2014-06-06 07:39:55 -07:00
Vinnie Falco
8b881d3a77 Add CBase58Data::hash_append 2014-06-05 20:00:24 -07:00
Miguel Portilla
f25456ce25 Fix VSProject.py extra dot 2014-06-05 17:47:46 -07:00
mDuo13
dfb1db4ab3 Return correct error for missing pathfinding request. Fixes RIPD-293 2014-06-05 17:47:28 -07:00
Vinnie Falco
4362cb660b Replace boost::shared_ptr with std::shared_ptr 2014-06-05 13:04:23 -07:00
Vinnie Falco
1aa0749ba8 Update rocksdb unity build 2014-06-04 17:20:43 -07:00
Vinnie Falco
c7f1f6a91f RocksDB changes to support unity build:
* Remove extra definition of TotalFileSize
* Remove extra definition of ClipToRange
* Move EncodedFileMetaData out from anonymous namespace
* Move version_set Saver to its own namespace
* Move some symbols into a named namespace
* Move symbols out of anonymous namespace (prevents warning)
* Make BloomHash inline
2014-06-04 17:15:28 -07:00
Vinnie Falco
888a3fec21 Merge commit '8514b88974c71c0fa85bb154507536ee49c33458' as 'src/rocksdb' 2014-06-04 16:10:38 -07:00
Vinnie Falco
8514b88974 Squashed 'src/rocksdb/' content from commit 457bae6
git-subtree-dir: src/rocksdb
git-subtree-split: 457bae6911
2014-06-04 16:10:38 -07:00
Vinnie Falco
724ec46129 Use per-file include directories for external code subtrees:
* leveldb, hyperleveldb, rocksdb, snappy
* SConstruct OSX fix regarding OpenSSL version check
2014-06-04 13:28:43 -07:00
Vinnie Falco
4f1d1d2a8a Reorganize source file hierarchy:
* Rename unity files
* Move some modules to new subdirectories
* Remove obsolete Visual Studio project files
* Remove obsolete coding style and TODO list
2014-06-03 21:43:59 -07:00
Tom Ritchford
39a387b54c Check for openSSL version in SConstruct.
* Uses the platform specific openssl binary to detect the current version.
2014-06-02 10:56:21 -07:00
Roberto Catini
2b0034667d Add Dockerfile:
* The ports are not automatically exposed.
* No test is performed after the build.
2014-06-02 10:27:09 -07:00
Tom Ritchford
98202c56ae base_uint now compares and assigns with beast::Zero.
Conflicts:
	src/ripple/types/api/base_uint.h
	src/ripple_basics/ripple_basics.h
2014-06-02 10:15:45 -07:00
Vinnie Falco
1e06ddf13c Refactor MultiSocket:
* Variadic constructor argument list
* Tidy up sources and filenames
2014-06-02 10:07:05 -07:00
Vinnie Falco
560071bb68 Make all include paths relative to a root directory:
* Better include path support in the VSProject scons tool.
* Various manual fixes to include paths.
2014-06-02 09:16:28 -07:00
Nik Bougalis
2e49ec47a3 Revert "Ste version to 0.25.2-rc1"
This reverts commit 3f10924594.
2014-06-01 16:32:41 -07:00
Mark Travis
e70d618aff Set version to 0.25.2-rc1 2014-06-01 22:51:13 +00:00
Mark Travis
3e4cf426bd Detect paths with illegal bridging offers 2014-06-01 22:45:55 +00:00
Mark Travis
3f10924594 Ste version to 0.25.2-rc1 2014-06-01 22:35:12 +00:00
Mark Travis
f8182c335a Detect paths with illegal bridging offers 2014-06-01 01:26:11 +00:00
Vinnie Falco
1d8d6a6d68 Revert "Improve checking of library versions."
This reverts commit 69fccdf5c6.
2014-05-28 19:04:37 -07:00
Tom Ritchford
69fccdf5c6 Improve checking of library versions.
* Correctly handle openSSL version checking on Ubuntu, Debian, OS/X.
* Also check versions of openSSL, Boost, GCC and MSVC at C++ compile time.
* Get rid of over-engineered runtime CheckLibraryVersions.
2014-05-28 17:07:35 -07:00
Nik Bougalis
27e8d44a56 Autobridging:
Complete implementation of bridged offers crossings. While processing an offer
A:B we consider both the A:B order book and the combined A:XRP and XRP:B books
and pick the better offers. The net result is better liquidity and potentially
better rates.

* Rearchitect core::Taker to perform direct and bridged crossings.
* Compute bridged qualities.
* Implement a new Bridged OfferCreate transactor.
* Factor out common code from the Bridged and Direct OfferCreate transactors.
* Perform flow calculations without losing accuracy.
* Rename all transactors.
* Cleanups.
2014-05-28 16:35:03 -07:00
Vinnie Falco
72bc4ebf37 Fix VSProject generator item sort 2014-05-28 16:35:02 -07:00
Tom Ritchford
353f32e6af Fix a few warnings 2014-05-28 09:28:50 -07:00
Howard Hinnant
9bbaa9a2ae Report whether a ledger is validated:
This addresses https://ripplelabs.atlassian.net/browse/RIPD-275
Use Json::StaticString to improve performance.
Use inject_error instead of manually adding errors.
2014-05-28 09:27:22 -07:00
Nicholas Dudfield
096fcefae9 Fix clang/travis, prefer static libs when BOOST_ROOT is set. 2014-05-28 08:32:11 -07:00
Vinnie Falco
0f1e292e34 New http::client_session for making requests:
- Add 10,000 popular URL data set for unit tests
2014-05-28 08:31:45 -07:00
Vinnie Falco
195957a7cc Add ci_char_traits 2014-05-28 07:30:02 -07:00
Vinnie Falco
eb122f45f9 Tidy up includes 2014-05-28 07:29:59 -07:00
Vinnie Falco
c51ac9d6da Fix rocksdb relative include 2014-05-27 15:23:50 -07:00
Vinnie Falco
97c9d02c43 Improved SConstruct:
* Automatic source list built via directory iteration
* Build multiple toolchains and flavors simulaneously:
    - Toolchains: gcc, clang, msvc
    - Flavors: debug, release
* Documentation on aliases (top of the SConstruct file)
2014-05-27 15:23:50 -07:00
Vinnie Falco
0c06939f38 Beast SCons tools:
* Add VSProject SCons Builder
* Add Protoc SCons Builder
* Add Beast build utilities python module
2014-05-27 15:23:49 -07:00
Vinnie Falco
5db677d74d Tidy up some source filenames:
* Add .unity suffix to mark unity sources
* Fix some relative include paths
2014-05-27 15:23:48 -07:00
Nik Bougalis
251ce4efbc base_uint cleanups:
* Remove unused and broken reverse iterators
* Use charUnHex to reduce code duplication
2014-05-27 09:26:18 -07:00
Nik Bougalis
386eabb61f Convert a unit test to manual 2014-05-26 15:29:48 -07:00
Nik Bougalis
b35eabe161 Optimize SQL query composition 2014-05-26 15:29:48 -07:00
Tom Swirly
9ad9845d69 Initialize unassigned variable bConsumed.
* Assigned in the code, but only to false.
* Someday will get assigned to true.
2014-05-23 12:16:24 -07:00
Tom Swirly
74eb25f9b5 RippleCalc: Stop using reference that might have been invalidated. 2014-05-23 12:16:22 -07:00
Nik Bougalis
044f390fe0 Properly standardize RFC1751 inputs 2014-05-23 11:06:43 -07:00
Miguel Portilla
06d6e4901e Complete NodeStore documentation
* Complete README.md
* Add missing doxygen
* Fix getHitRate bug
2014-05-19 10:53:40 -07:00
Tom Swirly
3ca9646329 Refactor the structure of RippleCalc
* Split code into multiple files
* Rename and move things
2014-05-19 10:53:40 -07:00
Tom Ritchford
4b3e629dfd Allow ledgers to be loaded from the command line.
Conflicts:

	src/ripple_data/protocol/BuildInfo.cpp
2014-05-19 10:53:39 -07:00
Tom Swirly
568fae9878 Add documentation comments 2014-05-19 10:53:39 -07:00
Tom Swirly
a844026f6b Clean up pre C++1 idioms:
* Use auto for in some loops
* Fix shadowing iterator declaration
* Rename NUMBER to ARRAYSIZE.
* Use placeholders instead of macros
* Replace macro BIND_TYPE with std::bind
* Replace BOOST_FOREACH with range-for
2014-05-19 10:53:38 -07:00
Vinnie Falco
b677cacb8c Set version to 0.25.1 2014-05-15 11:13:54 -07:00
Nik Bougalis
1d66169ef1 Fix rippled-example.cfg to list 'peers_max' 2014-05-15 11:11:16 -07:00
Vinnie Falco
74653e57e6 Use std::string in lexicalCast 2014-05-15 11:11:15 -07:00
Vinnie Falco
29d1d5f062 Set version to 0.25.0 2014-05-14 09:01:44 -07:00
Vinnie Falco
d8e8693d9a Update rippled-example.cfg 2014-05-13 20:43:39 -07:00
Miguel Portilla
be737e0047 Enable Snappy compression for NodeStore backends.
* Configured via config.cfg
2014-05-13 12:21:01 -07:00
Vinnie Falco
83ef06748d Add snappy compression integration 2014-05-13 12:16:39 -07:00
Vinnie Falco
5a93f9991a Merge commit '8b0602a5824199d495f6720ef2447f695179257a' as 'src/snappy/snappy' 2014-05-13 12:16:31 -07:00
Vinnie Falco
8b0602a582 Squashed 'src/snappy/snappy/' content from commit 1ff9be9
git-subtree-dir: src/snappy/snappy
git-subtree-split: 1ff9be9b8fafc8528ca9e055646f5932aa5db9c4
2014-05-13 12:16:31 -07:00
Vinnie Falco
eb24ca6def Update .gitattributes 2014-05-13 12:15:59 -07:00
Nik Bougalis
22af79606a Fix lexicographical compare during tfRequireAuth processing 2014-05-13 12:10:39 -07:00
Nik Bougalis
bee12fb89d Autobridging future support:
* Refactor and cleanup transactors
* Introduce new direct and bridged transactors
* Rename existing transactor to indicate legacy status
* New direct transactor defaults to being turned off (preserve legacy behavior)
2014-05-13 12:09:47 -07:00
Nik Bougalis
1a9fbab165 CBase58Data Refactoring:
* Remove unnecessary functions.
* Load from a base_uint const& - don't use void pointers.
* Free comparison functions.
* Explicitly specify encoding alphabet.
* Miscellaneous cleanups.
2014-05-13 08:48:53 -07:00
David Schwartz
9a4b9aa69f Remove redundant checkAccept call 2014-05-13 08:48:52 -07:00
David Schwartz
227043e51f Make I/O latency available through server_info 2014-05-13 08:48:51 -07:00
JoelKatz
db3a387224 Fetch pack cleanups:
* Limit backed up fetch pack requests
* Cleanups
* Dispatch fetch packs sooner
2014-05-13 08:48:50 -07:00
David Schwartz
0075f36bbc At level 64, only leaves are allowed 2014-05-13 08:48:49 -07:00
David Schwartz
52f45669d1 Dispatch incoming TX set data 2014-05-13 08:48:48 -07:00
JoelKatz
294a13d653 Put newly-created nodes in the treeNodeCache 2014-05-13 08:48:48 -07:00
JoelKatz
eed66894db SHAMap::canonicalize must return a node with the correct ID 2014-05-13 08:48:47 -07:00
Vinnie Falco
1434695c47 Fix vs2013 availability of make_reverse_iterator 2014-05-13 08:38:02 -07:00
Tom Swirly
390ea65e15 Refactor RippleCalc.cpp:
* Add comments
* Restrict code to 80 colums
* Remove boost::format
* Remove BOOST_FOREACH
* Make members private
* Add ripple_unordered_set to UnorderedContainers.h
* Replace boost::unordered_set with ripple::unordered_set
2014-05-09 12:03:57 -07:00
David Schwartz
6f2bcc6fb0 Keep SHAMapNodes that fault in handling client requests. 2014-05-09 11:46:24 -07:00
David Schwartz
66a762d504 Rework handling of modified ledger nodes:
* Track dirty nodes in a set
* Make flushDirty a member function
* Don't write deleted nodes
* Make sure new nodes are shareable
* Put new nodes in the treeNodeCache
2014-05-09 11:46:15 -07:00
David Schwartz
aaabec0b55 Use last closed ledger for old pathfinding 2014-05-09 11:46:05 -07:00
Nik Bougalis
6339800946 Refactor base_uint<> and STAmount::getText:
base_uint<>:
* Remove unnecessary typedefs and derived classes
* Factor out common code and eliminate redundancies
* Add tag support to improve type safety
* base_uint::ToString() -> to_string(base_uint const&)
* base_uint::GetHex() -> to_string(base_uint const&)

STAmount::getText:
* Don't overallocate
* Eliminate unnecessary copying
2014-05-09 11:45:44 -07:00
Nik Bougalis
a3e4a34021 Implement C++14 std::make_reverse_iterator 2014-05-09 11:45:10 -07:00
David Schwartz
6fcf3fedb6 Use Json::StaticString to improve performance:
* Move JSON-RPC fields to jsonrpc_fields.h
2014-05-07 13:04:35 -07:00
David Schwartz
34cbb26e47 Improved performance monitoring of NodeStore backends:
* Add multi-sample interface to LoadMonitor
* Instrument fetch operations and completions for reporting in server_info
2014-05-05 14:17:23 -07:00
David Schwartz
07d0379edd Reduce number of async fetches 2014-05-05 14:17:23 -07:00
Tom Swirly
96e8cddfc2 New strConcat concatenates strings in O(n) time.
* Accepts std::string and char const*.
* Also accepts numbers, bools and chars.
* New ripple::toString function augments std::to_string to handle
  bools and chars.
2014-05-05 14:17:23 -07:00
Tom Swirly
3c5e4e440b Clean up of TransactionSign and friends. 2014-05-05 14:17:22 -07:00
Tom Swirly
5ffcbb9b65 Add documentation to SHAMap 2014-05-05 14:17:21 -07:00
Nik Bougalis
ec0fe312af Simplify and improve performance of STAmount::createHumanCurrency 2014-05-05 14:17:21 -07:00
Miguel Portilla
3025d8611b Rename Feature to Amendment:
* Added a README.md describing an Amendment
2014-05-05 13:50:00 -07:00
Miguel Portilla
98612a7cd6 Cleanup nodestore backend classes:
* Add README.md
* Add missing std::move calls
* Refactor visitAll in backend
2014-05-05 13:50:00 -07:00
MarkusTeufelberger
6e428054ef Update RPM spec file to version 0.24.0 2014-05-05 13:49:59 -07:00
Vinnie Falco
3eb1c7bd6f Set version to 0.24.0 2014-05-05 10:20:46 -07:00
Vinnie Falco
2ed2158309 Set version to 0.24.0-rc2 2014-05-02 13:01:17 -07:00
JoelKatz
112d383698 Pathfinding dispatch improvements
* Simplify decision whether to update a path
* Prevent pathfinding threads from blocking each other
2014-05-02 13:01:17 -07:00
Vinnie Falco
11d0c89a59 Set version to 0.24.0-rc1 2014-05-01 16:14:20 -07:00
JoelKatz
7cffd0e0f5 Add comments to LedgerHistory 2014-05-01 16:14:14 -07:00
JoelKatz
d1f5006e44 Validation timing fixes:
* Log whether consensus built a ledger we already had or were acquiring
* Don't trigger an acquire for a validation for a ledger we might be building
* When we finish building a ledger, try to accept that ledger
* If we cannot accept a built ledger, check held validations
* Correctly set isCurrent for untrusted validations
* Add appropriate logging

This fixes a race condition that could cause spurious and expensive
ledger fetches across the network and delayed recognition of
fully-validated ledger.
2014-05-01 16:14:09 -07:00
Vinnie Falco
a10c48182f Move .proto and generated sources 2014-05-01 09:53:42 -07:00
Howard Hinnant
b5348980e2 Improve Json::Value special members (fixes RIPD-215):
* Add move special members
* Fix Json::Value::swap
2014-04-30 13:01:00 -07:00
Nik Bougalis
73c5a867c6 Fix out-of-order initialization 2014-04-30 11:32:18 -07:00
miguelportilla
b8162884d9 Finish implementation of Ledger process/Features logic:
* Defining RIPPLE_PROPOSE_FEATURES enables ledger features
* Reduce dependence on getApp via dependency injection
* Converted uint32 members to use Clock::time_point
* Inject Journal, tidy up classes:
    - Features
    - FeaturesImpl
    - FeeVote
    - FeeVoteImpl
2014-04-28 14:54:17 -07:00
David Schwartz
ebae927a3e Allow range-based for to work on STVector256 2014-04-28 14:54:17 -07:00
David Schwartz
3dde8b4345 If RocksDB high threads are configured, use them for flushes 2014-04-28 14:54:16 -07:00
Nik Bougalis
6f6720b346 Optimize composition of HTTP/RPC reply strings 2014-04-28 14:54:16 -07:00
JoelKatz
1ba0d40bb4 Small Ledger cleanups and improvements:
* Remove call to updateHash in LedgerConsensus::accept
 * Correct serialization size in updateHash
 * Add some comments to setImmutable and setAccepted
2014-04-28 14:54:15 -07:00
Nik Bougalis
3b87b140c9 Update README.md 2014-04-28 14:54:15 -07:00
Nik Bougalis
912d74e805 Tidy up some STAmount and base_uint operations:
* Constrain use of arithmetic operators in STAmount
* Prevent constructor conversion of uint256 to uint128 - make intent clear
* Prevent implicit conversion of uint64_t to uint256
* Prevent implicit conversion of uint64_t to uint160
2014-04-28 14:54:15 -07:00
JoelKatz
6ae329f4a6 Universal flags need to be added to tfAccountSetMask 2014-04-24 20:39:16 -07:00
Tom Swirly
360db3c7ca Fix RIPD-166:
* Allow RPC commands sign and submit to sign using the regular key.
* Allow command line RPC command submit to take an "offline" flag.
* Mark SerializedObject.getFlags() as const.
2014-04-24 20:27:45 -07:00
Tom Swirly
c39fd4e64d RPC: Improve wallet_propose, deprecate wallet_seed:
* Add master_key, public_key and public_key_hex to wallet_propose's JSON response.
* Report an error if we can't understand wallet_propose's passphrase.
* Deprecate wallet_seed by adding a "deprecated" parameter directing the user to wallet_propose.
2014-04-24 10:21:55 -07:00
Nik Bougalis
f4aec40fc1 Fix display formatting of STAmount 2014-04-22 12:39:43 -07:00
Tom Swirly
7fed69fc13 Split RPCHandler into a large number of small parts:
* Handler methods of RPCHandler are extracted into individual files.
* Helper methods of RPCHandler are converted into free functions, and
  extracted into individual files.
* Much code leaves ripple_app/rpc/RPCHandler.cpp and enters ripple_rpc/.
2014-04-18 11:22:29 -07:00
Nik Bougalis
f26d95d0bb Quality tests aren't manual 2014-04-18 09:31:22 -07:00
Vinnie Falco
29ee4899bc Fix VS2013 warnings about integer conversions 2014-04-17 13:06:06 -07:00
Howard Hinnant
6596c94eb9 Refactoring of container usage:
* New ripple container aliases use hardened_hash
* Use std::tuple instead of boost::tuple
* Use std unordered containers instead of boost
* Fix Destroyer for new containers
* Fix warning for fnv1a on 32-bit arch
* Validator fixes for new containers
2014-04-16 19:00:13 -07:00
Vinnie Falco
6f8145b696 Add [max_peers] doc to example cfg 2014-04-16 12:23:26 -07:00
Miguel Portilla
65f496fefb Fix 64-bit Visual Studio build 2014-04-16 12:19:32 -07:00
Vinnie Falco
3ca8bf5f98 Remove obsolete TODO files 2014-04-16 07:48:56 -07:00
Vinnie Falco
62354350a3 Refactor ripple_overlay:
* Use rvalue move to receive accepted sockets
  * Split asio dependent APIs to their own class and file
  * Update documentation
  * Organize code into different files
  * Make some members private
  * Rename things for clarity
2014-04-16 07:48:56 -07:00
Tom Swirly
898b7eb6f0 Add CleanCCPFiles.py, a utility for tidying up whitespace 2014-04-15 11:52:02 -07:00
Nik Bougalis
398edd39f8 Add beast::tagged_integer:
* Wraps standard integer types to provide type-safety
 * Named types provide self-documenting semantics
 * Catches programmer errors involving mismatched types at compile time
 * Operators restrict mutation to only safe and meaningful operations
2014-04-15 11:48:35 -07:00
Nik Bougalis
5fddf374f4 Refactor usage of boost::format 2014-04-15 11:48:34 -07:00
Nik Bougalis
2ed8edc19d Make is_set_bit a universal template function 2014-04-15 11:40:58 -07:00
Tom Swirly
feb88c4f7f Enforce minimum version requirements on OpenSSL and Boost 2014-04-15 10:22:51 -07:00
Vinnie Falco
ebcedcbe93 Fix Visual Studio 2013 build 2014-04-15 08:13:53 -07:00
The Doctor
e3995ac776 Updated example cfg for new validator public keys.
Signed-off-by: The Doctor <drwho@virtadpt.net>
2014-04-14 18:21:06 -07:00
Tom Swirly
64ee0d07d0 New Zero struct implements "compare with zero."
* Zero lets classes efficiently compare with 0, so
  you can use constructors like x < zero or y != zero.
* New BEAST_CONSTEXPR to handle Windows/C++11 differences
  regarding the constexpr specifier.
2014-04-14 11:14:11 -07:00
Tom Ritchford
524f41177c Improvements to scons build for beast.
* Common code extracted to Python directories.
* Read ~/.scons file for scons environment defaults.
* Override scons settings with shell environment variables.
* New "tags" for debug, nodebug, optimize, nooptimize builds.
* Universal platform detection.
* Default value of environment variables set through prefix dictionaries.
* Check for correct Boost value and fail otherwise.
* Extract git describe --tags into a preprocesor variable, -DTIP_BRANCH
* More colors - blue for unchanged defaults, green for changed defaults, red for error.
* Contain unit tests for non-obvious stuff.
* Check to see that boost libraries have been built.
* Right now, we accept both .dylib and .a versions but it'd be easy to enforce .a only.
2014-04-11 10:40:26 -07:00
Vinnie Falco
04ea9ff74c New classes for processing offers in order books:
* BookTip provides consume-and-step offer traversal
* OfferStream applies offer business rules and presents offers to callers
* Taker class manages state for the active party during order processing
* Offer class wraps book offers for presentation
2014-04-10 17:49:19 -07:00
Vinnie Falco
53bf5e7f36 New classes and types for handling asset amounts:
* Quality opaque type for order book quality
  * Amount replacement for STAmount
  * Amounts, in/out amount pair for offers
  * 'core' namespace with type aliases for Ripple primitives.
2014-04-10 17:49:19 -07:00
Nik Bougalis
bd60a93cd6 Fix conversion of binary data to hexadecimal strings in some cases. 2014-04-07 14:56:37 -07:00
The Doctor
8a608b5829 Configuration file improvements:
* Set default node_db to RocksDB from HyperlevelDB, to match gateway
  appliances and Ripple Labs server configurations.
* Set some rpc_startup options to reduce logging and save disk space.
* More sensible documentation regarding WebSocket SSL directives

Signed-off-by: The Doctor <drwho@virtadpt.net>
2014-04-07 13:19:21 -07:00
David Schwartz
151388692a Add bg_threads and high_threads RocksDB tunables 2014-04-04 19:01:01 -07:00
Nik Bougalis
bec876d062 Remove unused legacy code 2014-04-04 19:00:58 -07:00
Howard Hinnant
81238e21a5 Force BOOST_ASIO_HAS_STD_ARRAY to 1
for the clang / gcc libstdc++ 4.8 combination
2014-04-03 14:58:28 -04:00
Howard Hinnant
cc354ee9f2 Sub in std::array for boost::array and beast::FixedArray 2014-04-03 14:02:34 -04:00
JoelKatz
90842073bf Must set flags before signing validation. 2014-04-02 18:39:59 -07:00
Nik Bougalis
a5488c3727 Autobridging hooks and cleanups:
- Detect when we should autobridge and get bridge books.
- Move applyOffer from STAmount into the OfferCreate transactor.
2014-04-02 18:39:59 -07:00
Nik Bougalis
166b8963bb Don't create peer doors in standalone mode 2014-04-02 14:16:24 -07:00
Nik Bougalis
c51644f1b9 More robustly validate signature inputs, closes #313 2014-04-02 14:16:07 -07:00
Vinnie Falco
f124a34730 Fix assert invariant in Peers::close_all 2014-04-01 10:24:55 -07:00
Howard Hinnant
30e882196f New hash_append robust container hash function framework:
* is_contiguous_hashable trait identifies optimizable types
* hash_append() function overloads for basic types:
  - scalars, floats
  - array, C array
  - pair, tuple
  - boost array and tuple (if configured)
* Provided Spooky hash wrapper for use with hash_append
* Use hash_append in hardened_hash and other places
* New Utility meta functions for working with variadics:
  - static_and
  - static_sum
* Added type_name utility function for diagnostics
* hash_metrics suite of functions to evalulate hash functions
* Test suites to measure hash function performance
* Various fixes
2014-03-31 15:49:23 -07:00
David Schwartz
14830c7cb4 Avoid redundant unlock 2014-03-31 09:11:52 -07:00
JoelKatz
5a21269da4 mRecentPositions must be protected by the master lock. 2014-03-28 13:45:53 -07:00
JoelKatz
cc5466d450 Reject expired transactions immediately 2014-03-28 10:33:53 -07:00
JoelKatz
a068bff9c1 Set fully-canonical flag in transactions and validations. 2014-03-28 09:34:22 -07:00
David Schwartz
1e54472a1d Clean local transaction checks. Check account field size 2014-03-25 16:20:22 -07:00
David Schwartz
be9e18ddb8 Track and re-appply LocalTransactions as needed 2014-03-25 16:20:22 -07:00
JoelKatz
5d1aec6280 Charge for pathfinding updates. 2014-03-25 16:20:22 -07:00
JoelKatz
0442b3a683 Change resource costs. 2014-03-25 16:20:22 -07:00
Vinnie Falco
bbc8a8fdc4 Move hardened_hash to container/ 2014-03-25 15:22:34 -07:00
Vinnie Falco
428872731a Add beast SConstruct and .travis.yml 2014-03-25 15:22:34 -07:00
Nik Bougalis
015d91b50d OfferCreateTransactor cleanups:
- Use std containers instead of their boost counterparts
- Reduce transactor console verbosity
- Remove unneeded parameter shadowing member variable
- Remove BOOST_FOREACH
- Add comments
- Small cleanups
2014-03-25 15:22:33 -07:00
Nik Bougalis
436061be22 Transactor journal support and small cleanups 2014-03-25 15:22:13 -07:00
Nik Bougalis
d447a1db39 Refactor ECDSA canonical checks:
* Add signature canonicalization unit tests
* Tidy up into new classes and functions
2014-03-25 15:22:13 -07:00
Luke Cyca
a4a7dd4314 Fedora RPM support:
- Add RPM spec file
- Whitelist Fedora during SConstruct
2014-03-24 14:07:36 -07:00
Roberto Catini
4886772ca3 Add Arch Linux PKGBUILD:
The install process will first fetch the tip of the master branch
to build the latest official rippled release. It will also create
all the necessary data directories in /var.

An optional systemd service definition file is included.
2014-03-24 14:07:27 -07:00
The Doctor
0f19efac2d Example configuration file update:
- Fix config database default location.
  - Add SSL/TLS for WebSockets config. Currently commented out.
2014-03-24 14:07:19 -07:00
Vinnie Falco
b2d97703c6 beast cleanup and tidying:
* Replace custom types with C++11 <cstdint> types
* Fix sqlite integer intos and uses
* Fix String implicit integer constructors
* Escape the enclosing namespace in sqdb
* Replace contract checks with assert
* Make many header files compile independently
* Remove the dependence on beast_core.h in many places
* Remove unused or obsolete classes and functions
* Remove unused or obsolete macros
* Remove unused network functions and files
* Remove unused or obsolete classes:
  - ChildProcess
  - HighResolutionTimer
  - InterProcessLock
  - Throw
  - TrackedMutex
  - UntrackedMutex
  - XmlDocument
  - XmlElement
2014-03-23 15:23:55 -07:00
Vinnie Falco
936f45c7ec Add hardened_hash, prevents adversarial inputs 2014-03-22 18:42:18 -07:00
Vinnie Falco
a865149c65 New unit_test framework:
* Header-only!
* No external dependencies or other beast modules
* Compilation options allow for:
  - Stand-alone application to run a single test suite
  - Stand-alone application to run a set of test suites
  - Global suite of tests inline with the host application
  - Disable test suite generation completely
* Existing tests reworked to use the new classes
2014-03-21 18:00:37 -07:00
Vinnie Falco
547019bd1b beast.streams improvements:
* New basic_std_ostream wraps any std::stream.
* New debug_ostream redirects output to debugger if attached.
2014-03-21 07:33:16 -07:00
Vinnie Falco
953805d97e Add const_container 2014-03-21 07:33:16 -07:00
Vinnie Falco
e344cb3d62 beast cleaning and tidying:
* Consolidate small modules into one
* Remove Android-specific platform support
* Remove Chrono.h from beast_core.h
* Removed files:
  - TypeTraits.h
  - Utility.h
  - Net.h
  - Asio.h
* Remove zlib support:
  - Remove inline zlib library sources
  - Remove GZIPCompressorOutputStream
  - Remove GZIPDecompressorInputStream
* Remove obsolete or unused classes:
  - AbstractObject
  - BigInteger
  - BufferedInputStream
  - CacheLine
  - CPUMeter
  - DatagramSocket
  - DynamicObject
  - FileLogger
  - FPUFlags
  - Identifier
  - JSON
  - LocalisedStrings
  - MACAddress
  - MemoryAlignment
  - MemoryInputStream
  - MemoryMappedFile
  - NamedValueSet
  - OptionalScopedPointer
  - PerformanceCounter
  - PropertySet
  - ScopedTimeInterval
  - SparseSet
  - SpinDelay
  - StreamingSocket
  - StringPool
  - SubregionStream
  - Uuid
  - Variant
2014-03-21 07:30:50 -07:00
Vinnie Falco
693a5927a9 Update to SQLite 3.8.4.1 2014-03-20 19:17:25 -07:00
Howard Hinnant
07e2f87079 Fix and add tests for empty_base_optimization. 2014-03-20 13:47:48 -07:00
Vinnie Falco
9b152d8098 Fix error code assignment in raw_parser 2014-03-20 10:43:01 -07:00
Vinnie Falco
8daecb5430 Add abstract streams module:
* New basic_abstract_ostream template for generic output
* New abstract_ostream, common type alias
* basic_scoped_ostream, RAII output to abstract streams
2014-03-19 15:42:20 -07:00
Vinnie Falco
f1462de729 Add workaround/noexcept.h for visual studio 2014-03-19 13:42:05 -07:00
Vinnie Falco
3cb3e5273f Change to the treatment of BeastConfig.h
* No longer requires its own compiler include path
* Includes use relative paths to locate the file
* Client applications include the file themselves
* Inclusion of BeastConfig.h can be controlled via preprocessor directive
2014-03-19 13:42:04 -07:00
Howard Hinnant
cad50c68a8 General tidy and refactoring:
* Use nullptr (C++11) instead of NULL.
* Put each file into its own namespace declaration.
* Remove "using namespace" directives and add scope qualifiers.
* Control when beast's implementation of std::equal (C++14) is used.
* Tidy up some const declarations.

Conflicts:
	src/ripple_app/shamap/SHAMapSync.cpp
	src/ripple_app/tx/TransactionEngine.cpp
2014-03-19 13:42:01 -07:00
Vinnie Falco
c581ffb8a4 Restructure joyent message parser (from Node.js):
* New http::raw_parser wrapper
* Convert parser errors to error_code
* Enumeration and strings for parsed HTTP method
* Move parser engine into joyent namespace
* Rename includes to be distinct
2014-03-19 10:41:24 -07:00
Vinnie Falco
556778dbdb beast, beast::asio improvements and fixes:
* New maybe_const_t alias for maybe_const
* New asio::enable_wait_for_async for safe cleanup
* New asio::memory_buffer, a managed boost::asio compatible buffer
* shared_handler improvements:
   - Can be 'empty' (no stored handler).
   - Default constructible as 'empty'.
   - Safe evaluation in bool contexts, false==empty
* Fix is_call_possible metafunction:
   - Works on empty argument lists
   - Works with reference types
* Replace SafeBool idiom with C++11 explicit operator bool
* Move IPAddress function definitions to the header
* Move cyclic_iterator to container/
* Remove unused BufferType
* Remove obsolete classes:
   - NamedPipe
   - ReadWriteLock
   - ScopedReadLock
   - ScopedWriteLock
   - LockGuard
2014-03-17 17:40:55 -07:00
Vinnie Falco
816fab000d Fix SConstruct compiler arguments 2014-03-17 14:49:31 -07:00
Nik Bougalis
66d1dd6f81 Build system improvements:
* Reduce console verbosity.
* Display configured build environment.
* Log build environment and commands in rippled-build.log.
* When compiling under Travis:
  - define TRAVIS_CI_BUILD for C and C++ code.
  - define RIPPLE_MASTER_BUILD for builds made against
    the official Ripple repository.
2014-03-17 09:22:11 -07:00
Vinnie Falco
3eae68fc34 Remove obsolete support scripts 2014-03-15 06:07:43 -07:00
Vinnie Falco
8545aee4c7 Better diagnostics for SSL certificate failures 2014-03-14 16:20:34 -07:00
Vinnie Falco
29a4f61551 Set version to 0.23.0 2014-03-14 13:01:23 -07:00
Vinnie Falco
c2fd1215f5 Refactor beast::asio:
* New tools for completion handlers:
  - wrap_handler provides composed io_service execution guarantees.
  - bind_handler rebinds arguments to handlers.
  - shared_handler type-erases any completion handler.
  - buffer_sequence type-erases templated BufferSequences
  - abstract_socket replaces Socket
  - socket_wrapper replaces SocketWrapper
  - beast::asio placeholders to work with std::bind

* Removed obsolete classes and functions
  - AbstractHandler
  - ComposedAsyncOperation
  - SharedFunction
  - SharedHandler
  - SharedHandlerAllocator
  - SharedHandlerPtr
  - SharedHandlerType
  - SocketBase
  - SocketWrapperStrand
  - wrapHandler

* Refactored classes to use new tools
  - abstract_socket
  - socket_wrapper
  - HandshakeDetector
  - HttpClientType

* Miscellanous tidying
  - socket classes moved to beast::asio namespace
  - beast asio files provide their own namespace declaration.
  - Fix IsCallPossible conflicting template parameter name
  - Use <boost/get_pointer.hpp> for C++11 compatibility.
  - Remove extraneous include path from build environment.
2014-03-14 08:03:48 -07:00
Vinnie Falco
e3c1375f36 Add std::integer_sequence C++14 compatibility 2014-03-14 07:57:20 -07:00
Vinnie Falco
4e357601ec Move MultiSocket, RippleSSLContext to common module 2014-03-14 07:57:20 -07:00
Vinnie Falco
3674b01634 Add ripple::byte_view, ripple::const_byte_view 2014-03-14 07:57:20 -07:00
Vinnie Falco
f66aee4e7f Add beast::buffer_view 2014-03-14 07:57:19 -07:00
Vinnie Falco
b2f06dbe3c Add C++11 noexcept compatibility for VS2013 2014-03-14 07:57:19 -07:00
sublimator
b78076670e Fix typos: tecMASTER_DISABLED, tecNO_REGULAR_KEY 2014-03-14 07:57:18 -07:00
sublimator
a08a0703b6 Remove Jenkins CI build status badge
This isn't used any more is it?
2014-03-13 21:15:13 -07:00
sublimator
f80561e6aa Travis: disable gdb thread event logging
Attempt 2
2014-03-13 21:15:13 -07:00
JoelKatz
f5765b71f2 Handle unexpected relative paths from __FILE__
Fixes comref#RIPD-133
2014-03-13 16:49:20 -07:00
Vinnie Falco
6a6be847c0 Set version to 0.23.0-rc1 2014-03-12 19:05:08 -07:00
Nik Bougalis
4e26108a06 Protect callers of MultiSocket::remote_endpoint from exceptions 2014-03-12 13:51:00 -07:00
JoelKatz
c517d261bb Return a sensible error for unknown inner JSON fields 2014-03-12 00:54:00 -07:00
JoelKatz
5522a23670 Don't relay old proposals. 2014-03-11 22:21:34 -07:00
JoelKatz
64345f90a8 Allow setting LedgerConsensus to TRACE 2014-03-11 22:12:48 -07:00
JoelKatz
879c0d6b78 Be less promiscuous relaying proposals 2014-03-11 21:49:46 -07:00
Nik Bougalis
2e8df429df Expose PeerImp::start instead of requiring the use of accept/connect 2014-03-11 19:02:18 -07:00
JoelKatz
7aa1222310 Fix the "peer action" transition from syncing to full 2014-03-11 19:02:18 -07:00
JoelKatz
2b5142ee4d Make transaction forwarding less promiscuous 2014-03-11 19:02:17 -07:00
Nik Bougalis
e8d7d339ef Transactor refactoring:
- Reorganize transactor source files and VS project
- Don't expose Transactor interfaces to anyone but the TransactionEngine
- Improve compile times
- Begin using Journal
2014-03-11 19:02:17 -07:00
Nik Bougalis
5324a6d59d Don't create a Transactor if we don't have a valid TxID 2014-03-11 19:02:17 -07:00
Nik Bougalis
569b3a46a1 Cleanups:
- Cleanup VotableInteger class and remove unused duplicate
 - Remove obsolete function and move to std functions
 - Fix typos
 - Make isMemoOkay a free function
 - Sanitize error returns
2014-03-11 19:02:17 -07:00
JoelKatz
fc129e43fd Cleanup handling of expired offers 2014-03-11 19:02:16 -07:00
JoelKatz
b22a0f4a97 Ensure offer cleanup is deterministic 2014-03-11 19:02:16 -07:00
JoelKatz
cf63b5c859 Fix logging transactions that throw 2014-03-11 19:02:16 -07:00
David Schwartz
b4593a274d Limit how many reads we defer to avoid overflowing the cache 2014-03-11 19:02:16 -07:00
David Schwartz
163daf012a Add 'MemoData' field 2014-03-11 19:02:16 -07:00
JoelKatz
63df034bcf Clean up job renaming 2014-03-11 19:02:16 -07:00
David Schwartz
60787be80c Check the node store for transaction nodes with metadata 2014-03-11 19:02:15 -07:00
David Schwartz
f42ae3af21 Add ledger_data command to get full ledgers in pieces 2014-03-11 19:02:15 -07:00
David Schwartz
b1fea3c51e Disable retrieving full state trees for non-admins. 2014-03-11 19:02:15 -07:00
David Schwartz
16d2bbd6e5 Avoid disk I/O when data 'moves' in a SHAMap 2014-03-11 19:02:15 -07:00
David Schwartz
2505a908c5 Logging reduction in PeerImp 2014-03-11 19:02:15 -07:00
Nik Bougalis
4b71673ee9 Improve validation of JSON inputs 2014-03-11 19:02:14 -07:00
Nik Bougalis
242494a9ad Allow a server to keep no ledger history, closes #299 2014-03-11 19:02:14 -07:00
Nik Bougalis
3a684ce280 Robust HashPrefix initialization, closes #300 2014-03-11 19:02:14 -07:00
Nik Bougalis
756da7b844 Fix strUnHex parsing of odd-length strings and add unit tests 2014-03-11 19:02:14 -07:00
Nik Bougalis
9c465487ae Cache the result of remote_endpoint at connect/accept time and use it 2014-03-11 19:02:14 -07:00
Donovan Hide
e8002a7a62 Fix ledger log warning, closes #298 2014-03-11 19:02:13 -07:00
Nik Bougalis
5a53b48026 Require a C++11 conforming compiler 2014-03-11 19:02:13 -07:00
Vinnie Falco
b3f725d9fd Update http code for http parser API changes 2014-03-06 21:44:29 -08:00
Vinnie Falco
50f5d5bdf3 Merge commit '6c0edd2190bfd18ffc523f486367da3724cf98a3' into develop 2014-03-06 21:22:22 -08:00
Vinnie Falco
6c0edd2190 Squashed 'src/beast/beast/http/impl/http-parser/' changes from 547553b..cba704c
cba704c Bump version to 2.2.1
a252d4e fix content-length and chunk-size overflow test
42d6541 add vc project files to .gitignore
fd609ab Bump version to 2.2
efcf75d test: better fix for __APPLE__ test build
9ca484d test: fix build on osx
d7b938b Parse and emit status message of response
11419c8 Use unsigned int as bitfield type.
c4079e7 Add syntax highlighting to README C code
f5c779b Update misleading comment.
3cbd13d test: add amazon.com response test

git-subtree-dir: src/beast/beast/http/impl/http-parser
git-subtree-split: cba704cb2d9f1df80994dd4a791a0fa6cce65720
2014-03-06 21:22:22 -08:00
Vinnie Falco
d9a0181189 Set version to 0.22.0 2014-03-04 15:43:34 -08:00
Howard Hinnant
09570996a9 Fix beast::asio failures on OS X.
There are 38 unittest failures on OS X.  These changes address all of
them by adjusting which side of the socket (send or receive) gets
shut down.  In each case, the failure was 'Socket is not connected'.
I've interpreted that to mean that the other thread had already shut
down its side of the connection.
2014-03-04 15:43:33 -08:00
JoelKatz
adc4c855ca Fix the ledger range we advertise to peers 2014-03-04 15:43:33 -08:00
Nik Bougalis
8b1df06a94 PeerFinder fixes:
* Fix local advertisement (was missing)
* Fix Livecache histogram display
* If no [ips] are specified, use r.ripple.com
* Use different backing stores for PeerFinder and Validator databases
2014-03-04 15:43:32 -08:00
Vinnie Falco
7c81eec30c Remove unused TextDiff 2014-03-04 07:23:53 -08:00
Vinnie Falco
faa999d6d0 Consolidate C++14 compatibility into new headers 2014-03-03 18:51:56 -08:00
David Schwartz
370bfb7a22 Permit memos up to 1Kb.
* Overlong memos are basically treated like invalid signatures.
* Ability to clear message key.
2014-03-03 18:51:55 -08:00
David Schwartz
ae649ec917 Signature canonicalization and transaction mutation fixes 2014-03-03 18:51:55 -08:00
JoelKatz
93b44fcdc1 Return an empty pointer from getLedgerBySeq if sequence in future 2014-03-03 14:07:18 -08:00
David Schwartz
1fe57720c4 Legacy Pathfinding API improvements:
* Use the cache for source/dest currencies
* Allow a search depth and initial paths to be specified in old pathfinding
2014-03-03 10:59:31 -08:00
JoelKatz
fca8fa1b1b Clean up ledger fetch reasons.
Don't trigger immediately when fetching historical ledgers.
2014-03-03 10:57:36 -08:00
David Schwartz
81082ad10f Don't check the node store for proposed txn nodes 2014-03-03 10:57:31 -08:00
David Schwartz
2c515636cb Release the InboundLedger lock during getMissingNodes 2014-03-03 10:57:26 -08:00
David Schwartz
2f7ac98e34 Improve I/O when fetching ledgers
* negative cache for node store
* async fetch, thread pool for node store
* read barrier logic for node store
* SHAMap getMissingNodesNB (non-blocking)
* non-blocking getMissingNodes traverse
* tune caches
2014-03-03 10:56:48 -08:00
Nik Bougalis
37b39ed1a1 Update LICENSE 2014-03-01 11:54:11 -08:00
Nik Bougalis
73485d5a23 Resolve hostnames found in the [ips] config section 2014-03-01 11:53:57 -08:00
Nik Bougalis
28c7827f14 Calculate program file directories:
* Determine location of database files in Config
* Inject database directory or file path in PeerFinder and Validators
* PeerFinder and Validators will share the same sqlite file
2014-03-01 11:53:57 -08:00
JoelKatz
e055dc1513 WebSocket dispatch changes.
Don't let one connection hold a thread for too long without
having to wait for another turn
2014-02-28 12:18:15 -08:00
JoelKatz
c173f14fc0 Give pathfinding updates priority over client and RPC requests 2014-02-28 12:15:41 -08:00
Howard Hinnant
cd30e552a7 Fix clang warnings 2014-02-28 12:15:12 -08:00
Vinnie Falco
9bf1a76e91 Remove unused classes 2014-02-28 12:03:33 -08:00
Vinnie Falco
2957b688fd PeerFinder and Peers fixes:
- Fix bootcache incorrect failure on socket cancel
- Fix peer connect race on stop
- Simplify some loops
- Require boost 1.55 via static_assert
2014-02-28 12:03:33 -08:00
JoelKatz
add40d524f Merge pull request #296 from nbougalis/quickfix-jobcount
Fix variable mismatch for job counts
2014-02-26 14:38:51 -08:00
Nik Bougalis
04a55e35b6 Fix variable mismatch for job counts 2014-02-26 14:29:00 -08:00
JoelKatz
955ce45448 Fix the assert on a self-connect 2014-02-24 22:30:04 -08:00
Vinnie Falco
995e64a205 PeerFinder fixes:
* Fix split horizon using recent address cache
* Change message tuning parameters to reduce dead messages
* Improved peer handout algorithm for addresses
* Improved handout algorithm for redirects
* Improved selection algorithm for autoconnect
* Faster autoconnection strategy
* Consolidate deadline timers
* Send empty endpoints message as a socket ping
* Fix hop count adjustments for live cache filtering
* Remove broken Peer::isConnected function
* Optimized Livecache for handouts
* Optimized Bootcache for handouts
* Remove uptime metric from Bootcache entries
* Add histogram to Livecache print output
2014-02-24 19:25:01 -08:00
Vinnie Falco
bf085f0ef3 New utility classes, containers, C++14 compatibility, and fixes:
* Add std::equal_to <void> (since C++14)
* Add heterogeneous std::equal (since C++14)
* Add maybe_const
* Add empty_base_optimization
* Add is_constructible specialization for pair, tuple
* Add aged associative containers:
  - aged_set, aged_map, aged_multiset, aged_multimap
  - aged_unordered_set, aged_unordered_map,
  - aged_unordered_multiset, aged_unordered_multimap
* Fix auto keyword pass by reference
* Fix basic_seconds_clock warning and project file
2014-02-24 19:25:01 -08:00
David Schwartz
1374b37882 Remove dead serializer signature code 2014-02-24 18:28:44 -08:00
JoelKatz
e275f4eb9d Handle a removed peer when counting ledger use 2014-02-24 18:28:43 -08:00
JoelKatz
652d809129 Validate params before dispatching 2014-02-24 18:28:43 -08:00
JoelKatz
c186519bcf Ledger fetch fixes. 2014-02-24 18:28:42 -08:00
Nik Bougalis
870fb4f291 Fix missing break on mtCLUSTER handler 2014-02-24 18:28:42 -08:00
Nik Bougalis
7cd63489f4 Refactor Job tracking and statistics gathering 2014-02-23 01:47:35 -08:00
Vinnie Falco
616a53888e Use forward_tuple to prevent needless copies 2014-02-22 21:33:01 -08:00
Vinnie Falco
a336cc26f9 Remove deprecated IPAddress 2014-02-22 21:33:00 -08:00
Howard Hinnant
382088c456 Add find_create stat to InboundLedgers 2014-02-22 21:33:00 -08:00
Howard Hinnant
ff80531db4 Update LICENSE 2014-02-22 21:32:59 -08:00
Vinnie Falco
105cf3cd1e Revert "Tidy up build scripts:"
This reverts commit 66b5f75142.
2014-02-22 21:32:59 -08:00
JoelKatz
38ba7e695a Don't hold the master lock 2014-02-21 14:46:57 -08:00
JoelKatz
996326a00e Configurable fetch depth. 2014-02-17 17:26:58 -08:00
JoelKatz
f2beb82b97 Pathfinding dispatch improvements
* Keep requests forwards, flip only on insert
* Insert requests in more sensible order (after new, before old)
* Remove a redundant cache/request check
2014-02-17 17:26:50 -08:00
JoelKatz
41c0702408 Fix custom currency parsers 2014-02-17 17:26:43 -08:00
Nik Bougalis
66b5f75142 Tidy up build scripts:
* Relax the boost -mt link requirement for Debian
* Tidy up scons output, reduce verbosity, add color
2014-02-17 15:50:51 -08:00
JoelKatz
c2a16ddbab Cannot call gotTXData without master lock ... yet! 2014-02-14 14:26:03 -08:00
Vinnie Falco
5bb194cf89 PeerFinder fixes:
* Add Livecache property stream support
* Tidy up log output
* Move peer code to ripple_overlay module
* Remove or hide some Peer interfaces
* Fix asserts by removing isConnected which was not thread safe
2014-02-14 14:00:51 -08:00
Vinnie Falco
645b9a01c7 Make abstract_clock members const 2014-02-14 11:14:09 -08:00
Vinnie Falco
3a1a5d12de Refactor PeerFinder:
* Revise documentation in README.md
* Inject abstract_clock in Manager
* Introduce the Slot object as a replacement for Peer
* New bullet-proof method for slot accounting
* Replace Peer with Slot for tracking connections
* Prevent duplicate outbound connection attempts
* Improved connection and bootstrap business logic
* Refactor PeerImp, PeersImp private interfaces
* Give PeersImp access to the PeerImp interface
* Handle errors retrieving endpoints from asio sockets
* Use weak_ptr to manage PeerImp lifetime
* Better handling of socket closure in PeerImp
* Improve the orderly shutdown logic of PeersImp
2014-02-13 14:19:27 -08:00
Vinnie Falco
12748e7539 Add chrono APIs to DeadlineTimer 2014-02-12 12:58:20 -08:00
Nicholas Dudfield
2f69d4c8ee Update Travis matrix:
* New clang compiler target
* Sconstruct changes for clang
* Patches to support clang
2014-02-11 19:13:51 -08:00
Nicholas Dudfield
8dbf8b9038 Fix clang compile error 2014-02-11 19:13:45 -08:00
Vinnie Falco
fdfe047f3e Fix new RPC dispatcher params 2014-02-11 19:05:08 -08:00
Vinnie Falco
38c3f84c9f Update beast project file 2014-02-10 19:48:37 -08:00
Vinnie Falco
9c5b071556 Fix crash on exit in ~InboundLedger 2014-02-08 11:07:10 -08:00
Vinnie Falco
46dc52e449 Fix insight object lifetimes in Group 2014-02-08 10:48:54 -08:00
Vinnie Falco
f469e3853d Insight support for jobs:
* Add insight Groups to Application singleton
* Put JobQueue metrics into "jobq" Group
* Add queued time to Job
* Add per-type Job queue time metrics
* Add per-type Job execution time metrics
* Break JobQueue sources out of the namespace
* Use free function to create the JobQueue
2014-02-08 10:09:22 -08:00
Vinnie Falco
a681a4fcd4 Improved logging for insight stat packets 2014-02-08 09:33:04 -08:00
Vinnie Falco
575b0bb7b0 Fix gcc compile 2014-02-07 09:09:01 -08:00
sublimator
588cf4bfca Update travis to use boost 1.55 2014-02-07 08:09:24 -08:00
NATTSiM
9cc8c341e7 Fix clang compile 2014-02-07 08:09:15 -08:00
Vinnie Falco
9b657ba224 Refactor RPC module:
* Move JsonPropertyStream to ripple_json
* Remove unused RPC service manager
* Recreate RPC module in app code area
* Add RPC::Manager
* Add DoPrint handler
2014-02-06 18:21:08 -08:00
Vinnie Falco
9bc6e83f8a Change bassert to always call assert 2014-02-06 14:30:03 -08:00
Nik Bougalis
572aae320d Performance fixes: decongest master lock 2014-02-05 15:57:10 -08:00
Nik Bougalis
2906899811 Ignore ports when checking RPC IP filter list 2014-02-05 15:57:09 -08:00
Nik Bougalis
1a6bf88900 Resolver Work:
* Don't stall during shutdown
* Properly handle unit test execution
* Handle whitespace when parsing names to resolve
2014-02-05 15:57:09 -08:00
Nik Bougalis
e60b28980a PeerFinder work and refactoring:
* Implement PeerFinder business logic.
* Support fixed peers (including DNS support).
* Add journal support to Peer and Peers.
* Refactor PeerDoor support.
* Tidy up Peers and eliminate connection functionality and timers.
* Refactor Peer interface and add journal support.
* Allow construction of incoming Peer using an existing socket.
* Remove TESTNET support.
* Allow connections from/to cluster peers without consuming slots
* Misc. cleanups.
2014-02-05 15:56:04 -08:00
Vinnie Falco
a253b2ef4b Refactor IP::Endpoint 2014-02-05 15:53:16 -08:00
Vinnie Falco
0c2e35edc9 Remove obsolete Visual Studio projects 2014-02-05 15:42:28 -08:00
Vinnie Falco
d0970397a6 Revert system test changes:
* Revert "Shutdown rippled before http server in json rpc test to avoid http server potentially receiving messages due to automatic ledger close interval."
* Revert "Update ripple-lib integration tests"

This reverts commit 83442825e5.
2014-02-04 15:18:36 -08:00
Vinnie Falco
0afbda0351 Redirect Visual Studio 2013 project output 2014-02-04 09:25:27 -08:00
Vinnie Falco
2009f8b1ca Add insight support to TaggedCache, KeyCache:
* Move TaggedCache, KeyCache to common
* Add radmap module, FullBelowCache class
* Add get_seconds_clock
* Inject FullBelowCache in SHAMap
2014-02-03 23:00:45 -08:00
Vinnie Falco
35715a0146 Add basic_seconds_clock, insight::Groups 2014-02-03 22:55:47 -08:00
Vinnie Falco
20e27ceb04 Update Visual Studio 2013 project file 2014-02-03 22:36:29 -08:00
Vinnie Falco
7fb614f7af Fix application pointer singleton lifetime 2014-02-03 22:36:28 -08:00
Nicholas Dudfield
83442825e5 Shutdown rippled before http server in json rpc test to avoid http server potentially receiving messages due to automatic ledger close interval. 2014-02-03 22:36:28 -08:00
Nik Bougalis
123c482a69 Robustly validate input to the 'ledger' RPC command 2014-02-03 18:43:21 -08:00
Vinnie Falco
3f091fce59 Update project build requirements
* Add Visual Studio 2013 project file
* Update SConstruct for boost 1.55.0
2014-02-03 16:58:32 -08:00
wltsmrz
6c5f88aa25 Update ripple-lib integration tests 2014-02-03 10:42:34 -08:00
Vinnie Falco
23eccebf5b Fix crash on exit via Application singleton 2014-02-01 21:28:12 -08:00
Vinnie Falco
15112c1a27 Fix mutable tx json field for autofill_fee 2014-02-01 07:10:53 -08:00
David Schwartz
d0ca81ff36 visitLeaves must visit all branches 2014-01-31 19:26:53 -08:00
David Schwartz
3e218c494d Enlarge the humanAccountID cache 2014-01-31 19:26:53 -08:00
David Schwartz
88bd5b12a4 Raise RPC time and size limits 2014-01-31 19:26:53 -08:00
David Schwartz
5df5983f88 Fix missing call to setHeartbeatTimer 2014-01-31 19:26:53 -08:00
David Schwartz
aa5ca7cea5 Don't copy the parameters when calling lookupLedger 2014-01-31 19:26:53 -08:00
David Schwartz
02483b2e0b Avoid race conditions updating ledger fee entries 2014-01-31 19:26:53 -08:00
David Schwartz
f7817866ba call pubValidatedTransactions, we may have book listeners 2014-01-31 19:26:53 -08:00
JoelKatz
d62287d54b Calculate correct fee in RPC sign/submit, error if over limit 2014-01-31 19:26:53 -08:00
Nicholas Dudfield
aad074cd8e Tweak to path-finding tests. Specify test patterns outside of mocha.opts 2014-01-31 19:05:10 -08:00
Vinnie Falco
580d179dd0 Tidy up Validators logging 2014-01-29 07:53:27 -08:00
Vinnie Falco
616a514c4d Fix PropertyStream overloads 2014-01-29 07:53:27 -08:00
NATTSiM
bac8d41954 Pass IPAddress in getAdminRole 2014-01-28 22:52:11 -08:00
JoelKatz
f295bb20a1 Set version to 0.21.0.rc2 2014-01-24 11:17:16 -08:00
JoelKatz
b5ffa2351a DirectoryEntryIterator fix 2014-01-24 10:54:56 -08:00
JoelKatz
1b37b52071 Whitespace changes 2014-01-24 10:54:47 -08:00
JoelKatz
b1ffd10079 Fix "limit" mishandling in doBookOffers 2014-01-24 10:53:55 -08:00
Vinnie Falco
39235f5b91 Set version to 0.21.0.rc1 2014-01-23 23:31:26 -05:00
JoelKatz
8825d94636 Temporarily change getBookPage not to use OB iterators 2014-01-23 16:26:45 -08:00
JoelKatz
c8a7b2af56 Prevent infinite loop in getBookPage 2014-01-23 16:05:38 -08:00
JoelKatz
d22b25c030 Set version to 0.21.0 2014-01-23 13:38:38 -08:00
JoelKatz
d475994e02 Pairwise no ripple:
* Cannot set noRipple flag with negative balance.
* Paths with consecutive no ripple links are invalid
* Adjust pathfinding value of no ripple out paths
* Check for no ripple when adding links in pathfinding
* Remove old noRipple logic
* Update trust line delete logic
2014-01-23 13:38:33 -08:00
JoelKatz
f0bb3dfdfb Never allow a retry as a final result 2014-01-23 13:38:28 -08:00
JoelKatz
e7f0b8eca6 Add DeliveredAmount to transaction metadata 2014-01-23 13:38:25 -08:00
JoelKatz
0bab6a9fec Add directory and order book iterators
This should fix the crossed order book bug.
* Change OfferCreate::takeOffers to use new iterators
* Change NetworkOps::getBookPage to use new iterators
* If we find an offer in the book but not the ledger, deindex it
2014-01-23 13:38:11 -08:00
David Schwartz
9486fc416c Support AccountTxnID and LastLedgerSequence. 2014-01-23 13:37:46 -08:00
JoelKatz
fb63aa737a Revert d2953f602e 2014-01-23 13:36:31 -08:00
JoelKatz
58a6ca1d3d Remove extraneous logging 2014-01-23 13:24:51 -08:00
JoelKatz
505f029edb Clean up 'destination_currencies' in new pathfinding reply 2014-01-23 13:24:43 -08:00
JoelKatz
815659b898 Replace a lock with an atomic in new pathfinding 2014-01-23 13:24:33 -08:00
JoelKatz
07d16f280c Clean up the checkAccept path to use the ledger sequence 2014-01-23 13:24:28 -08:00
JoelKatz
f88ddc947c Handle non-object in 'json' RPC method 2014-01-23 13:24:22 -08:00
Vinnie Falco
65ffdff40c Insight support for ResourceManager 2014-01-21 10:28:36 -05:00
Vinnie Falco
c95dccfec6 Move PathRequests to separate files 2014-01-21 10:28:36 -05:00
Vinnie Falco
fe83f471f5 Use duration in insight::Event, add chrono_util 2014-01-21 10:28:35 -05:00
sublimator
d2953f602e Error reporting tests 2014-01-21 10:28:35 -05:00
Vinnie Falco
9d07ddeae1 Improved human readable JSON-RPC error messages 2014-01-21 10:28:34 -05:00
Vinnie Falco
ef7810bc95 Add ScopedPointer::reset 2014-01-21 10:28:34 -05:00
David Schwartz
486539b3d3 Make offerDelete and fill Items more robust. 2014-01-21 10:28:34 -05:00
David Schwartz
990fb20a2a OrderBookDB::addOrderBook cleanup 2014-01-21 10:28:33 -05:00
Vinnie Falco
9b61a83721 Refactor, tidy up:
* Fix for msvc std::function return types
* Convert macros to constants
* Add Journal to PeerSet and use in InboundLedger
* Break lines and add annotations
* Remove some warnings
2014-01-21 10:28:33 -05:00
JoelKatz
f753519976 Ledger fetch improvements. Fetch policy improvements. 2014-01-17 16:06:15 -08:00
David Schwartz
663e38dcdd Locking and dispatching performance improvements:
* Avoid taking the master lock in most peer operations
* Dispatch recvGetLedger to JobQueue
* Dispatch consensus ledger fetches.
* Release master lock earlier in RPCHandler
2014-01-17 16:05:48 -08:00
Vinnie Falco
7570b6489d Fix and tidy up NodeStore
* Use std::unique_ptr
* Move globals to Manager singleton (fixes RocksDB exit crash)
2014-01-17 15:21:51 -05:00
Vinnie Falco
c341d1a71e Tidy up for C++11, and fixes:
* Remove shared_ptr legacy support
* Add make_unique support for pre-C++14 environments
* Fix comparison bug in sqdb
* Use std::shared_ptr in a few places
2014-01-17 12:19:04 -05:00
Vinnie Falco
fa10e90c9d Use abstract_clock 2014-01-17 12:19:04 -05:00
Vinnie Falco
68501763dd Refactor KeyCache 2014-01-17 12:19:04 -05:00
Vinnie Falco
cac1d555be Add std::make_unique 2014-01-17 12:19:03 -05:00
NATTSiM
25ff77c2fd Fix Clang compile and link errors 2014-01-16 17:18:05 -05:00
Vinnie Falco
2870c7f457 Workaround for MSVC std::function bug 2014-01-15 19:10:08 -08:00
JoelKatz
ab8d7a86ae Dispatch peerHas to JobQueue 2014-01-14 11:24:41 -08:00
JoelKatz
809359e81e Correctly handle empty account tree in ledger fetch 2014-01-14 11:24:32 -08:00
JoelKatz
6e4cd5bc9c Don't send nodes twice in getNodeFat 2014-01-14 11:24:01 -08:00
NATTSiM
de018bd582 Improved PropertyStream find and print routines 2014-01-13 21:51:31 -08:00
Vinnie Falco
544642a6ea Fix io_latency_probe hang on exit 2014-01-13 18:24:22 -08:00
JoelKatz
06737bb36f SHAMapSync bugfix. Cannot avoid push in getMissingNodes 2014-01-13 09:50:54 -08:00
JoelKatz
7efbfa2d20 Limit legacy pathfinding requests 2014-01-10 23:09:26 -08:00
Vinnie Falco
4d5df92cbc Add io_latency_probe 2014-01-10 22:54:00 -08:00
David Schwartz
1fcb2872b9 Reduce log priorities. 2014-01-10 22:54:00 -08:00
David Schwartz
00c87ca2dd Add LES::dirIsEmpty function to check if a directory is empty 2014-01-10 22:53:59 -08:00
JoelKatz
d474d68566 Order book subscribe cleanups. 2014-01-10 22:53:59 -08:00
David Schwartz
93e03804d0 SHAMapSync cleanups and performance improvements 2014-01-10 22:53:58 -08:00
JoelKatz
4591658160 PathRequests object to own all path requests. 2014-01-10 22:53:57 -08:00
JoelKatz
a2109b4bda Remove files inadvertently added 2014-01-10 22:53:57 -08:00
Vinnie Falco
deafea9c88 [REMOVE] Allow gcc 4.7 and later 2014-01-10 22:53:57 -08:00
Nicholas Dudfield
93f1a05f5c Update build for gcc 4.8.x:
* Use gcc 4.8.x, boost 1.54
* Honor CC,CXX,PATH environment variables
* Prevent compilation with unsupported toolchains
* Print g++ version during Travis build
* Run built-in unit tests after Travis build
2014-01-10 16:24:17 -08:00
Vinnie Falco
95a573b755 Set version to 0.20.1 2014-01-08 17:08:27 -08:00
Nik Bougalis
2a4623814c Don't log StatsD messages to the console by default 2014-01-08 16:57:47 -08:00
Vinnie Falco
1017adf743 Set version to 0.20.0 2014-01-08 16:15:12 -08:00
Vinnie Falco
34fb12344c Fix JobQueue 2014-01-08 14:55:10 -08:00
Vinnie Falco
ce3358bdf8 Improve diagnostics for ResourceManager 2014-01-08 11:18:46 -08:00
Vinnie Falco
1159dadfdb Fix missing jtACCEPT job limit 2014-01-08 11:18:45 -08:00
Vinnie Falco
62516ef07f Refactor TaggedCache 2014-01-07 21:14:14 -08:00
Vinnie Falco
eecd305efd Add std::hash <std::pair> specialization 2014-01-07 21:14:13 -08:00
Vinnie Falco
a83fa6b2b2 Fix warning in chrono_io 2014-01-07 21:14:07 -08:00
Vinnie Falco
b2feafa94c Use abstract_clock and improved tests, in ResourceManager
Conflicts:
	Builds/VisualStudio2012/RippleD.vcxproj.filters
2014-01-07 17:23:26 -08:00
Vinnie Falco
2d234e500d Add abstract_clock, manual_clock, chrono_io
Conflicts:
	src/beast/Builds/VisualStudio2012/beast.vcxproj.filters
2014-01-07 17:17:26 -08:00
Vinnie Falco
fee0e7b20e Fix bind in call to addJob 2014-01-07 17:08:01 -08:00
JoelKatz
a0f6429652 Add LedgerHolder class, use in LedgerMaster 2014-01-07 15:57:51 -08:00
JoelKatz
8f8b2ae4a3 Handle offers in quality directory but not in ledger 2014-01-07 15:57:50 -08:00
JoelKatz
9abdd16721 Release the master lock earlier in a few cases 2014-01-07 15:57:50 -08:00
JoelKatz
1e5963aeeb Move some operations from the I/O queue to the Job queue 2014-01-07 15:57:50 -08:00
JoelKatz
e25a83bb39 Some tiny bugfixes:
* Don't let ledger idle interval get too short
* Fix CBigNum::setuint256
* Fix SqliteStatement::isError
* Remove dead code, fix incorrect comments
* Check for NULL earlier in CKey constructors
* Prevent expire times from underflowing in TaggedCache
2014-01-07 15:57:49 -08:00
David Schwartz
e3a67b13ff Reset liquidity before retrying rippleCalc 2014-01-07 15:57:48 -08:00
JoelKatz
750cbb8399 Improvements because items in SHAMaps are immutable:
* SHAMapItem::getData is not needed
* SHAMapTreeNode::getItem is not needed
* SHAMapTreeNode::getData is not needed
* No need to copy them when constructing transactions
* No need to copy them when computing map deltas
* No need to copy them in deepCompare
* No need to copy them in SHAMapTreeNode's copy constructor
2014-01-07 15:57:48 -08:00
JoelKatz
045beb5f36 Concurrent SHAMap code
Use shared lock for SHAMap itself and concurrent map for nodes
2014-01-07 15:57:47 -08:00
JoelKatz
cd8234acba Pathfinding bugfix. Missing lock. 2014-01-07 15:57:46 -08:00
JoelKatz
de85a7c2bd Pathfinding improvements:
* Make each path request track whether it needs updating.
* Improve new request handling, reverse order for processing requests.
* Break to handle new requests immediately.
* Make mPathFindThread an integer rather than a bool. Allow two threads.
* For old pathfinding, if the ledger is unspecified, use the PathRequest's RippleLineCache.
* Log new pathfinding request latencies.
* Suspend processing requests if server is backed up.
2014-01-07 15:57:46 -08:00
Vinnie Falco
087301933a General refactoring, using C++11
* Remove broken RecycledObjectPool

* Fix beast::ServiceQueue using List instead of LockFreeStack

* Add class semaphore, fixes broken Semaphore

* Move crytpo module files to new beast directory

* Use c++11 replacements for boost and beast types:
  - std::atomic instead of beast::Atomic
  - std::function instead of boost::function, beast::function
  - std::unique_ptr instead of beast::ScopedPointer
  - std::shared_ptr instead of boost::shared_ptr

* Remove modules:
  - beast_db
  - beast_crypto
  - beast_extras

* Remove unnecessary classes:
  - AbstractFifo
  - AddConst
  - AtomicCounter
  - AtomicFlag
  - AtomicPointer
  - AtomicState
  - CopyConst
  - Expression
  - ForwardList
  - IfCond
  - Interval
  - IntrusiveArray
  - KeyvaDB
  - PointerToOther
  - PointerTraits
  - RemoveConst
  - RemoveConstVolatile
  - RemoveReference
  - RemoveVolatile
  - SharedObjectArray
  - SingleThreadedSharedObject
  - SophiaDB factory
  - SortedSet
  - WeakReference
  - beast::unique_ptr
2014-01-07 15:57:45 -08:00
JoelKatz
52333b8bd4 Fix a compiler warning in Ledger::visitStateItems 2014-01-07 15:48:50 -08:00
JoelKatz
3768b3c3ca Fix a pathfinding bug 2014-01-07 15:48:50 -08:00
JoelKatz
09b39e107d Fix subscribing to "real time" transactions. 2014-01-07 15:48:49 -08:00
Vinnie Falco
4b1155bf32 Improved diagnostic for RocksDB error codes
Conflicts:
	Builds/VisualStudio2012/RippleD.vcxproj.filters
2014-01-07 15:46:38 -08:00
Vinnie Falco
3c7fc31c95 Add ripple_common module
Conflicts:
	Builds/VisualStudio2012/RippleD.vcxproj.filters
2014-01-07 15:15:44 -08:00
Nicholas Dudfield
da3881a486 Make websocket-test the first test, and give custom timeouts of 1000ms 2014-01-05 13:40:47 +07:00
Nicholas Dudfield
ff12d9adaa Run server-test and websocket-test first. Show stderr upon abnormal rippled exit 2014-01-05 13:09:42 +07:00
Vinnie Falco
528cf56f80 Reduce StatsDCollector log verbosity 2014-01-02 19:32:27 -08:00
Vinnie Falco
0ebe3f1f35 Disable NameResolver temporarily 2014-01-02 16:12:55 -08:00
Vinnie Falco
328680b6cd Fix Resolver contract check 2014-01-02 16:10:49 -08:00
Vinnie Falco
f9dca105a6 Improved async stop for Resolver
Conflicts:
	src/ripple_app/peers/NameResolver.cpp
2014-01-02 15:38:03 -08:00
Vinnie Falco
3664db61e7 Fix static storage duration issue with some Journal logs 2014-01-02 15:21:33 -08:00
Vinnie Falco
49677aa799 Fix RippleBookType and unit tests 2013-12-29 11:33:50 -08:00
NATTSiM
27b771e2ba Fix clang compile 2013-12-27 17:46:51 -08:00
Vinnie Falco
6527cdfa97 Add RippleAsset types
Conflicts:
	Builds/VisualStudio2012/RippleD.vcxproj.filters
2013-12-27 17:21:11 -08:00
JoelKatz
b2dbe8ef83 Ledger acquire fixes/cleanups/logging
* Inbound ledger and SHAMapAddNode cleanup
    * Log acquire stats
    * Fix progress logic
    * Remove ledgers we no longer need to acquire
    * Stash stale state data in our fetch pack, it can still be useful
    * Stash in fetch pack if acquire terminated while job was pending
    * Account for duplicate/invalid nodes in a few cases previously missed
    * Dispatch each InboundLedger once (not per data)
    * Trigger only the "best" peer
    * Don't call tryAdvance on failed acquires
2013-12-27 16:48:03 -08:00
NATTSiM
9bdb0774ad Make InboundLedgers, LedgerConsensus abstract 2013-12-27 16:48:03 -08:00
Vinnie Falco
8c2ec2cfbe Add AbstractObject, cyclic_iterator, Journal improvements 2013-12-27 16:47:43 -08:00
Wolfgang Spraul
00f959ab7e removed boost_random 2013-12-26 14:31:22 -08:00
Vinnie Falco
f9c4070ad3 Add FetchPack unit test 2013-12-22 12:57:44 -08:00
Vinnie Falco
074325a7ea Inject SHAMap missing node handler dependency 2013-12-22 12:38:07 -08:00
JoelKatz
2f521a6a91 Build fetch packs correctly. 2013-12-22 12:38:07 -08:00
sublimator
07959b3cc9 Allow to full network limit in Amount::isLegalNet 2013-12-20 15:44:03 -08:00
The Doctor
21faf8eaeb Improvements to initscript and default configuration.
* Added absolute paths to the [node_db] and [debug_logfile] stanzas in the config file.

* Changed some tabs into spaces for consistency.

* Added directory tree sanity checking to initscript.

Signed-off-by: The Doctor <drwho@virtadpt.net>
2013-12-20 15:38:30 -08:00
Nik Bougalis
3e2b5dcc3d Hostname resolution support for Peers 2013-12-19 14:50:03 -08:00
Nik Bougalis
88a8433d31 Add reference counting to AsyncObject 2013-12-19 14:39:26 -08:00
Vinnie Falco
81d418007a Add CollectorManager for Beast.Insight support 2013-12-16 18:08:11 -08:00
Vinnie Falco
f88fcf55a3 Add Beast.Insight stats collection module 2013-12-16 12:22:25 -08:00
Vinnie Falco
561c8dea08 Add stl module for c++11 compatibility classes 2013-12-16 11:35:21 -08:00
David Schwartz
de92ac9e0b Websocket improvements:
* Log on_close/on_fail/on_open calls.
* Ping out connections.
* Improve ping logic.
* On websocket ping out, close abnormally.
* Avoid deadlock when shutting down websocket endpoint
2013-12-16 09:40:15 -08:00
JoelKatz
deead04a6a getFetchPack fixes, spread fetch pack requests. 2013-12-15 07:20:24 -08:00
JoelKatz
d4771a9b36 Fix missing call to setPubLedger on gap in published ledger stream. 2013-12-13 11:14:34 -08:00
JoelKatz
27b8415d0c During old pathfinding, unlock earlier. 2013-12-12 21:17:25 -08:00
David Schwartz
e1e81e5d97 Call pendSaveValidated without holding the ledger master lock 2013-12-12 21:17:20 -08:00
Vinnie Falco
3705680d68 Disable RocksDB for older compilers 2013-12-10 11:23:06 -08:00
Vinnie Falco
a01f546ae3 Use ScopedPointer instead of deprecated auto_ptr 2013-12-10 14:14:15 -05:00
Bryce Lynch
eabc905bac Add Debian-style initscript
* Add validators and validation_quorum from the v0.16 release notes.
* We keep having to tell people to do this during integration, let's just make it the default.
* Add comment about the log file location that states that it has to be absolute rather than relative after an integration troubleshoot earlier today.

Signed-off-by: Bryce Lynch <bryce@ripple.com>
2013-12-09 16:21:22 -08:00
JoelKatz
37588b6808 Avoid an extraneous test. 2013-12-09 00:52:40 -08:00
JoelKatz
071db75f04 Add a 1 MB payload limit to incoming websocket requests 2013-12-09 00:52:40 -08:00
David Schwartz
1e00940a90 Move some ledger cleaner helper functions into the ledger master. 2013-12-08 23:53:57 -08:00
JoelKatz
b984566480 Suppress a warning. 2013-12-08 23:53:47 -08:00
JoelKatz
51aef120a1 Pathfinding performance improvements:
* Use a single RippleLineCache, even for 'fast' requests
* Use a ledger copy to avoid stalling other code
2013-12-08 23:52:54 -08:00
JoelKatz
636d722e8d Memory-conserving changes to SHAMapTreeNode and visitLeavesInternal. 2013-12-08 23:52:54 -08:00
Vinnie Falco
e6da61120a Make AbstractObject unit test manual 2013-12-06 09:57:03 -08:00
JoelKatz
b901e0dcf3 Fix load stats in get_info 2013-12-05 22:04:42 -08:00
Vinnie Falco
177b3c93c4 Move DecayingSample to algorithm 2013-12-05 18:35:37 -08:00
JoelKatz
9996e4a57e The new recommended fee schedule is:
* Transaction fee: 10 drops
* Base reserve: 20 XRP
* Incremental reserve: 5 XRP
2013-12-04 19:07:58 -08:00
JoelKatz
4751b6a65c Fix for issue 211, fixes to NetworkOPs getTxsAccountB 2013-12-04 17:09:22 -08:00
David Schwartz
b3c79f5c2f Change visitLeaves to visit a snapshot so the ledger stays unlocked 2013-12-04 11:10:27 -08:00
David Schwartz
0e53105ab5 Remove dead code and fix a race condition in the node back end.
Race was between a store and a fetch, as follows:
1) Fetch: Search for the node, it is not found.
2) Store: Add the node to the database, remove the node from the negative cache.
3) Fetch: Add the node to the negative cache.
This would leave a node in the DB, cache, and negative cache.
2013-12-04 11:10:22 -08:00
Vinnie Falco
0f2a657196 Add double conversion for PropertyStream map items 2013-11-30 17:56:25 -08:00
Vinnie Falco
89aa2c7a6a Refactor some Journal::Sink members 2013-11-30 17:32:50 -08:00
Vinnie Falco
4c843b6c66 IPAddress fixes and algorithm comparison functors 2013-11-30 09:21:46 -08:00
Vinnie Falco
130c7c5c58 Refactor and fix some object arithmetic comparisons 2013-11-30 06:28:29 -08:00
Vinnie Falco
76c364ec2d Add const now() 2013-11-30 01:42:38 -08:00
Vinnie Falco
a549c94a15 Fix missing assert in UnitTest runner 2013-11-30 01:42:37 -08:00
Vinnie Falco
6de8a6907f Add AbstractObject 2013-11-30 01:42:37 -08:00
Vinnie Falco
fc31562052 Tidy doc comments 2013-11-29 23:44:36 -08:00
Vinnie Falco
cdaa65c07a Remove LightningDB database and backend 2013-11-27 15:14:21 -08:00
Vinnie Falco
8a278cf9d6 Remove sophia database and backend 2013-11-27 15:09:26 -08:00
Vinnie Falco
97cecc18ce Set version to 0.19.2 2013-11-27 13:10:19 -08:00
JoelKatz
536db23e14 Fix foundResume check in account_tx 2013-11-27 12:25:45 -08:00
2168 changed files with 270244 additions and 173858 deletions

2
.gitattributes vendored
View File

@@ -1,5 +1,5 @@
# Set default behaviour, in case users don't have core.autocrlf set.
* text=auto
#* text=auto
# These annoying files
rippled.1 binary

3
.gitignore vendored
View File

@@ -72,3 +72,6 @@ My Amplifier XE Results - RippleD
# Compiler intermediate output
/out.txt
# Build Log
rippled-build.log

View File

@@ -1,10 +1,58 @@
language: cpp
compiler:
- clang
- gcc
before_install:
- sudo apt-get update -qq
- sudo apt-get install -qq libboost1.48-all-dev protobuf-compiler libprotobuf-dev libssl-dev exuberant-ctags
script: scons && npm install && npm test
- sudo apt-get install -qq python-software-properties
- sudo add-apt-repository -y ppa:ubuntu-toolchain-r/test
- sudo add-apt-repository -y ppa:boost-latest/ppa
- sudo apt-get update -qq
- sudo apt-get install -qq g++-4.8
- sudo apt-get install -qq libboost1.55-all-dev
# We want debug symbols for boost as we install gdb later
- sudo apt-get install -qq libboost1.55-dbg
- | # Setup the BOOST_ROOT
export BOOST_ROOT=$HOME/boost_root
mkdir -p $BOOST_ROOT/stage
ln -s /usr/lib/x86_64-linux-gnu $BOOST_ROOT/stage/lib
ln -s /usr/include/boost $BOOST_ROOT/boost
- | # Try to patch boost
sudo patch /usr/include/boost/bimap/detail/debug/static_error.hpp Builds/travis/static_error.boost.patch
sudo patch /usr/include/boost/config/compiler/clang.hpp Builds/travis/clang.boost.patch
- sudo apt-get install -qq mlocate
- sudo updatedb
- sudo locate libboost | grep /lib | grep -e ".a$"
- sudo apt-get install -qq protobuf-compiler libprotobuf-dev libssl-dev exuberant-ctags
# We need gcc >= 4.8 for some c++11 features
- sudo apt-get install -qq gcc-4.8
- sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-4.8 40 --slave /usr/bin/g++ g++ /usr/bin/g++-4.8
- sudo update-alternatives --set gcc /usr/bin/gcc-4.8
# Stuff is gold. Nuff said ;)
- sudo apt-get -y install binutils-gold
# We can get a backtrace if the guy crashes
- sudo apt-get -y install gdb
# What versions are we ACTUALLY running?
- g++ -v
- clang -v
script:
# Set so any failing command will abort the build
- set -e
# If only we could do -j12 ;)
- scons
# See what we've actually built
- ldd ./build/rippled
# Run unittests (under gdb)
- | # create gdb script
echo "set env MALLOC_CHECK_=3" > script.gdb
echo "run" >> script.gdb
echo "backtrace full" >> script.gdb
# gdb --help
- cat script.gdb | gdb --ex 'set print thread-events off' --return-child-result --args ./build/rippled --unittest
# Run integration tests
- npm install
- npm test
notifications:
email:
false

41
Builds/ArchLinux/PKGBUILD Normal file
View File

@@ -0,0 +1,41 @@
# Maintainer: Roberto Catini <roberto.catini@gmail.com>
pkgname=rippled
pkgrel=1
pkgver=0
pkgdesc="Ripple peer-to-peer network daemon"
arch=('i686' 'x86_64')
url="https://github.com/ripple/rippled"
license=('custom:ISC')
depends=('protobuf' 'openssl' 'boost-libs')
makedepends=('git' 'scons' 'boost')
checkdepends=('nodejs')
backup=("etc/$pkgname/rippled.cfg")
source=("git://github.com/ripple/rippled.git#branch=master")
sha512sums=('SKIP')
pkgver() {
cd "$srcdir/$pkgname"
git describe --long --tags | sed -r 's/([^-]*-g)/r\1/;s/-/./g'
}
build() {
cd "$srcdir/$pkgname"
scons build/rippled
}
check() {
cd "$srcdir/$pkgname"
npm install
npm test
build/rippled --unittest
}
package() {
cd "$srcdir/$pkgname"
install -D -m644 LICENSE "$pkgdir/usr/share/licenses/$pkgname/LICENSE"
install -D build/rippled "$pkgdir/usr/bin/rippled"
install -D -m644 doc/rippled-example.cfg "$pkgdir/etc/$pkgname/rippled.cfg"
mkdir -p "$pkgdir/var/lib/$pkgname/db"
mkdir -p "$pkgdir/var/log/$pkgname"
}

30
Builds/Docker/Dockerfile Normal file
View File

@@ -0,0 +1,30 @@
# rippled
# use the ubuntu base image
FROM ubuntu
MAINTAINER Roberto Catini roberto.catini@gmail.com
# make sure the package repository is up to date
RUN apt-get update
RUN apt-get -y upgrade
# install the dependencies
RUN apt-get -y install git scons pkg-config protobuf-compiler libprotobuf-dev libssl-dev libboost1.55-all-dev
# download source code from official repository
RUN git clone https://github.com/ripple/rippled.git src; cd src/; git checkout master
# compile
RUN cd src/; scons build/rippled
# move to root directory and strip
RUN cp src/build/rippled rippled; strip rippled
# copy default config
RUN cp src/doc/rippled-example.cfg rippled.cfg
# clean source
RUN rm -r src
# launch rippled when launching the container
ENTRYPOINT ./rippled

View File

@@ -45,7 +45,6 @@ linux-g++:QMAKE_CXXFLAGS += \
-pthread
INCLUDEPATH += \
"../../src" \
"../../src/leveldb/" \
"../../src/leveldb/port" \
"../../src/leveldb/include" \
@@ -63,41 +62,42 @@ UI_HEADERS_DIR += ../../src/ripple_basics
# New style
#
SOURCES += \
../../src/ripple/beast/ripple_beast.cpp \
../../src/ripple/beast/ripple_beast.unity.cpp \
../../src/ripple/beast/ripple_beastc.c \
../../src/ripple/http/ripple_http.cpp \
../../src/ripple/json/ripple_json.cpp \
../../src/ripple/peerfinder/ripple_peerfinder.cpp \
../../src/ripple/resource/ripple_resource.cpp \
../../src/ripple/rpc/ripple_rpc.cpp \
../../src/ripple/sitefiles/ripple_sitefiles.cpp \
../../src/ripple/sophia/ripple_sophia.c \
../../src/ripple/sslutil/ripple_sslutil.cpp \
../../src/ripple/testoverlay/ripple_testoverlay.cpp \
../../src/ripple/types/ripple_types.cpp \
../../src/ripple/validators/ripple_validators.cpp
../../src/ripple/common/ripple_common.unity.cpp \
../../src/ripple/http/ripple_http.unity.cpp \
../../src/ripple/json/ripple_json.unity.cpp \
../../src/ripple/peerfinder/ripple_peerfinder.unity.cpp \
../../src/ripple/radmap/ripple_radmap.unity.cpp \
../../src/ripple/resource/ripple_resource.unity.cpp \
../../src/ripple/sitefiles/ripple_sitefiles.unity.cpp \
../../src/ripple/sslutil/ripple_sslutil.unity.cpp \
../../src/ripple/testoverlay/ripple_testoverlay.unity.cpp \
../../src/ripple/types/ripple_types.unity.cpp \
../../src/ripple/validators/ripple_validators.unity.cpp
# ---------
# Old style
#
SOURCES += \
../../src/ripple_app/ripple_app.cpp \
../../src/ripple_app/ripple_app_pt1.cpp \
../../src/ripple_app/ripple_app_pt2.cpp \
../../src/ripple_app/ripple_app_pt3.cpp \
../../src/ripple_app/ripple_app_pt4.cpp \
../../src/ripple_app/ripple_app_pt5.cpp \
../../src/ripple_app/ripple_app_pt6.cpp \
../../src/ripple_app/ripple_app_pt7.cpp \
../../src/ripple_app/ripple_app_pt8.cpp \
../../src/ripple_basics/ripple_basics.cpp \
../../src/ripple_core/ripple_core.cpp \
../../src/ripple_data/ripple_data.cpp \
../../src/ripple_hyperleveldb/ripple_hyperleveldb.cpp \
../../src/ripple_leveldb/ripple_leveldb.cpp \
../../src/ripple_mdb/ripple_mdb.c \
../../src/ripple_net/ripple_net.cpp \
../../src/ripple_websocket/ripple_websocket.cpp
../../src/ripple_app/ripple_app.unity.cpp \
../../src/ripple_app/ripple_app_pt1.unity.cpp \
../../src/ripple_app/ripple_app_pt2.unity.cpp \
../../src/ripple_app/ripple_app_pt3.unity.cpp \
../../src/ripple_app/ripple_app_pt4.unity.cpp \
../../src/ripple_app/ripple_app_pt5.unity.cpp \
../../src/ripple_app/ripple_app_pt6.unity.cpp \
../../src/ripple_app/ripple_app_pt7.unity.cpp \
../../src/ripple_app/ripple_app_pt8.unity.cpp \
../../src/ripple_basics/ripple_basics.unity.cpp \
../../src/ripple_core/ripple_core.unity.cpp \
../../src/ripple_data/ripple_data.unity.cpp \
../../src/ripple_hyperleveldb/ripple_hyperleveldb.unity.cpp \
../../src/ripple_leveldb/ripple_leveldb.unity.cpp \
../../src/ripple_net/ripple_net.unity.cpp \
../../src/ripple_overlay/ripple_overlay.unity.cpp \
../../src/ripple_rpc/ripple_rpc.unity.cpp \
../../src/ripple_websocket/ripple_websocket.unity.cpp
LIBS += \
-lboost_date_time-mt\

View File

@@ -1,30 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ImportGroup Label="PropertySheets" />
<PropertyGroup Label="UserMacros">
<RepoDir>..\..</RepoDir>
<SrcDir>$(RepoDir)\src\cpp\ripple</SrcDir>
</PropertyGroup>
<PropertyGroup>
<OutDir>$(RepoDir)\build\VisualStudio2010\$(Configuration).$(Platform)\</OutDir>
</PropertyGroup>
<PropertyGroup>
<IntDir>$(RepoDir)\build\obj\VisualStudio2010\$(Configuration).$(Platform)\</IntDir>
</PropertyGroup>
<ItemDefinitionGroup>
<ClCompile>
<AdditionalIncludeDirectories>$(RepoDir);$(RepoDir)\src\cpp\leveldb;$(RepoDir)\src\cpp\leveldb\include;$(RepoDir)\src\cpp\protobuf\src;$(RepoDir)\src\cpp\protobuf\vsprojects;$(RepoDir)\build\proto;$(RepoDir)\Subtrees\beast;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>USE_LEVELDB;BOOST_TEST_ALTERNATIVE_INIT_API;BOOST_TEST_NO_MAIN;_WIN32_WINNT=0x0600;_SCL_SECURE_NO_WARNINGS;_CRT_SECURE_NO_WARNINGS;WIN32;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<WarningLevel>Level3</WarningLevel>
<MultiProcessorCompilation>true</MultiProcessorCompilation>
</ClCompile>
</ItemDefinitionGroup>
<ItemGroup>
<BuildMacro Include="RepoDir">
<Value>$(RepoDir)</Value>
</BuildMacro>
<BuildMacro Include="SrcDir">
<Value>$(SrcDir)</Value>
</BuildMacro>
</ItemGroup>
</Project>

View File

@@ -1,20 +0,0 @@

Microsoft Visual Studio Solution File, Format Version 11.00
# Visual Studio 2010
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "RippleD", "RippleD.vcxproj", "{EE95954F-3D34-4FB1-ADBD-FE8395233026}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Win32 = Debug|Win32
Release|Win32 = Release|Win32
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{EE95954F-3D34-4FB1-ADBD-FE8395233026}.Debug|Win32.ActiveCfg = Debug|Win32
{EE95954F-3D34-4FB1-ADBD-FE8395233026}.Debug|Win32.Build.0 = Debug|Win32
{EE95954F-3D34-4FB1-ADBD-FE8395233026}.Release|Win32.ActiveCfg = Release|Win32
{EE95954F-3D34-4FB1-ADBD-FE8395233026}.Release|Win32.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

View File

@@ -1,98 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{EE95954F-3D34-4FB1-ADBD-FE8395233026}</ProjectGuid>
<Keyword>Win32Proj</Keyword>
<RootNamespace>RippleD</RootNamespace>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<CharacterSet>NotSet</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>NotSet</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
<Import Project="RippleD.props" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>WIN32;_DEBUG;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
<MinimalRebuild>false</MinimalRebuild>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<PrecompiledHeader>
</PrecompiledHeader>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<PreprocessorDefinitions>WIN32;NDEBUG;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<MinimalRebuild>false</MinimalRebuild>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="..\..\modules\ripple_app\ripple_app_pt1.cpp" />
<ClCompile Include="..\..\modules\ripple_app\ripple_app_pt2.cpp" />
<ClCompile Include="..\..\modules\ripple_app\ripple_app_pt3.cpp" />
<ClCompile Include="..\..\modules\ripple_app\ripple_app_pt4.cpp" />
<ClCompile Include="..\..\modules\ripple_basics\ripple_basics.cpp" />
<ClCompile Include="..\..\modules\ripple_data\ripple_data.cpp" />
<ClCompile Include="..\..\src\cpp\database\sqlite3.c" />
<ClCompile Include="..\..\src\cpp\leveldb_core.cpp" />
<ClCompile Include="..\..\src\cpp\protobuf_core.cpp" />
<ClCompile Include="..\..\src\cpp\websocket_core.cpp" />
<ClCompile Include="..\..\Subtrees\beast\modules\beast_basics\beast_basics.cpp" />
<ClCompile Include="..\..\Subtrees\beast\modules\beast_core\beast_core.cpp" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@@ -1,37 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<ClCompile Include="..\..\modules\ripple_app\ripple_app_pt1.cpp" />
<ClCompile Include="..\..\modules\ripple_app\ripple_app_pt2.cpp" />
<ClCompile Include="..\..\modules\ripple_app\ripple_app_pt3.cpp" />
<ClCompile Include="..\..\modules\ripple_app\ripple_app_pt4.cpp" />
<ClCompile Include="..\..\modules\ripple_basics\ripple_basics.cpp" />
<ClCompile Include="..\..\modules\ripple_data\ripple_data.cpp" />
<ClCompile Include="..\..\Subtrees\beast\modules\beast_basics\beast_basics.cpp">
<Filter>Subtrees</Filter>
</ClCompile>
<ClCompile Include="..\..\Subtrees\beast\modules\beast_core\beast_core.cpp">
<Filter>Subtrees</Filter>
</ClCompile>
<ClCompile Include="..\..\src\cpp\leveldb_core.cpp">
<Filter>Subtrees</Filter>
</ClCompile>
<ClCompile Include="..\..\src\cpp\protobuf_core.cpp">
<Filter>Subtrees</Filter>
</ClCompile>
<ClCompile Include="..\..\src\cpp\websocket_core.cpp">
<Filter>Subtrees</Filter>
</ClCompile>
<ClCompile Include="..\..\src\cpp\database\sqlite3.c">
<Filter>Subtrees</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<Filter Include="Ripple">
<UniqueIdentifier>{63db902e-0e7a-42d1-b5f5-663e4b48786c}</UniqueIdentifier>
</Filter>
<Filter Include="Subtrees">
<UniqueIdentifier>{469e8a0a-64bf-4fa1-8b6f-81207db68577}</UniqueIdentifier>
</Filter>
</ItemGroup>
</Project>

View File

@@ -1,36 +0,0 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 2012
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "RippleD", "RippleD.vcxproj", "{B7F39ECD-473C-484D-BC34-31F8362506A5}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "beast", "..\..\src\beast\Builds\VisualStudio2012\beast.vcxproj", "{73C5A0F0-7629-4DE7-9194-BE7AC6C19535}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Win32 = Debug|Win32
Debug|x64 = Debug|x64
Release|Win32 = Release|Win32
Release|x64 = Release|x64
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{B7F39ECD-473C-484D-BC34-31F8362506A5}.Debug|Win32.ActiveCfg = Debug|Win32
{B7F39ECD-473C-484D-BC34-31F8362506A5}.Debug|Win32.Build.0 = Debug|Win32
{B7F39ECD-473C-484D-BC34-31F8362506A5}.Debug|x64.ActiveCfg = Debug|x64
{B7F39ECD-473C-484D-BC34-31F8362506A5}.Debug|x64.Build.0 = Debug|x64
{B7F39ECD-473C-484D-BC34-31F8362506A5}.Release|Win32.ActiveCfg = Release|Win32
{B7F39ECD-473C-484D-BC34-31F8362506A5}.Release|Win32.Build.0 = Release|Win32
{B7F39ECD-473C-484D-BC34-31F8362506A5}.Release|x64.ActiveCfg = Release|x64
{B7F39ECD-473C-484D-BC34-31F8362506A5}.Release|x64.Build.0 = Release|x64
{73C5A0F0-7629-4DE7-9194-BE7AC6C19535}.Debug|Win32.ActiveCfg = Debug|Win32
{73C5A0F0-7629-4DE7-9194-BE7AC6C19535}.Debug|Win32.Build.0 = Debug|Win32
{73C5A0F0-7629-4DE7-9194-BE7AC6C19535}.Debug|x64.ActiveCfg = Debug|x64
{73C5A0F0-7629-4DE7-9194-BE7AC6C19535}.Debug|x64.Build.0 = Debug|x64
{73C5A0F0-7629-4DE7-9194-BE7AC6C19535}.Release|Win32.ActiveCfg = Release|Win32
{73C5A0F0-7629-4DE7-9194-BE7AC6C19535}.Release|Win32.Build.0 = Release|Win32
{73C5A0F0-7629-4DE7-9194-BE7AC6C19535}.Release|x64.ActiveCfg = Release|x64
{73C5A0F0-7629-4DE7-9194-BE7AC6C19535}.Release|x64.Build.0 = Release|x64
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

View File

@@ -1,31 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ImportGroup Label="PropertySheets" />
<PropertyGroup Label="UserMacros">
<RepoDir>..\..</RepoDir>
</PropertyGroup>
<PropertyGroup>
<OutDir>$(RepoDir)\build\VisualStudio2012\$(Configuration).$(Platform)\</OutDir>
<IntDir>$(RepoDir)\build\obj\VisualStudio2012\$(Configuration).$(Platform)\</IntDir>
<TargetName>rippled</TargetName>
</PropertyGroup>
<ItemDefinitionGroup>
<ClCompile>
<PreprocessorDefinitions>_VARIADIC_MAX=10;_WIN32_WINNT=0x0600;_SCL_SECURE_NO_WARNINGS;_CRT_SECURE_NO_WARNINGS;WIN32;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<MultiProcessorCompilation>true</MultiProcessorCompilation>
<WarningLevel>Level3</WarningLevel>
<AdditionalIncludeDirectories>$(RepoDir)\src\protobuf\src;$(RepoDir)\src\protobuf\vsprojects;$(RepoDir)\src;$(RepoDir)\src\leveldb;$(RepoDir)\src\leveldb\include;$(RepoDir)\build\proto;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<AdditionalOptions>/bigobj %(AdditionalOptions)</AdditionalOptions>
<ExceptionHandling>Async</ExceptionHandling>
<DisableSpecificWarnings>4018;4244</DisableSpecificWarnings>
</ClCompile>
<Link>
<AdditionalDependencies>Shlwapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<BuildMacro Include="RepoDir">
<Value>$(RepoDir)</Value>
</BuildMacro>
</ItemGroup>
</Project>

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,4 @@
RippleD.vcxproj -text
RippleD.vcxproj.filters -text

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,26 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Express 2013 for Windows Desktop
VisualStudioVersion = 12.0.30110.0
MinimumVisualStudioVersion = 10.0.40219.1
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "RippleD", "RippleD.vcxproj", "{26B7D9AC-1A80-8EF8-6703-D061F1BECB75}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Win32 = Debug|Win32
Debug|x64 = Debug|x64
Release|Win32 = Release|Win32
Release|x64 = Release|x64
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{26B7D9AC-1A80-8EF8-6703-D061F1BECB75}.Debug|Win32.ActiveCfg = debug|x64
{26B7D9AC-1A80-8EF8-6703-D061F1BECB75}.Debug|x64.ActiveCfg = debug|x64
{26B7D9AC-1A80-8EF8-6703-D061F1BECB75}.Debug|x64.Build.0 = debug|x64
{26B7D9AC-1A80-8EF8-6703-D061F1BECB75}.Release|Win32.ActiveCfg = release|x64
{26B7D9AC-1A80-8EF8-6703-D061F1BECB75}.Release|x64.ActiveCfg = release|x64
{26B7D9AC-1A80-8EF8-6703-D061F1BECB75}.Release|x64.Build.0 = release|x64
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

53
Builds/rpm/rippled.spec Normal file
View File

@@ -0,0 +1,53 @@
Name: rippled
Version: 0.26.1
Release: 1%{?dist}
Summary: Ripple peer-to-peer network daemon
Group: Applications/Internet
License: ISC
URL: https://github.com/ripple/rippled
# curl -L -o SOURCES/rippled-release.zip https://github.com/ripple/rippled/archive/release.zip
Source0: rippled-release.zip
BuildRoot: %(mktemp -ud %{_tmppath}/%{name}-%{version}-%{release}-XXXXXX)
BuildRequires: gcc-c++ scons openssl-devel protobuf-devel
Requires: protobuf openssl
%description
Rippled is the server component of the Ripple network.
%prep
%setup -n rippled-release
%build
# Assume boost is manually installed
export RIPPLED_BOOST_HOME=/usr/local/boost_1_55_0
scons -j `grep -c processor /proc/cpuinfo` build/rippled
%install
rm -rf %{buildroot}
mkdir -p %{buildroot}/usr/share/%{name}
cp LICENSE %{buildroot}/usr/share/%{name}/
mkdir -p %{buildroot}/usr/bin
cp build/rippled %{buildroot}/usr/bin/rippled
mkdir -p %{buildroot}/etc/%{name}
cp doc/rippled-example.cfg %{buildroot}/etc/%{name}/rippled.cfg
mkdir -p %{buildroot}/var/lib/%{name}/db
mkdir -p %{buildroot}/var/log/%{name}
%clean
rm -rf %{buildroot}
%files
%defattr(-,root,root,-)
/usr/bin/rippled
/usr/share/rippled/LICENSE
/etc/rippled/rippled-example.cfg

View File

@@ -0,0 +1,13 @@
--- /usr/include/boost/config/compiler/clang.hpp 2013-07-20 13:17:10.000000000 -0400
+++ /usr/include/boost/config/compiler/clang.rippled.hpp 2014-03-11 16:40:51.000000000 -0400
@@ -39,6 +39,10 @@
// Clang supports "long long" in all compilation modes.
#define BOOST_HAS_LONG_LONG
+#if defined(__SIZEOF_INT128__)
+# define BOOST_HAS_INT128
+#endif
+
//
// Dynamic shared object (DSO) and dynamic-link library (DLL) support
//

View File

@@ -0,0 +1,10 @@
--- /usr/include/boost/bimap/detail/debug/static_error.hpp 2008-03-22 17:45:55.000000000 -0400
+++ /usr/include/boost/bimap/detail/debug/static_error.rippled.hpp 2014-03-12 19:40:05.000000000 -0400
@@ -25,7 +25,6 @@
// a static error.
/*===========================================================================*/
#define BOOST_BIMAP_STATIC_ERROR(MESSAGE,VARIABLES) \
- struct BOOST_PP_CAT(BIMAP_STATIC_ERROR__,MESSAGE) {}; \
BOOST_MPL_ASSERT_MSG(false, \
BOOST_PP_CAT(BIMAP_STATIC_ERROR__,MESSAGE), \
VARIABLES)

BIN
LICENSE

Binary file not shown.

View File

@@ -1,8 +1,8 @@
#Ripple - P2P Payment Network
#rippled - Ripple P2P server
##[![Build Status](https://ci.ripple.com/jenkins/buildStatus/icon?job=rippled)](https://ci.ripple.com/jenkins/job/rippled/)
##[![Build Status](https://travis-ci.org/ripple/rippled.png?branch=develop)](https://travis-ci.org/ripple/rippled)
This is the repository for Ripple's `rippled`, reference P2P network server.
This is the repository for Ripple's `rippled`, reference P2P server.
###Build instructions:
* https://ripple.com/wiki/Rippled_build_instructions
@@ -33,20 +33,8 @@ README for more details.
Javascript / Mocha tests.
## License
Provided under the terms of the ISC License:
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
Ripple is open source and permissively licensed under the ISC license. See the
LICENSE file for more details.
###For more information:
* https://ripple.com

View File

@@ -1,290 +1,605 @@
# rippled SConstruct
#
# Ripple - SConstruct
#
'''
import commands
import copy
import glob
Target Builds
----------------------------------------------------------------------------
<none> Same as 'install'
install Default target and copies it to build/rippled (default)
all All available variants
debug All available debug variants
release All available release variants
clang All clang variants
clang.debug clang debug variant
clang.release clang release variant
gcc All gcc variants
gcc.debug gcc debug variant
gcc.release gcc release variant
msvc All msvc variants
msvc.debug MSVC debug variant
msvc.release MSVC release variant
vcxproj Generate Visual Studio 2013 project file
If the clang toolchain is detected, then the default target will use it, else
the gcc toolchain will be used. On Windows environments, the MSVC toolchain is
also detected.
'''
#
'''
TODO
- Fix git-describe support
- Fix printing exemplar command lines
- Fix toolchain detection
'''
#-------------------------------------------------------------------------------
import collections
import os
import platform
import re
import subprocess
import sys
import textwrap
import time
import SCons.Action
OSX = bool(platform.mac_ver()[0])
FreeBSD = bool('FreeBSD' == platform.system())
Linux = bool('Linux' == platform.system())
Ubuntu = bool(Linux and 'Ubuntu' == platform.linux_distribution()[0])
Debian = bool(Linux and 'debian' == platform.linux_distribution()[0])
Archlinux = bool(Linux and ('','','') == platform.linux_distribution()) #Arch still has issues with the platform module
sys.path.append(os.path.join('src', 'beast', 'site_scons'))
#
# We expect this to be set
#
BOOST_HOME = os.environ.get("RIPPLED_BOOST_HOME", None)
import Beast
#------------------------------------------------------------------------------
def parse_time(t):
return time.strptime(t, '%a %b %d %H:%M:%S %Z %Y')
CHECK_PLATFORMS = 'Debian', 'Ubuntu'
CHECK_COMMAND = 'openssl version -a'
CHECK_LINE = 'built on: '
BUILD_TIME = 'Mon Apr 7 20:33:19 UTC 2014'
OPENSSL_ERROR = ('Your openSSL was built on %s; '
'rippled needs a version built on or after %s.')
def check_openssl():
if Beast.system.platform in CHECK_PLATFORMS:
for line in subprocess.check_output(CHECK_COMMAND.split()).splitlines():
if line.startswith(CHECK_LINE):
line = line[len(CHECK_LINE):]
if parse_time(line) < parse_time(BUILD_TIME):
raise Exception(OPENSSL_ERROR % (line, BUILD_TIME))
else:
break
else:
raise Exception("Didn't find any '%s' line in '$ %s'" %
(CHECK_LINE, CHECK_COMMAND))
if OSX or Ubuntu or Debian or Archlinux:
CTAGS = 'ctags'
elif FreeBSD:
CTAGS = 'exctags'
else:
CTAGS = 'exuberant-ctags'
def import_environ(env):
'''Imports environment settings into the construction environment'''
def set(keys):
if type(keys) == list:
for key in keys:
set(key)
return
if keys in os.environ:
value = os.environ[keys]
env[keys] = value
set(['GNU_CC', 'GNU_CXX', 'GNU_LINK'])
set(['CLANG_CC', 'CLANG_CXX', 'CLANG_LINK'])
#
# scons tools
#
def detect_toolchains(env):
def is_compiler(comp_from, comp_to):
return comp_from and comp_to in comp_from
env = Environment(
tools = ['default', 'protoc']
)
def detect_clang(env):
n = sum(x in env for x in ['CLANG_CC', 'CLANG_CXX', 'CLANG_LINK'])
if n > 0:
if n == 3:
return True
raise ValueError('CLANG_CC, CLANG_CXX, and CLANG_LINK must be set together')
cc = env.get('CC')
cxx = env.get('CXX')
link = env.subst(env.get('LINK'))
if (cc and cxx and link and
is_compiler(cc, 'clang') and
is_compiler(cxx, 'clang') and
is_compiler(link, 'clang')):
env['CLANG_CC'] = cc
env['CLANG_CXX'] = cxx
env['CLANG_LINK'] = link
return True
cc = env.WhereIs('clang')
cxx = env.WhereIs('clang++')
link = cxx
if (is_compiler(cc, 'clang') and
is_compiler(cxx, 'clang') and
is_compiler(link, 'clang')):
env['CLANG_CC'] = cc
env['CLANG_CXX'] = cxx
env['CLANG_LINK'] = link
return True
env['CLANG_CC'] = 'clang'
env['CLANG_CXX'] = 'clang++'
env['CLANG_LINK'] = env['LINK']
return False
# Use a newer gcc on FreeBSD
if FreeBSD:
env.Replace(CC = 'gcc46')
env.Replace(CXX = 'g++46')
env.Append(CCFLAGS = ['-Wl,-rpath=/usr/local/lib/gcc46'])
env.Append(LINKFLAGS = ['-Wl,-rpath=/usr/local/lib/gcc46'])
def detect_gcc(env):
n = sum(x in env for x in ['GNU_CC', 'GNU_CXX', 'GNU_LINK'])
if n > 0:
if n == 3:
return True
raise ValueError('GNU_CC, GNU_CXX, and GNU_LINK must be set together')
cc = env.get('CC')
cxx = env.get('CXX')
link = env.subst(env.get('LINK'))
if (cc and cxx and link and
is_compiler(cc, 'gcc') and
is_compiler(cxx, 'g++') and
is_compiler(link, 'g++')):
env['GNU_CC'] = cc
env['GNU_CXX'] = cxx
env['GNU_LINK'] = link
return True
cc = env.WhereIs('gcc')
cxx = env.WhereIs('g++')
link = cxx
if (is_compiler(cc, 'gcc') and
is_compiler(cxx, 'g++') and
is_compiler(link, 'g++')):
env['GNU_CC'] = cc
env['GNU_CXX'] = cxx
env['GNU_LINK'] = link
return True
env['GNU_CC'] = 'gcc'
env['GNU_CXX'] = 'g++'
env['GNU_LINK'] = env['LINK']
return False
if OSX:
env.Replace(CC= 'clang')
env.Replace(CXX= 'clang++')
env.Append(CXXFLAGS = ['-std=c++11', '-stdlib=libc++'])
env.Append(LINKFLAGS='-stdlib=libc++')
env['FRAMEWORKS'] = ['AppKit']
toolchains = []
if detect_clang(env):
toolchains.append('clang')
if detect_gcc(env):
toolchains.append('gcc')
if env.Detect('cl'):
toolchains.append('msvc')
return toolchains
GCC_VERSION = re.split('\.', commands.getoutput(env['CXX'] + ' -dumpversion'))
def files(base):
def _iter(base):
for parent, _, files in os.walk(base):
for path in files:
path = os.path.join(parent, path)
yield os.path.normpath(path)
return list(_iter(base))
# Add support for ccache. Usage: scons ccache=1
ccache = ARGUMENTS.get('ccache', 0)
if int(ccache):
env.Prepend(CC = ['ccache'])
env.Prepend(CXX = ['ccache'])
ccache_dir = os.getenv('CCACHE_DIR')
if ccache_dir:
env.Replace(CCACHE_DIR = ccache_dir)
def print_coms(target, source, env):
'''Display command line exemplars for an environment'''
print ('Target: ' + Beast.yellow(str(target[0])))
# TODO Add 'PROTOCCOM' to this list and make it work
Beast.print_coms(['CXXCOM', 'CCCOM', 'LINKCOM'], env)
#
# Builder for CTags
#
ctags = Builder(action = '$CTAGS $CTAGSOPTIONS -f $TARGET $SOURCES')
env.Append(BUILDERS = { 'CTags' : ctags })
if OSX:
env.Replace(CTAGS = CTAGS)
else:
env.Replace(CTAGS = CTAGS, CTAGSOPTIONS = '--tag-relative')
#-------------------------------------------------------------------------------
# Use openssl
env.ParseConfig('pkg-config --static --cflags --libs openssl')
# Use protobuf
env.ParseConfig('pkg-config --static --cflags --libs protobuf')
# Set construction variables for the base environment
def config_base(env):
if False:
env.Replace(
CCCOMSTR='Compiling ' + Beast.blue('$SOURCES'),
CXXCOMSTR='Compiling ' + Beast.blue('$SOURCES'),
LINKCOMSTR='Linking ' + Beast.blue('$TARGET'),
)
check_openssl()
# Beast uses kvm on FreeBSD
if FreeBSD:
env.Append (
LIBS = [
'kvm'
env.Append(CPPDEFINES=['OPENSSL_NO_SSL2'])
#git = Beast.Git(env) # TODO(TOM)
if False: #git.exists:
env.Append(CPPDEFINES={'GIT_COMMIT_ID' : '"%s"' % git.commit_id})
try:
BOOST_ROOT = os.path.normpath(os.environ['BOOST_ROOT'])
env.Append(CPPPATH=[
BOOST_ROOT,
])
env.Append(LIBPATH=[
os.path.join(BOOST_ROOT, 'stage', 'lib'),
])
env['BOOST_ROOT'] = BOOST_ROOT
except KeyError:
pass
if Beast.system.windows:
try:
OPENSSL_ROOT = os.path.normpath(os.environ['OPENSSL_ROOT'])
env.Append(CPPPATH=[
os.path.join(OPENSSL_ROOT, 'include'),
])
env.Append(LIBPATH=[
os.path.join(OPENSSL_ROOT, 'lib', 'VC', 'static'),
])
except KeyError:
pass
elif Beast.system.osx:
OSX_OPENSSL_ROOT = '/usr/local/Cellar/openssl/'
most_recent = sorted(os.listdir(OSX_OPENSSL_ROOT))[-1]
openssl = os.path.join(OSX_OPENSSL_ROOT, most_recent)
env.Prepend(CPPPATH='%s/include' % openssl)
env.Prepend(LIBPATH=['%s/lib' % openssl])
# Set toolchain and variant specific construction variables
def config_env(toolchain, variant, env):
if variant == 'debug':
env.Append(CPPDEFINES=['DEBUG', '_DEBUG'])
elif variant == 'release':
env.Append(CPPDEFINES=['NDEBUG'])
if toolchain in Split('clang gcc'):
if Beast.system.linux:
env.ParseConfig('pkg-config --static --cflags --libs openssl')
env.ParseConfig('pkg-config --static --cflags --libs protobuf')
env.Prepend(CCFLAGS=['-Wall'])
env.Append(CCFLAGS=[
'-Wno-sign-compare',
'-Wno-char-subscripts',
'-Wno-format',
'-Wno-deprecated-register'
])
env.Append(CXXFLAGS=[
'-frtti',
'-std=c++11',
'-Wno-invalid-offsetof'])
if Beast.system.osx:
env.Append(CPPDEFINES={
'BEAST_COMPILE_OBJECTIVE_CPP': 1,
})
# These should be the same regardless of platform...
if Beast.system.osx:
env.Append(CCFLAGS=[
'-Wno-deprecated',
'-Wno-deprecated-declarations',
'-Wno-unused-variable',
'-Wno-unused-function',
])
else:
if toolchain == 'gcc':
env.Append(CCFLAGS=[
'-Wno-unused-but-set-variable'
])
boost_libs = [
'boost_date_time',
'boost_filesystem',
'boost_program_options',
'boost_regex',
'boost_system',
'boost_thread'
]
)
# We prefer static libraries for boost
if env.get('BOOST_ROOT'):
static_libs = ['%s/stage/lib/lib%s.a' % (env['BOOST_ROOT'], l) for
l in boost_libs]
if all(os.path.exists(f) for f in static_libs):
boost_libs = [File(f) for f in static_libs]
# The required version of boost is documented in the README file.
BOOST_LIBS = [
'boost_date_time',
'boost_filesystem',
'boost_program_options',
'boost_regex',
'boost_system',
'boost_thread',
'boost_random',
]
env.Append(LIBS=boost_libs)
env.Append(LIBS=['dl'])
# We whitelist platforms where the non -mt version is linked with pthreads. This
# can be verified with: ldd libboost_filesystem.* If a threading library is
# included the platform can be whitelisted.
if FreeBSD or Ubuntu or Archlinux or OSX:
# non-mt libs do link with pthreads.
env.Append(
LIBS = BOOST_LIBS
)
else:
env.Append(
LIBS = [l + '-mt' for l in BOOST_LIBS]
)
if Beast.system.osx:
env.Append(LIBS=[
'crypto',
'protobuf',
'ssl',
])
env.Append(FRAMEWORKS=[
'AppKit',
'Foundation'
])
else:
env.Append(LIBS=['rt'])
env.Append(LINKFLAGS=[
'-rdynamic'
])
if variant == 'debug':
env.Append(CCFLAGS=[
'-g'
])
elif variant == 'release':
env.Append(CCFLAGS=[
'-O3',
'-fno-strict-aliasing'
])
if toolchain == 'clang':
if Beast.system.osx:
env.Replace(CC='clang', CXX='clang++', LINK='clang++')
elif 'CLANG_CC' in env and 'CLANG_CXX' in env and 'CLANG_LINK' in env:
env.Replace(CC=env['CLANG_CC'], CXX=env['CLANG_CXX'], LINK=env['CLANG_LINK'])
# C and C++
# Add '-Wshorten-64-to-32'
env.Append(CCFLAGS=[])
# C++ only
env.Append(CXXFLAGS=['-Wno-mismatched-tags'])
elif toolchain == 'gcc':
if 'GNU_CC' in env and 'GNU_CXX' in env and 'GNU_LINK' in env:
env.Replace(CC=env['GNU_CC'], CXX=env['GNU_CXX'], LINK=env['GNU_LINK'])
# Why is this only for gcc?!
env.Append(CCFLAGS=['-Wno-unused-local-typedefs'])
elif toolchain == 'msvc':
env.Append (CPPPATH=[
os.path.join('src', 'protobuf', 'src'),
os.path.join('src', 'protobuf', 'vsprojects'),
])
env.Append(CCFLAGS=[
'/bigobj', # Increase object file max size
'/EHa', # ExceptionHandling all
'/fp:precise', # Floating point behavior
'/Gd', # __cdecl calling convention
'/Gm-', # Minimal rebuild: disabled
'/GR', # Enable RTTI
'/Gy-', # Function level linking: disabled
'/FS',
'/MP', # Multiprocessor compilation
'/openmp-', # pragma omp: disabled
'/Zc:forScope', # Language extension: for scope
'/Zi', # Generate complete debug info
'/errorReport:none', # No error reporting to Internet
'/nologo', # Suppress login banner
#'/Fd${TARGET}.pdb', # Path: Program Database (.pdb)
'/W3', # Warning level 3
'/WX-', # Disable warnings as errors
'/wd"4018"',
'/wd"4244"',
'/wd"4267"',
'/wd"4800"', # Disable C4800 (int to bool performance)
])
env.Append(CPPDEFINES={
'_WIN32_WINNT' : '0x6000',
})
env.Append(CPPDEFINES=[
'_SCL_SECURE_NO_WARNINGS',
'_CRT_SECURE_NO_WARNINGS',
'WIN32_CONSOLE',
])
env.Append(LIBS=[
'ssleay32MT.lib',
'libeay32MT.lib',
'Shlwapi.lib',
'kernel32.lib',
'user32.lib',
'gdi32.lib',
'winspool.lib',
'comdlg32.lib',
'advapi32.lib',
'shell32.lib',
'ole32.lib',
'oleaut32.lib',
'uuid.lib',
'odbc32.lib',
'odbccp32.lib',
])
env.Append(LINKFLAGS=[
'/DEBUG',
'/DYNAMICBASE',
'/ERRORREPORT:NONE',
#'/INCREMENTAL',
'/MACHINE:X64',
'/MANIFEST',
#'''/MANIFESTUAC:"level='asInvoker' uiAccess='false'"''',
'/nologo',
'/NXCOMPAT',
'/SUBSYSTEM:CONSOLE',
'/TLBID:1',
])
if variant == 'debug':
env.Append(CCFLAGS=[
'/GS', # Buffers security check: enable
'/MTd', # Language: Multi-threaded Debug CRT
'/Od', # Optimization: Disabled
'/RTC1', # Run-time error checks:
])
env.Append(CPPDEFINES=[
'_CRTDBG_MAP_ALLOC'
])
else:
env.Append(CCFLAGS=[
'/MT', # Language: Multi-threaded CRT
'/Ox', # Optimization: Full
])
else:
raise SCons.UserError('Unknown toolchain == "%s"' % toolchain)
#-------------------------------------------------------------------------------
#
# VFALCO NOTE Clean area.
#
#-------------------------------------------------------------------------------
#
# Nothing having to do with directories, source files,
# or include paths should reside outside the boundaries.
#
# List of includes passed to the C++ compiler.
# These are all relative to the repo dir.
#
INCLUDE_PATHS = [
'.',
def addSource(path, env, variant_dirs, CPPPATH=[]):
if CPPPATH:
env = env.Clone()
env.Prepend(CPPPATH=CPPPATH)
return env.Object(Beast.variantFile(path, variant_dirs))
#-------------------------------------------------------------------------------
# Configure the base construction environment
root_dir = Dir('#').srcnode().get_abspath() # Path to this SConstruct file
build_dir = os.path.join('build')
base = Environment(
toolpath=[os.path.join ('src', 'beast', 'site_scons', 'site_tools')],
tools=['default', 'Protoc', 'VSProject'],
ENV=os.environ,
TARGET_ARCH='x86_64')
import_environ(base)
config_base(base)
base.Append(CPPPATH=[
'src',
'src/leveldb',
'src/leveldb/port',
'src/leveldb/include',
'src/beast',
'build/proto'
]
os.path.join('src', 'beast'),
os.path.join(build_dir, 'proto'),
])
# if BOOST_HOME:
# INCLUDE_PATHS.append(BOOST_HOME)
#-------------------------------------------------------------------------------
#
# Compiled sources
#
COMPILED_FILES = []
# -------------------
# Beast unity sources
#
if OSX:
# OSX: Use the Objective C++ version of beast_core
COMPILED_FILES.extend (['src/ripple/beast/ripple_beastobjc.mm'])
# Configure the toolchains, variants, default toolchain, and default target
variants = ['debug', 'release']
all_toolchains = ['clang', 'gcc', 'msvc']
if Beast.system.osx:
toolchains = ['clang']
default_toolchain = 'clang'
else:
COMPILED_FILES.extend (['src/ripple/beast/ripple_beast.cpp'])
COMPILED_FILES.extend (['src/ripple/beast/ripple_beastc.c'])
toolchains = detect_toolchains(base)
if not toolchains:
raise ValueError('No toolchains detected!')
if 'msvc' in toolchains:
default_toolchain = 'msvc'
elif 'gcc' in toolchains:
if 'clang' in toolchains:
cxx = os.environ.get('CXX', 'g++')
default_toolchain = 'clang' if 'clang' in cxx else 'gcc'
else:
default_toolchain = 'gcc'
elif 'clang' in toolchains:
default_toolchain = 'clang'
else:
raise ValueError("Don't understand toolchains in " + str(toolchains))
default_variant = 'debug'
default_target = None
# ------------------------------
# New-style Ripple unity sources
#
COMPILED_FILES.extend([
'src/ripple/http/ripple_http.cpp',
'src/ripple/json/ripple_json.cpp',
'src/ripple/peerfinder/ripple_peerfinder.cpp',
'src/ripple/resource/ripple_resource.cpp',
'src/ripple/rocksdb/ripple_rocksdb.cpp',
'src/ripple/rpc/ripple_rpc.cpp',
'src/ripple/sitefiles/ripple_sitefiles.cpp',
'src/ripple/sophia/ripple_sophia.c',
'src/ripple/sslutil/ripple_sslutil.cpp',
'src/ripple/testoverlay/ripple_testoverlay.cpp',
'src/ripple/types/ripple_types.cpp',
'src/ripple/validators/ripple_validators.cpp'
])
for source in [
'src/ripple/proto/ripple.proto',
]:
base.Protoc([],
source,
PROTOCPROTOPATH=[os.path.dirname(source)],
PROTOCOUTDIR=os.path.join(build_dir, 'proto'),
PROTOCPYTHONOUTDIR=None)
# ------------------------------
# Old-style Ripple unity sources
#
COMPILED_FILES.extend([
'src/ripple_app/ripple_app.cpp',
'src/ripple_app/ripple_app_pt1.cpp',
'src/ripple_app/ripple_app_pt2.cpp',
'src/ripple_app/ripple_app_pt3.cpp',
'src/ripple_app/ripple_app_pt4.cpp',
'src/ripple_app/ripple_app_pt5.cpp',
'src/ripple_app/ripple_app_pt6.cpp',
'src/ripple_app/ripple_app_pt7.cpp',
'src/ripple_app/ripple_app_pt8.cpp',
'src/ripple_basics/ripple_basics.cpp',
'src/ripple_core/ripple_core.cpp',
'src/ripple_data/ripple_data.cpp',
'src/ripple_hyperleveldb/ripple_hyperleveldb.cpp',
'src/ripple_leveldb/ripple_leveldb.cpp',
'src/ripple_mdb/ripple_mdb.c',
'src/ripple_net/ripple_net.cpp',
'src/ripple_websocket/ripple_websocket.cpp'
])
# Declare the targets
aliases = collections.defaultdict(list)
msvc_configs = []
for toolchain in all_toolchains:
for variant in variants:
# Configure this variant's construction environment
env = base.Clone()
config_env(toolchain, variant, env)
variant_name = '%s.%s' % (toolchain, variant)
variant_dir = os.path.join(build_dir, variant_name)
variant_dirs = {
os.path.join(variant_dir, 'src') :
'src',
os.path.join(variant_dir, 'proto') :
os.path.join (build_dir, 'proto'),
}
for dest, source in variant_dirs.iteritems():
env.VariantDir(dest, source, duplicate=0)
objects = []
objects.append(addSource('src/ripple/unity/app.cpp', env, variant_dirs))
objects.append(addSource('src/ripple/unity/app1.cpp', env, variant_dirs))
objects.append(addSource('src/ripple/unity/app2.cpp', env, variant_dirs))
objects.append(addSource('src/ripple/unity/app3.cpp', env, variant_dirs))
objects.append(addSource('src/ripple/unity/app4.cpp', env, variant_dirs))
objects.append(addSource('src/ripple/unity/app5.cpp', env, variant_dirs))
objects.append(addSource('src/ripple/unity/app6.cpp', env, variant_dirs))
objects.append(addSource('src/ripple/unity/app7.cpp', env, variant_dirs))
objects.append(addSource('src/ripple/unity/app8.cpp', env, variant_dirs))
objects.append(addSource('src/ripple/unity/app9.cpp', env, variant_dirs))
objects.append(addSource('src/ripple/unity/basics.cpp', env, variant_dirs))
objects.append(addSource('src/ripple/unity/beast.cpp', env, variant_dirs))
objects.append(addSource('src/ripple/unity/beastc.c', env, variant_dirs))
objects.append(addSource('src/ripple/unity/common.cpp', env, variant_dirs))
objects.append(addSource('src/ripple/unity/core.cpp', env, variant_dirs))
objects.append(addSource('src/ripple/unity/data.cpp', env, variant_dirs))
objects.append(addSource('src/ripple/unity/http.cpp', env, variant_dirs))
objects.append(addSource('src/ripple/unity/json.cpp', env, variant_dirs))
objects.append(addSource('src/ripple/unity/net.cpp', env, variant_dirs))
objects.append(addSource('src/ripple/unity/overlay.cpp', env, variant_dirs))
objects.append(addSource('src/ripple/unity/peerfinder.cpp', env, variant_dirs))
objects.append(addSource('src/ripple/unity/protobuf.cpp', env, variant_dirs))
objects.append(addSource('src/ripple/unity/ripple.proto.cpp', env, variant_dirs))
objects.append(addSource('src/ripple/unity/radmap.cpp', env, variant_dirs))
objects.append(addSource('src/ripple/unity/resource.cpp', env, variant_dirs))
objects.append(addSource('src/ripple/unity/rpcx.cpp', env, variant_dirs))
objects.append(addSource('src/ripple/unity/sitefiles.cpp', env, variant_dirs))
objects.append(addSource('src/ripple/unity/sslutil.cpp', env, variant_dirs))
objects.append(addSource('src/ripple/unity/testoverlay.cpp', env, variant_dirs))
objects.append(addSource('src/ripple/unity/types.cpp', env, variant_dirs))
objects.append(addSource('src/ripple/unity/validators.cpp', env, variant_dirs))
objects.append(addSource('src/ripple/unity/websocket.cpp', env, variant_dirs))
#
#
#-------------------------------------------------------------------------------
objects.append(addSource('src/ripple/unity/nodestore.cpp', env, variant_dirs, [
'src/leveldb/include',
#'src/hyperleveldb/include', # hyper
'src/rocksdb/include',
]))
# Map top level source directories to their location in the outputs
#
objects.append(addSource('src/ripple/unity/leveldb.cpp', env, variant_dirs, [
'src/leveldb/',
'src/leveldb/include',
'src/snappy/snappy',
'src/snappy/config',
]))
VariantDir('build/obj/src', 'src', duplicate=0)
objects.append(addSource('src/ripple/unity/hyperleveldb.cpp', env, variant_dirs, [
'src/hyperleveldb',
'src/snappy/snappy',
'src/snappy/config',
]))
#-------------------------------------------------------------------------------
objects.append(addSource('src/ripple/unity/rocksdb.cpp', env, variant_dirs, [
'src/rocksdb',
'src/rocksdb/include',
'src/snappy/snappy',
'src/snappy/config',
]))
# Add the list of includes to compiler include paths.
#
for path in INCLUDE_PATHS:
env.Append (CPPPATH = [ path ])
objects.append(addSource('src/ripple/unity/snappy.cpp', env, variant_dirs, [
'src/snappy/snappy',
'src/snappy/config',
]))
if BOOST_HOME:
env.Prepend (CPPPATH = [ BOOST_HOME ])
if toolchain == "clang" and Beast.system.osx:
objects.append(addSource('src/ripple/unity/beastobjc.mm', env, variant_dirs))
#-------------------------------------------------------------------------------
target = env.Program(
target = os.path.join(variant_dir, 'rippled'),
source = objects
)
# Apparently, only linux uses -ldl
if Linux: # not FreeBSD:
env.Append(
LIBS = [
'dl', # dynamic linking for linux
]
)
if toolchain == default_toolchain and variant == default_variant:
default_target = target
install_target = env.Install (build_dir, source = default_target)
env.Alias ('install', install_target)
env.Default (install_target)
aliases['all'].extend(install_target)
if toolchain == 'msvc':
config = env.VSProjectConfig(variant, 'x64', target, env)
msvc_configs.append(config)
if toolchain in toolchains:
aliases['all'].extend(target)
aliases[variant].extend(target)
aliases[toolchain].extend(target)
env.Alias(variant_name, target)
env.Append(
LIBS = \
# rt is for clock_nanosleep in beast
['rt'] if not OSX else [] +\
[
'z'
]
)
for key, value in aliases.iteritems():
env.Alias(key, value)
# We prepend, in case there's another BOOST somewhere on the path
# such, as installed into `/usr/lib/`
if BOOST_HOME is not None:
env.Prepend(
LIBPATH = ["%s/stage/lib" % BOOST_HOME])
if not OSX:
env.Append(LINKFLAGS = [
'-rdynamic', '-pthread',
])
DEBUGFLAGS = ['-g', '-DDEBUG', '-D_DEBUG']
env.Append(CCFLAGS = ['-pthread', '-Wall', '-Wno-sign-compare', '-Wno-char-subscripts']+DEBUGFLAGS)
env.Append(CXXFLAGS = ['-O1', '-pthread', '-Wno-invalid-offsetof', '-Wformat']+DEBUGFLAGS)
# RTTI is required for Beast and CountedObject.
#
env.Append(CXXFLAGS = ['-frtti'])
if (int(GCC_VERSION[0]) == 4 and int(GCC_VERSION[1]) == 6):
env.Append(CXXFLAGS = ['-std=c++0x'])
elif (int(GCC_VERSION[0]) > 4 or (int(GCC_VERSION[0]) == 4 and int(GCC_VERSION[1]) >= 7)):
env.Append(CXXFLAGS = ['-std=c++11'])
# FreeBSD doesn't support O_DSYNC
if FreeBSD:
env.Append(CPPFLAGS = ['-DMDB_DSYNC=O_SYNC'])
if OSX:
env.Append(LINKFLAGS = ['-L/usr/local/opt/openssl/lib'])
env.Append(CXXFLAGS = ['-I/usr/local/opt/openssl/include'])
PROTO_SRCS = env.Protoc([], 'src/ripple_data/protocol/ripple.proto', PROTOCOUTDIR='build/proto', PROTOCPYTHONOUTDIR=None)
env.Clean(PROTO_SRCS, 'site_scons/site_tools/protoc.pyc')
# Only tag actual Ripple files.
TAG_SRCS = copy.copy(COMPILED_FILES)
# Derive the object files from the source files.
OBJECT_FILES = []
OBJECT_FILES.append(PROTO_SRCS[0])
for file in COMPILED_FILES:
OBJECT_FILES.append('build/obj/' + file)
#
# Targets
#
rippled = env.Program('build/rippled', OBJECT_FILES)
tags = env.CTags('tags', TAG_SRCS)
Default(rippled, tags)
vcxproj = base.VSProject(
os.path.join('Builds', 'VisualStudio2013', 'RippleD'),
source = [],
VSPROJECT_ROOT_DIRS = ['src/beast', 'src', '.'],
VSPROJECT_CONFIGS = msvc_configs)
base.Alias('vcxproj', vcxproj)

View File

@@ -1,6 +0,0 @@
#!/bin/sh -x
cd ~/NewCoin
git pull
scons -j 2
cp -p newcoind bin/

View File

@@ -1,10 +0,0 @@
#!/bin/sh
# XXX Should not need to make db directory. newcoind should do this.
for SITE in $HOSTS
do
echo "Clearing db for:" $SITE
DB_DIR="/var/www/$SITE/db/"
mkdir -p "/var/www/$SITE/db/"
rm -rf "/var/www/$SITE/db/*"
done

View File

@@ -1,5 +0,0 @@
#!/bin/sh -x
network-stop
sleep 1
network-start

View File

@@ -1,6 +0,0 @@
#!/bin/sh
for SITE in $HOSTS
do
(nx $SITE &)
done

View File

@@ -1,6 +0,0 @@
#!/bin/sh
for SITE in $HOSTS
do
(nx $SITE stop &)
done

View File

@@ -1,5 +0,0 @@
#!/bin/sh -x
echo "Building and restarting."
network-build
network-restart

7
bin/nx
View File

@@ -1,7 +0,0 @@
#!/bin/sh
SITE=$1
shift
COMMAND=$@
cd "/var/www/$SITE"
newcoind $COMMAND

View File

@@ -1,118 +0,0 @@
// Copyright (c) 2013 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.
#include "leveldb/db.h"
#include "db/db_impl.h"
#include "leveldb/cache.h"
#include "util/testharness.h"
#include "util/testutil.h"
namespace leveldb {
class AutoCompactTest {
public:
std::string dbname_;
Cache* tiny_cache_;
Options options_;
DB* db_;
AutoCompactTest() {
dbname_ = test::TmpDir() + "/autocompact_test";
tiny_cache_ = NewLRUCache(100);
options_.block_cache = tiny_cache_;
DestroyDB(dbname_, options_);
options_.create_if_missing = true;
options_.compression = kNoCompression;
ASSERT_OK(DB::Open(options_, dbname_, &db_));
}
~AutoCompactTest() {
delete db_;
DestroyDB(dbname_, Options());
delete tiny_cache_;
}
std::string Key(int i) {
char buf[100];
snprintf(buf, sizeof(buf), "key%06d", i);
return std::string(buf);
}
uint64_t Size(const Slice& start, const Slice& limit) {
Range r(start, limit);
uint64_t size;
db_->GetApproximateSizes(&r, 1, &size);
return size;
}
void DoReads(int n);
};
static const int kValueSize = 200 * 1024;
static const int kTotalSize = 100 * 1024 * 1024;
static const int kCount = kTotalSize / kValueSize;
// Read through the first n keys repeatedly and check that they get
// compacted (verified by checking the size of the key space).
void AutoCompactTest::DoReads(int n) {
std::string value(kValueSize, 'x');
DBImpl* dbi = reinterpret_cast<DBImpl*>(db_);
// Fill database
for (int i = 0; i < kCount; i++) {
ASSERT_OK(db_->Put(WriteOptions(), Key(i), value));
}
ASSERT_OK(dbi->TEST_CompactMemTable());
// Delete everything
for (int i = 0; i < kCount; i++) {
ASSERT_OK(db_->Delete(WriteOptions(), Key(i)));
}
ASSERT_OK(dbi->TEST_CompactMemTable());
// Get initial measurement of the space we will be reading.
const int64_t initial_size = Size(Key(0), Key(n));
const int64_t initial_other_size = Size(Key(n), Key(kCount));
// Read until size drops significantly.
std::string limit_key = Key(n);
for (int read = 0; true; read++) {
ASSERT_LT(read, 100) << "Taking too long to compact";
Iterator* iter = db_->NewIterator(ReadOptions());
for (iter->SeekToFirst();
iter->Valid() && iter->key().ToString() < limit_key;
iter->Next()) {
// Drop data
}
delete iter;
// Wait a little bit to allow any triggered compactions to complete.
Env::Default()->SleepForMicroseconds(1000000);
uint64_t size = Size(Key(0), Key(n));
fprintf(stderr, "iter %3d => %7.3f MB [other %7.3f MB]\n",
read+1, size/1048576.0, Size(Key(n), Key(kCount))/1048576.0);
if (size <= initial_size/10) {
break;
}
}
// Verify that the size of the key space not touched by the reads
// is pretty much unchanged.
const int64_t final_other_size = Size(Key(n), Key(kCount));
ASSERT_LE(final_other_size, initial_other_size + 1048576);
ASSERT_GE(final_other_size, initial_other_size/5 - 1048576);
}
TEST(AutoCompactTest, ReadAll) {
DoReads(kCount);
}
TEST(AutoCompactTest, ReadHalf) {
DoReads(kCount/2);
}
} // namespace leveldb
int main(int argc, char** argv) {
return leveldb::test::RunAllTests();
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,10 @@
[Unit]
Description=Ripple Peer-to-Peer Network Daemon
[Service]
Type=simple
User=nobody
ExecStart=/usr/bin/rippled --conf=/etc/rippled/rippled.cfg
[Install]
WantedBy=multi-user.target

114
doc/rippled.init Normal file
View File

@@ -0,0 +1,114 @@
#!/bin/sh
### BEGIN INIT INFO
# Provides: ripple
# Required-Start: $local_fs $remote_fs $network $syslog
# Required-Stop: $local_fs $remote_fs $network $syslog
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: starts the ripple network node
# Description: starts rippled using start-stop-daemon
### END INIT INFO
set -e
NAME=rippled
USER="rippled"
GROUP="rippled"
PIDFILE=/var/run/$NAME.pid
DAEMON=/usr/local/sbin/rippled
DAEMON_OPTS="--conf /etc/ripple/rippled.cfg"
NET_OPTS="--net $DAEMON_OPTS"
LOGDIR="/var/log/rippled"
DBDIR="/var/db/rippled/db/hyperldb"
export PATH="${PATH:+$PATH:}/usr/sbin:/sbin"
# I wish it didn't come down to this, but this is the easiest way to ensure
# sanity of an install.
if [ ! -d $LOGDIR ]; then
mkdir -p $LOGDIR
chown $USER:$GROUP $LOGDIR
fi
if [ ! -d $DBDIR ]; then
mkdir -p $DBDIR
chown -R $USER:$GROUP $DBDIR
fi
case "$1" in
start)
echo -n "Starting daemon: "$NAME
start-stop-daemon --start --quiet --background -m --pidfile $PIDFILE \
--exec $DAEMON --chuid $USER --group $GROUP --verbose -- $NET_OPTS
echo "."
;;
stop)
echo -n "Stopping daemon: "$NAME
$DAEMON $DAEMON_OPTS stop
rm -f $PIDFILE
echo "."
;;
restart)
echo -n "Restarting daemon: "$NAME
$DAEMON $DAEMON_OPTS stop
rm -f $PIDFILE
start-stop-daemon --start --quiet --background -m --pidfile $PIDFILE \
--exec $DAEMON --chuid $USER --group $GROUP -- $NET_OPTS
echo "."
;;
status)
echo "Status of $NAME:"
echo -n "PID of $NAME: "
if [ -f "$PIDFILE" ]; then
cat $PIDFILE
$DAEMON $DAEMON_OPTS server_info
else
echo "$NAME not running."
fi
echo "."
;;
fetch)
echo "$NAME ledger fetching info:"
$DAEMON $DAEMON_OPTS fetch_info
echo "."
;;
uptime)
echo "$NAME uptime:"
$DAEMON $DAEMON_OPTS get_counts
echo "."
;;
startconfig)
echo "$NAME is being started with the following command line:"
echo "$DAEMON $NET_OPTS"
echo "."
;;
command)
# Truncate the script's argument vector by one position to get rid of
# this entry.
shift
# Pass the remainder of the argument vector to rippled.
$DAEMON $DAEMON_OPTS "$@"
echo "."
;;
test)
$DAEMON $DAEMON_OPTS ping
echo "."
;;
*)
echo "Usage: $0 {start|stop|restart|status|fetch|uptime|startconfig|"
echo " command|test}"
exit 1
esac
exit 0

View File

@@ -1,207 +0,0 @@
--------------------------------------------------------------------------------
RIPPLE TODO
--------------------------------------------------------------------------------
Vinnie's List: Changes day to day, descending priority
- PeerFinder work
- Validators work
- HTTPClient improvements based on HTTPServer
- HTTPMessage improvements
- Ditch old HTTPClient so I can take the name
- Finish RPCAsyncServer, RPCService and RPCService::Manager
- Fix RPCDoor to respect config setting for [rpc_secure]
- Clean up calculation of COnfig file location.
- Remove TESTNET and all related code and settings.
- Remove addRpcSub, findRpcSub, and notify the appropriate partner(s)
David Features:
- override config items from command line
- change config via RPC, this is for debugging
--------------------------------------------------------------------------------
- std::priority_queue for DeadlineTimer
- Change ProxyInfo to use IPAddress, get rid of IPv4Address from the parsing
code
- Validators should delay the application of newly downloaded lists from
sources, to mitigate the effects of attacks. Unless there's no validators
in the list.
- Validators RPC options to immediately apply UNL,
manually revisit sources, etc...
- Look into using CMake
- IPv6 support in IPAddress
- Configuration list for Jenkins
- Fix all crash and leaks on exit
Say there's a leak, a ledger that can never be accessed is locked in some
structure. If the organized teardown code frees that structure, the leak
will not be reported.
Yes, so you'll detect some small subset of leaks that way.
You'll still have to be vigilant for the leaks that won't detect.
The problem is ordering. There are lots of circular dependencies.
The biggest problem is the order of destruction of global objects. (I think)
Getting rid of global objects is a good solution to that.
Vinnie Falco: Those I can resolve with my ReferenceCountedSingleton. And
yeah thats a good approach, one that I am doing slowly anyway
Yeah, that's good for other reasons too, not just the unpredictability of
creation order that can hide bugs.
There may also just be some missing destructors.
Some of it may be things being shut down in the wrong order. Like if you shut
down the cache and then something that uses the cache, objects may get
put in the cache after it was shut down.
- Do something about the throw() reporting weaknesses:
* Make sure all Sconstruct and .pro builds have debug symbols in release
* Replace all throw with beast::Throw()
(Only in ripple sources, not in Subtrees/, protobuf, or websocket)
- Improved Beast exception object, provides __FILE__ and __LINE__
- Add file and line capabilities to beast::Throw()
- Allow beast::Throw to be hooked for logging
- Add stack trace capability to beast::Throw() diagnostics via the hook
(use the existing beast::SystemStats::getStackBacktrace())
- Implement getStackBacktrace for BEAST_BSD targets
- Add UnhandledExceptionCatcher to beast
- Return EXIT_FAILURE on unhandled exception
- Consolidate JSON code maybe use Beast
- Deeply create directories specified in config settings
- Refactor Section code into ConfigFile
- Supress useless gcc warnings
http://stackoverflow.com/questions/3378560/how-to-disable-gcc-warnings-for-a-few-lines-of-code
- Get rid of boost::filesystem
- What the heck is up with site_scons/site_tools/protoc.py?
- Add convenience variadic functions to JobQueue that do the bind for you
- Consolidate databases
- Figure out why we need WAL sqlite mode if we no longer use sqlite for the node store
- Add "skipped" field to beginTestCase() to disable a test but still record
that it was skipped in the output. Like for mdb import.
- Get rid of 'ref' typedefs that really mean const&
- Use secp256k1 from beast
- Fix xsd/dtd line in JUnit XML output
- Get rid of the WriteLog() stuff in the ripple tests and make it report the
message directly to the UnitTest object. Then update the JUnit XML output
routines to also write the auxiliary messages.
* Restyle all the macros in ConfigSection.h
- Move src/protobuf to Subtrees and deal with protobuf_core.cpp
- Replace home-made database wrappers with beast::sqdb
- Use static creation member functions instead of endless constructor
variations in base_uint, uint256, and family.
- Raise the warning level and fix everything
- Replace base_uint and uintXXX with UnsignedInteger
* Need to specialize UnsignedInteger to work efficiently with 4 and 8 byte
multiples of the size.
- Rewrite boost program_options in Beast
- Replace endian conversion calls with beast calls:
htobe32, be32toh, ntohl, etc...
Start by removing the system headers which provide these routines, if possible
- Rename RPCHandler to CallHandler
- Rename "fullBelow" to something like haveAllDescendants or haveAllChildren.
- Rewrite Sustain to use Beast and work on Windows as well
* Do not enable watchdog process if a debugger is attached
- Make sure the leak detector output appears on Linux and FreeBSD debug builds.
- Rename LoadMonitor to LoadMeter, change LoadEvent to LoadMeter::ScopedSample
- Rename LedgerMaster to Ledgers, create ILedgers interface.
- Replace all NULL with nullptr
- Make TxFormats a member of ICore instead of a singleton.
PROBLEM: STObject derived classes like STInt16 make direct use of the
singleton. It might have to remain a singleton. At the very least,
it should be a SharedSingleton to resolve ordering issues.
- Replace C11X with BEAST_COMPILER_SUPPORTS_MOVE_SEMANTICS
- Remove "ENABLE_INSECURE" when the time is right.
- lift unique_ptr / auto_ptr into ripple namespace,
or replace with ScopedPointer (preferred)
- Go searching through VFALCO notes and fix everything
- Deal with function-level statics used for SqliteDatabase (like in
HSBESQLite::visitAll)
- Document in order:
SerializedType
STObject
SerializedLedgerEntry
- Consolidate SQLite database classes: DatabaseCon, Database, SqliteDatabase.
--------------------------------------------------------------------------------
WEBSOCKET TODO
--------------------------------------------------------------------------------
- Rewrite for sanity
--------------------------------------------------------------------------------
PROTOCOL BUFFERS TODO
--------------------------------------------------------------------------------
- Create/maintain the protobuf Git repo (original uses SVN)
- Update the subtree
- Make a Visual Studio 2012 Project for source browsing
--------------------------------------------------------------------------------
Davidisms
--------------------------------------------------------------------------------
(Figure out a good place to record information like this permanently)
Regarding a defect where a failing transaction was being submitted over and over
again on the network (July 3, 2013)
The core problem was an interaction between two bits of logic.
1) Normally, we won't relay a transaction again if we already recently relayed
it. But this is bypassed if the transaction failed in a way that could
allow it to succeed later. This way, if one server discovers a transaction
can now work, it can get all servers to retry it.
2) Normally, we won't relay a transaction if we think it can't claim a fee.
But if we're not sure it can't claim a fee because we're in an unhealthy
state, we propagate the transaction to let other servers decide if they
think it can claim a fee.
With these two bits of logic, two unhealthy servers could infinitely propagate
a transaction back and forth between each other.
A node is "full below" if we believe we have (either in the database or
scheduled to be stored in the database) the contents of every node below that
node in a hash tree. When trying to acquire a hash tree/map, if a node is
full below, we know not to bother with anything below that node.
The fullBelowCache is a cache of hashes of nodes that are full below. Which means
there are no missing children

View File

@@ -20,6 +20,8 @@
#
[validators]
n9KPnVLn7ewVzHvn218DcEYsnWLzKerTDwhpofhk4Ym1RUq4TeGw first
n9LFzWuhKNvXStHAuemfRKFVECLApowncMAM5chSCL9R5ECHGN4V second
n94rSdgTyBNGvYg8pZXGuNt59Y5bGAZGxbxyvjDaqD9ceRAgD85P third
n949f75evCHwgyP4fPVgaHqNHxUVN15PsJEZ3B3HnXPcPjcZAoy7 RL1
n9MD5h24qrQqiyBC8aeqqCWvpiBiYQ3jxSr91uiDvmrkyHRdYLUj RL2
n9L81uNCaPgtUJfaHh89gmdvXKAmSt5Gdsw2g1iPWaPkAHW5Nm4C RL3
n9KiYM9CgngLvtRCQHZwgC2gjpdaZcCcbt3VboxiNFcKuwFVujzS RL4
n9LdgEtkmGB9E2h3K4Vp7iGUaKuq23Zr32ehxiU8FWY7xoxbWTSA RL5

View File

@@ -1,59 +0,0 @@
// Copyright (c) 2013 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.
// Test for issue 200: when iterator switches direction from backward
// to forward, the current key can be yielded unexpectedly if a new
// mutation has been added just before the current key.
#include "leveldb/db.h"
#include "util/testharness.h"
namespace leveldb {
class Issue200 { };
TEST(Issue200, Test) {
// Get rid of any state from an old run.
std::string dbpath = test::TmpDir() + "/leveldb_issue200_test";
DestroyDB(dbpath, Options());
DB *db;
Options options;
options.create_if_missing = true;
ASSERT_OK(DB::Open(options, dbpath, &db));
WriteOptions write_options;
ASSERT_OK(db->Put(write_options, "1", "b"));
ASSERT_OK(db->Put(write_options, "2", "c"));
ASSERT_OK(db->Put(write_options, "3", "d"));
ASSERT_OK(db->Put(write_options, "4", "e"));
ASSERT_OK(db->Put(write_options, "5", "f"));
ReadOptions read_options;
Iterator *iter = db->NewIterator(read_options);
// Add an element that should not be reflected in the iterator.
ASSERT_OK(db->Put(write_options, "25", "cd"));
iter->Seek("5");
ASSERT_EQ(iter->key().ToString(), "5");
iter->Prev();
ASSERT_EQ(iter->key().ToString(), "4");
iter->Prev();
ASSERT_EQ(iter->key().ToString(), "3");
iter->Next();
ASSERT_EQ(iter->key().ToString(), "4");
iter->Next();
ASSERT_EQ(iter->key().ToString(), "5");
delete iter;
delete db;
DestroyDB(dbpath, options);
}
} // namespace leveldb
int main(int argc, char** argv) {
return leveldb::test::RunAllTests();
}

View File

@@ -10,7 +10,7 @@
},
"dependencies": {
"ripple-lib": "0.7.25",
"ripple-lib": "0.7.37",
"async": "~0.2.9",
"extend": "~1.2.0",
"simple-jsonrpc": "~0.0.2",
@@ -22,7 +22,7 @@
},
"scripts": {
"test": "mocha test/*-test.{js,coffee}"
"test": "mocha test/websocket-test.js test/server-test.js test/*-test.{js,coffee}"
},
"repository": {

View File

@@ -1,88 +0,0 @@
#!python
"""
protoc.py: Protoc Builder for SCons
This Builder invokes protoc to generate C++ and Python
from a .proto file.
NOTE: Java is not currently supported.
From: http://www.scons.org/wiki/ProtocBuilder
"""
__author__ = "Scott Stafford"
import SCons.Action
import SCons.Builder
import SCons.Defaults
import SCons.Node.FS
import SCons.Util
from SCons.Script import File, Dir
import os.path
protocs = 'protoc'
ProtocAction = SCons.Action.Action('$PROTOCCOM', '$PROTOCCOMSTR')
def ProtocEmitter(target, source, env):
dirOfCallingSConscript = Dir('.').srcnode()
env.Prepend(PROTOCPROTOPATH = dirOfCallingSConscript.path)
source_with_corrected_path = []
for src in source:
commonprefix = os.path.commonprefix([dirOfCallingSConscript.path, src.srcnode().path])
if len(commonprefix)>0:
source_with_corrected_path.append( src.srcnode().path[len(commonprefix + os.sep):] )
else:
source_with_corrected_path.append( src.srcnode().path )
source = source_with_corrected_path
for src in source:
modulename = os.path.splitext(os.path.basename(src))[0]
if env['PROTOCOUTDIR']:
base = os.path.join(env['PROTOCOUTDIR'] , modulename)
target.extend( [ base + '.pb.cc', base + '.pb.h' ] )
if env['PROTOCPYTHONOUTDIR']:
base = os.path.join(env['PROTOCPYTHONOUTDIR'] , modulename)
target.append( base + '_pb2.py' )
try:
target.append(env['PROTOCFDSOUT'])
except KeyError:
pass
# XXX KLUDGE: Force things to be right.
env['PROTOCOUTDIR'] = 'build/proto'
env['PROTOCPROTOPATH'] = ['src/ripple_data/protocol']
#~ print "PROTOC SOURCE:", [str(s) for s in source]
#~ print "PROTOC TARGET:", [str(s) for s in target]
return target, source
ProtocBuilder = SCons.Builder.Builder(action = ProtocAction,
emitter = ProtocEmitter,
srcsuffix = '$PROTOCSRCSUFFIX')
def generate(env):
"""Add Builders and construction variables for protoc to an Environment."""
try:
bld = env['BUILDERS']['Protoc']
except KeyError:
bld = ProtocBuilder
env['BUILDERS']['Protoc'] = bld
env['PROTOC'] = env.Detect(protocs) or 'protoc'
env['PROTOCFLAGS'] = SCons.Util.CLVar('')
env['PROTOCPROTOPATH'] = SCons.Util.CLVar('')
env['PROTOCCOM'] = '$PROTOC ${["-I%s"%x for x in PROTOCPROTOPATH]} $PROTOCFLAGS --cpp_out=$PROTOCCPPOUTFLAGS$PROTOCOUTDIR ${PROTOCPYTHONOUTDIR and ("--python_out="+PROTOCPYTHONOUTDIR) or ""} ${PROTOCFDSOUT and ("-o"+PROTOCFDSOUT) or ""} ${SOURCES}'
env['PROTOCOUTDIR'] = '${SOURCE.dir}'
env['PROTOCPYTHONOUTDIR'] = "python"
env['PROTOCSRCSUFFIX'] = '.proto'
def exists(env):
return env.Detect(protocs)

2
src/.gitignore vendored
View File

@@ -1,2 +0,0 @@
# boost subtree
/boost

View File

@@ -27,6 +27,21 @@
@file BeastConfig.h
*/
//------------------------------------------------------------------------------
//
// Unit Tests
//
//------------------------------------------------------------------------------
/** Config: BEAST_NO_UNIT_TEST_INLINE
Prevents unit test definitions from being inserted into a global table.
The default is to include inline unit test definitions.
*/
#ifndef BEAST_NO_UNIT_TEST_INLINE
//#define BEAST_NO_UNIT_TEST_INLINE 1
#endif
//------------------------------------------------------------------------------
//
// Diagnostics
@@ -151,14 +166,18 @@
#define RIPPLE_DUMP_LEAKS_ON_EXIT 1
#endif
/** Config: RIPPLE_TRACK_MUTEXES
Turns on a feature that enables tracking and diagnostics for mutex
and recursive mutex objects. This affects the type of lock used
by RippleMutex and RippleRecursiveMutex
@note This can slow down performance considerably.
//------------------------------------------------------------------------------
// These control whether or not certain functionality gets
// compiled into the resulting rippled executable
/** Config: RIPPLE_ROCKSDB_AVAILABLE
Controls whether or not the RocksDB database back-end is compiled into
rippled. RocksDB requires a relatively modern C++ compiler (tested with
gcc versions 4.8.1 and later) that supports some C++11 features.
*/
#ifndef RIPPLE_TRACK_MUTEXES
#define RIPPLE_TRACK_MUTEXES 0
#ifndef RIPPLE_ROCKSDB_AVAILABLE
//#define RIPPLE_ROCKSDB_AVAILABLE 0
#endif
//------------------------------------------------------------------------------
@@ -170,19 +189,48 @@
#define RIPPLE_USE_VALIDATORS 0
#endif
// Turning this on will use the new PeerFinder logic to establish connections
// to other peers. Even with this off, PeerFinder will still send mtENDPOINTS
// messages as needed, and collect legacy IP endpoint information.
//
#ifndef RIPPLE_USE_PEERFINDER
#define RIPPLE_USE_PEERFINDER 0
/** Config: BEAST_USE_BOOST_FEATURES
This activates boost specific features and improvements. If this is
turned on, the include paths for your build environment must be set
correctly to find the boost headers.
*/
#ifndef BEAST_USE_BOOST_FEATURES
//#define BEAST_USE_BOOST_FEATURES 1
#endif
// Here temporarily
// Controls whether or not the new RPC::Manager logic will be
// used to invoke RPC commands before they pass to the original code.
#ifndef RIPPLE_USE_RPC_SERVICE_MANAGER
#define RIPPLE_USE_RPC_SERVICE_MANAGER 0
/** Config: RIPPLE_PROPOSE_FEATURES
This determines whether to add any features to the proposed transaction set.
*/
#ifndef RIPPLE_PROPOSE_AMENDMENTS
#define RIPPLE_PROPOSE_AMENDMENTS 0
#endif
/** Config: RIPPLE_ENABLE_AUTOBRIDGING
This determines whether ripple implements offer autobridging via XRP.
*/
#ifndef RIPPLE_ENABLE_AUTOBRIDGING
#define RIPPLE_ENABLE_AUTOBRIDGING 0
#endif
/** Config: RIPPLE_SINGLE_IO_SERVICE_THREAD
When set, restricts the number of threads calling io_service::run to one.
This is useful when debugging.
*/
#ifndef RIPPLE_SINGLE_IO_SERVICE_THREAD
#define RIPPLE_SINGLE_IO_SERVICE_THREAD 0
#endif
/** Config: RIPPLE_STRUCTURED_OVERLAY
Enables Structured Overlay support (unfinished)
*/
#ifndef RIPPLE_STRUCTURED_OVERLAY
#define RIPPLE_STRUCTURED_OVERLAY 0
#endif
/** Config: RIPPLE_ASYNC_RPC_HANDLER
*/
#ifndef RIPPLE_ASYNC_RPC_HANDLER
#define RIPPLE_ASYNC_RPC_HANDLER 1
#endif
#endif

View File

@@ -27,3 +27,4 @@ Builds/VisualStudio2012/Debug
Builds/VisualStudio2012/Release
project.xcworkspace
modules/beast_cryptopp
bin/

26
src/beast/.travis.yml Normal file
View File

@@ -0,0 +1,26 @@
language: cpp
compiler:
- gcc
- clang
before_install:
- sudo add-apt-repository -y ppa:ubuntu-toolchain-r/test
- sudo add-apt-repository -y ppa:boost-latest/ppa
- sudo apt-get update -qq
- sudo apt-get install -qq python-software-properties
- sudo apt-get install -qq g++-4.8
- sudo apt-get install -qq libboost1.55-all-dev
- sudo apt-get install -qq libssl-dev
- sudo apt-get install -qq gcc-4.8
- sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-4.8 40 --slave /usr/bin/g++ g++ /usr/bin/g++-4.8
- sudo update-alternatives --set gcc /usr/bin/gcc-4.8
# - sudo apt-get -y install binutils-gold
- g++ -v
- clang -v
script:
# Abort build on failure
- set -e
- scons
notifications:
email:
false

View File

@@ -27,6 +27,19 @@
@file BeastConfig.h
*/
//------------------------------------------------------------------------------
//
// Unit Tests
//
//------------------------------------------------------------------------------
/** Config: BEAST_NO_UNIT_TEST_INLINE
Prevents unit test definitions from being inserted into a global table.
*/
#ifndef BEAST_NO_UNIT_TEST_INLINE
#define BEAST_NO_UNIT_TEST_INLINE 0
#endif
//------------------------------------------------------------------------------
//
// Diagnostics
@@ -146,6 +159,4 @@
//#define BEAST_USE_BOOST_FEATURES 1
#endif
//------------------------------------------------------------------------------
#endif

View File

@@ -1,22 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ImportGroup Label="PropertySheets" />
<PropertyGroup Label="UserMacros">
<RepoDir>..\..</RepoDir>
</PropertyGroup>
<PropertyGroup />
<ItemDefinitionGroup>
<ClCompile>
<WarningLevel>Level4</WarningLevel>
<PreprocessorDefinitions>BEAST_COMPILING_STATIC_LIBARARY=1;_CRTDBG_MAP_ALLOC;_WIN32_WINNT=0x0600;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<MultiProcessorCompilation>true</MultiProcessorCompilation>
<MinimalRebuild>false</MinimalRebuild>
<AdditionalIncludeDirectories>$(RepoDir)\config;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ClCompile>
</ItemDefinitionGroup>
<ItemGroup>
<BuildMacro Include="RepoDir">
<Value>$(RepoDir)</Value>
</BuildMacro>
</ItemGroup>
</Project>

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -1,228 +0,0 @@
Write code in a clear, self-documenting style but use comments where necessary.
Use Test Driven Development. It encourages designing interfaces first, before implementation.
Don't Repeat Yourself, <20>D.R.Y.<2E>. Put redundant code in a class so it can be re-used and unit tested.
Expose as little of a class as possible. Prefer private over protected. Prefer protected over public. The smaller the interface footprint, the easier it is to write unit tests and comprehend the operation of the class. This is the Interface Segregation Principle.
Use language constants (enum or static const) with descriptive names instead of hard-coded <20>magic numbers.<2E>
Make classes depend on as few external classes or routines as possible. Ideally, no dependencies.
Don't limit flexibility of parameters by forcing the caller to use specific types where general types would work.
--------------------------------------------------------------------------------
# Coding Standards
Coding standards used here are extreme strict and consistent. The style
evolved gradually over the years, incorporating generally acknowledged
best-practice C++ advice, experience, and personal preference.
## Don't Repeat Yourself!
The [Don't Repeat Yourself][1] principle summarises the essence of what it
means to write good code, in all languages, at all levels.
## Formatting
The goal of source code formatting should always be to make things as easy to
read as possible. White space is used to guide the eye so that details are not
overlooked. Blank lines are used to separate code into "paragraphs."
* No tab characters please.
* Tab stops are set to 4 spaces.
* Braces are indented in the [Allman style][2].
* Always place a space before and after all binary operators,
especially assignments (`operator=`).
* The `!` operator should always be followed by a space.
* The `~` operator should be preceded by a space, but not followed by one.
* The `++` and `--` operators should have no spaces between the operator and
the operand.
* A space never appears before a comma, and always appears after a comma.
* Always place a space before an opening parenthesis. One exception is if
the parentheses are empty.
* Don't put spaces after a parenthesis. A typical member function call might
look like this: `foobar (1, 2, 3);`
* In general, leave a blank line before an `if` statement.
* In general, leave a blank line after a closing brace `}`.
* Do not place code or comments on the same line as any opening or
closing brace.
* Do not write `if` statements all-on-one-line. The exception to this is when
you've got a sequence of similar `if` statements, and are aligning them all
vertically to highlight their similarities.
* In an `if-else` statement, if you surround one half of the statement with
braces, you also need to put braces around the other half, to match.
* When writing a pointer type, use this spacing: `SomeObject* myObject`.
Technically, a more correct spacing would be `SomeObject *myObject`, but
it makes more sense for the asterisk to be grouped with the type name,
since being a pointer is part of the type, not the variable name. The only
time that this can lead to any problems is when you're declaring multiple
pointers of the same type in the same statement - which leads on to the next
rule:
* When declaring multiple pointers, never do so in a single statement, e.g.
`SomeObject* p1, *p2;` - instead, always split them out onto separate lines
and write the type name again, to make it quite clear what's going on, and
avoid the danger of missing out any vital asterisks.
* The previous point also applies to references, so always put the `&` next to
the type rather than the variable, e.g. `void foo (Thing const& thing)`. And
don't put a space on both sides of the `*` or `&` - always put a space after
it, but never before it.
* The word `const` should be placed to the right of the thing that it modifies,
for consistency. For example `int const` refers to an int which is const.
`int const*` is a pointer to an int which is const. `int *const` is a const
pointer to an int.
* Always place a space in between the template angle brackets and the type
name. Template code is already hard enough to read!
## Naming conventions
* Member variables and method names are written with camel-case, and never
begin with a capital letter.
* Class names are also written in camel-case, but always begin with a capital
letter.
* For global variables... well, you shouldn't have any, so it doesn't matter.
* Class data members begin with `m_`, static data members begin with `s_`.
Global variables begin with `g_`. This is so the scope of the corresponding
declaration can be easily determined.
* Avoid underscores in your names, especially leading or trailing underscores.
In particular, leading underscores should be avoided, as these are often used
in standard library code, so to use them in your own code looks quite jarring.
* If you really have to write a macro for some reason, then make it all caps,
with underscores to separate the words. And obviously make sure that its name
is unlikely to clash with symbols used in other libraries or 3rd party code.
## Types, const-correctness
* If a method can (and should!) be const, make it const!
* If a method definitely doesn't throw an exception (be careful!), mark it as
`noexcept`
* When returning a temporary object, e.g. a String, the returned object should
be non-const, so that if the class has a C++11 move operator, it can be used.
* If a local variable can be const, then make it const!
* Remember that pointers can be const as well as primitives; For example, if
you have a `char*` whose contents are going to be altered, you may still be
able to make the pointer itself const, e.g. `char* const foobar = getFoobar();`.
* Do not declare all your local variables at the top of a function or method
(i.e. in the old-fashioned C-style). Declare them at the last possible moment,
and give them as small a scope as possible.
* Object parameters should be passed as `const&` wherever possible. Only
pass a parameter as a copy-by-value object if you really need to mutate
a local copy inside the method, and if making a local copy inside the method
would be difficult.
* Use portable `for()` loop variable scoping (i.e. do not have multiple for
loops in the same scope that each re-declare the same variable name, as
this fails on older compilers)
* When you're testing a pointer to see if it's null, never write
`if (myPointer)`. Always avoid that implicit cast-to-bool by writing it more
fully: `if (myPointer != nullptr)`. And likewise, never ever write
`if (! myPointer)`, instead always write `if (myPointer == nullptr)`.
It is more readable that way.
* Avoid C-style casts except when converting between primitive numeric types.
Some people would say "avoid C-style casts altogether", but `static_cast` is
a bit unreadable when you just want to cast an `int` to a `float`. But
whenever a pointer is involved, or a non-primitive object, always use
`static_cast`. And when you're reinterpreting data, always use
`reinterpret_cast`.
* Until C++ gets a universal 64-bit primitive type (part of the C++11
standard), it's best to stick to the `int64` and `uint64` typedefs.
## Object lifetime and ownership
* Absolutely do NOT use `delete`, `deleteAndZero`, etc. There are very very few
situations where you can't use a `ScopedPointer` or some other automatic
lifetime management class.
* Do not use `new` unless there's no alternative. Whenever you type `new`, always
treat it as a failure to find a better solution. If a local variable can be
allocated on the stack rather than the heap, then always do so.
* Do not ever use `new` or `malloc` to allocate a C++ array. Always use a
`HeapBlock` instead.
* And just to make it doubly clear: Never use `malloc` or `calloc`.
* If a parent object needs to create and own some kind of child object, always
use composition as your first choice. If that's not possible (e.g. if the
child needs a pointer to the parent for its constructor), then use a
`ScopedPointer`.
* If possible, pass an object as a reference rather than a pointer. If possible,
make it a `const` reference.
* Obviously avoid static and global values. Sometimes there's no alternative,
but if there is an alternative, then use it, no matter how much effort it
involves.
* If allocating a local POD structure (e.g. an operating-system structure in
native code), and you need to initialise it with zeros, use the `= { 0 };`
syntax as your first choice for doing this. If for some reason that's not
appropriate, use the `zerostruct()` function, or in case that isn't suitable,
use `zeromem()`. Don't use `memset()`.
## Classes
* Declare a class's public section first, and put its constructors and
destructor first. Any protected items come next, and then private ones.
* Use the most restrictive access-specifier possible for each member. Prefer
`private` over `protected`, and `protected` over `public`. Don't expose
things unnecessarily.
* Preferred positioning for any inherited classes is to put them to the right
of the class name, vertically aligned, e.g.:
class Thing : public Foo,
private Bar
{
}
* Put a class's member variables (which should almost always be private, of course),
after all the public and protected method declarations.
* Any private methods can go towards the end of the class, after the member
variables.
* If your class does not have copy-by-value semantics, derive the class from
`Uncopyable`.
* If your class is likely to be leaked, then derive your class from
`LeakChecked<>`.
* Constructors that take a single parameter should be default be marked
`explicit`. Obviously there are cases where you do want implicit conversion,
but always think about it carefully before writing a non-explicit constructor.
* Do not use `NULL`, `null`, or 0 for a null-pointer. And especially never use
'0L', which is particulary burdensome. Use `nullptr` instead - this is the
C++2011 standard, so get used to it. There's a fallback definition for `nullptr`
in Beast, so it's always possible to use it even if your compiler isn't yet
C++2011 compliant.
* All the C++ 'guru' books and articles are full of excellent and detailed advice
on when it's best to use inheritance vs composition. If you're not already
familiar with the received wisdom in these matters, then do some reading!
## Miscellaneous
* Constrain the scope of identifiers to the smallest area that needs it. Consider
using nested classes or classes inside functions, if doing so will expose less
interface and implementation overall.
* `goto` statements should not be used at all, even if the alternative is
more verbose code. The only exception is when implementing an algorithm in
a function as a state machine.
* Don't use macros! OK, obviously there are many situations where they're the
right tool for the job, but treat them as a last resort. Certainly don't ever
use a macro just to hold a constant value or to perform any kind of function
that could have been done as a real inline function. And it goes without saying
that you should give them names which aren't going to clash with other code.
And `#undef` them after you've used them, if possible.
* When using the `++` or `--` operators, never use post-increment if
pre-increment could be used instead. Although it doesn't matter for
primitive types, it's good practice to pre-increment since this can be
much more efficient for more complex objects. In particular, if you're
writing a for loop, always use pre-increment,
e.g. `for (int = 0; i < 10; ++i)`
* Never put an "else" statement after a "return"! This is well-explained in the
LLVM coding standards...and a couple of other very good pieces of advice from
the LLVM standards are in there as well.
* When getting a possibly-null pointer and using it only if it's non-null, limit
the scope of the pointer as much as possible - e.g. Do NOT do this:
Foo* f = getFoo ();
if (f != nullptr)
f->doSomething ();
// other code
f->doSomething (); // oops! f may be null!
..instead, prefer to write it like this, which reduces the scope of the
pointer, making it impossible to write code that accidentally uses a null
pointer:
if (Foo* f = getFoo ())
f->doSomethingElse ();
// f is out-of-scope here, so impossible to use it if it's null
(This also results in smaller, cleaner code)
[1]: http://en.wikipedia.org/wiki/Don%27t_repeat_yourself
[2]: http://en.wikipedia.org/wiki/Indent_style#Allman_style

View File

@@ -102,7 +102,7 @@ INPUT_ENCODING = UTF-8
FILE_PATTERNS =
RECURSIVE = YES
EXCLUDE = modules/beast_core/beast_core.h \
modules/beast_core/beast_core.cpp \
modules/beast_core/beast_core.unity.cpp \
modules/beast_basics/beast_basics.cpp \
modules/beast_basics/native \
modules/beast_basics/zip/zlib

139
src/beast/SConstruct Normal file
View File

@@ -0,0 +1,139 @@
from __future__ import absolute_import, division, print_function, unicode_literals
import copy
import itertools
import ntpath
import os
import random
import sys
def add_beast_to_path():
python_home = os.path.join(os.getcwd(), 'python')
if python_home not in sys.path:
sys.path.append(python_home)
add_beast_to_path()
from beast.env.AddCommonFlags import add_common_flags
from beast.env.AddUserEnv import add_user_env
from beast.env import Print
from beast.platform import GetEnvironment
from beast.util import Boost
from beast.util import File
from beast.util import Tests
VARIANT_DIRECTORIES = {
'beast': ('bin', 'beast'),
'modules': ('bin', 'modules'),
}
BOOST_LIBRARIES = '' #boost_system'
MAIN_PROGRAM_FILE = 'beast/unit_test/tests/main.cpp'
DOTFILE = '~/.scons'
def main():
File.validate_libraries(Boost.LIBPATH, BOOST_LIBRARIES)
defaults = GetEnvironment.get_environment(ARGUMENTS)
working = copy.deepcopy(defaults)
add_common_flags(defaults)
add_user_env(working, DOTFILE)
add_common_flags(working)
Print.print_build_config(working, defaults)
env = Environment(**working)
for name, path in VARIANT_DIRECTORIES.items():
env.VariantDir(os.path.join(*path), name, duplicate=0)
env.Replace(PRINT_CMD_LINE_FUNC=Print.print_cmd_line)
#Tests.run_tests(env, MAIN_PROGRAM_FILE, '.', '.test.cpp')
#main()
#-------------------------------------------------------------------------------
def is_unity(path):
b, e = os.path.splitext(path)
return os.path.splitext(b)[1] == '.unity' and e in ['.c', '.cpp']
def files(base):
for parent, _, files in os.walk(base):
for path in files:
path = os.path.join(parent, path)
yield os.path.normpath(path)
#-------------------------------------------------------------------------------
'''
/MP /GS /W3 /wd"4018" /wd"4244" /wd"4267" /Gy- /Zc:wchar_t
/I"D:\lib\OpenSSL-Win64\include" /I"D:\lib\boost_1_55_0"
/I"..\..\src\protobuf\src" /I"..\..\src\protobuf\vsprojects"
/I"..\..\src\leveldb" /I"..\..\src\leveldb\include" /I"..\..\build\proto"
/Zi /Gm- /Od /Fd"..\..\build\obj\VisualStudio2013\Debug.x64\vc120.pdb"
/fp:precise /D "_CRTDBG_MAP_ALLOC" /D "WIN32" /D "_DEBUG" /D "_CONSOLE"
/D "_VARIADIC_MAX=10" /D "_WIN32_WINNT=0x0600" /D "_SCL_SECURE_NO_WARNINGS"
/D "_CRT_SECURE_NO_WARNINGS" /D "_MBCS" /errorReport:prompt /WX- /Zc:forScope
/RTC1 /GR /Gd /MTd /openmp- /Fa"..\..\build\obj\VisualStudio2013\Debug.x64\"
/EHa /nologo /Fo"..\..\build\obj\VisualStudio2013\Debug.x64\"
/Fp"..\..\build\obj\VisualStudio2013\Debug.x64\rippled.pch"
'''
# Path to this SConstruct file
base_dir = Dir('#').srcnode().get_abspath()
base_env = Environment(
tools = ['default', 'VSProject'],
CCCOMSTR = '',
CMDLINE_QUIET = 1,
CPPPATH = [
os.environ['BOOST_ROOT'],
os.environ['OPENSSL_ROOT']
],
CPPDEFINES = [
'_WIN32_WINNT=0x6000']
)
#base_env.Replace(PRINT_CMD_LINE_FUNC=Print.print_cmd_line)
env = base_env
bin_dir = os.path.join(base_dir, 'bin')
srcs = filter(is_unity, list(files('beast')) + list(files('modules')))
for variant in ['Debug']: #, 'Release']:
for platform in ['Win32']:
#env = base_env.Clone()
#env.Replace(PRINT_CMD_LINE_FUNC=Print.print_cmd_line)
variant_dir = os.path.join(bin_dir, variant + '.' + platform)
env.VariantDir(os.path.join(variant_dir, 'beast'), 'beast', duplicate=0)
env.VariantDir(os.path.join(variant_dir, 'modules'), 'modules', duplicate=0)
env.Append(CCFLAGS=[
'/EHsc',
'/bigobj',
'/Fd${TARGET}.pdb'
])
if variant == 'Debug':
env.Append(CCFLAGS=[
'/MTd',
'/Od',
'/Zi'
])
else:
env.Append(CCFLAGS=[
'/MT',
'/Ox'
])
variant_srcs = [os.path.join(variant_dir, os.path.relpath(f, base_dir)) for f in srcs]
beast = env.StaticLibrary(
target = os.path.join(variant_dir, 'beast.lib'),
source = variant_srcs)
env.VSProject (
'out',
buildtarget = beast,
source = filter(is_unity, list(files('beast')) + list(files('modules'))))
env.Default ('out.vcxproj')
#env.Default (os.path.join(bin_dir,'Debug.Win32', 'beast.lib'))

View File

@@ -1,74 +0,0 @@
--------------------------------------------------------------------------------
BEAST TODO
--------------------------------------------------------------------------------
- Use SemanticVersion for beast version numbers to replace BEAST_VERSION
- add support for a __PRETTY_FUNCTION__ equivalent for all environments
- add expectThrow() to UnitTest, where it expects an exception
- Import secp256k1 from sipa
- Set sqlite thread safety model to '2' in beast_sqlite
- Document and rename all the sqdb files and classes
- Specialize UnsignedInteger<> for peformance in the storage format
- Rename HeapBlock routines to not conflict with _CRTDBG_MAP_ALLOC macros
- Design a WeakPtr / SharedPtr / SharedObject intrusive system
- Implement beast::Bimap?
- Use Bimap for storage in the DeadlineTimer::Manager, to support
thousands of timers.
- Think about adding a shouldStop bool to InterruptibleThread, along
with a shouldStop () function returning bool, and a stop() method.
- Make OwnedArray add routines return a pointer instead of reference
- Tidy up CacheLine, MemoryAlignment
- Remove anything having to do with DLL builds like
BEAST_DLL, BEAST_DLL_BUILD, BEAST_DISABLE_DLL_ALLOCATORS
- Fix FifoFreeStoreWithTLS reference counting bug
- Implement a reasonable substitute for boost's thread_local_storage
- Think about doing away with BEAST_CALLTYPE and BEAST_API
- Decide if headers should just include BeastConfig.h instead of making the
host program do it.
- Rename malloc/calloc JUCE members that conflict with the debug CRT from MSVC
- Reformat every Doxygen comment
- Fix Doxygen metatags
- update Beast Doxyfile
- Rename include guards to boost style, e.g. BEAST_THROW_H_INCLUDED
- Decide if we should get rid of AtomicCounter, AtomicFlag, AtomicPointer, AtomicState
- Clean up CacheLine, StaticObject
- Clean up ConcurrentObject
- Rename SharedData to SharedState or something?
- Figure out what to do with ReadWriteLock, and NamedPipe which uses it?
- Put BEAST_PUBLIC_FUNCTION in front of all loose functions
- restructure the repo sources to look like this:
/Source/beast/beast_core/beast_core.h
etc...
- Put the BeastConfig.h at the root of the repo.
- Make sure the template BeastConfig.h is included in the Doxyfile
- Implement robust key/value database with bulk write

View File

@@ -24,10 +24,12 @@
#ifndef BEAST_ARITHMETIC_H_INCLUDED
#define BEAST_ARITHMETIC_H_INCLUDED
#include "Config.h"
#include "CStdInt.h"
#include <beast/Config.h>
#include <beast/utility/noexcept.h>
#include <cmath>
#include <cstdint>
#include <algorithm>
namespace beast {
@@ -195,12 +197,6 @@ inline bool isPositiveAndNotGreaterThan (const int valueToTest, const int upperL
}
//==============================================================================
/** Handy function to swap two values. */
template <typename Type>
inline void swapVariables (Type& variable1, Type& variable2)
{
std::swap (variable1, variable2);
}
/** Handy function for getting the number of elements in a simple const C array.
E.g.
@@ -218,54 +214,12 @@ int numElementsInArray (Type (&array)[N])
return N;
}
//==============================================================================
// Some useful maths functions that aren't always present with all compilers and build settings.
/** Using beast_hypot is easier than dealing with the different types of hypot function
that are provided by the various platforms and compilers. */
template <typename Type>
inline Type beast_hypot (Type a, Type b) noexcept
{
#if BEAST_MSVC
return static_cast <Type> (_hypot (a, b));
#else
return static_cast <Type> (hypot (a, b));
#endif
}
/** 64-bit abs function. */
inline int64 abs64 (const int64 n) noexcept
inline std::int64_t abs64 (const std::int64_t n) noexcept
{
return (n >= 0) ? n : -n;
}
//==============================================================================
/** A predefined value for Pi, at double-precision.
@see float_Pi
*/
const double double_Pi = 3.1415926535897932384626433832795;
/** A predefined value for Pi, at single-precision.
@see double_Pi
*/
const float float_Pi = 3.14159265358979323846f;
//==============================================================================
/** The isfinite() method seems to vary between platforms, so this is a
platform-independent function for it.
*/
template <typename FloatingPointType>
inline bool beast_isfinite (FloatingPointType value)
{
#if BEAST_WINDOWS
return _finite (value);
#elif BEAST_ANDROID
return isfinite (value);
#else
return std::isfinite (value);
#endif
}
//==============================================================================
#if BEAST_MSVC
@@ -309,149 +263,6 @@ inline int roundToInt (const FloatType value) noexcept
#pragma optimize ("", on) // resets optimisations to the project defaults
#endif
/** Fast floating-point-to-integer conversion.
This is a slightly slower and slightly more accurate version of roundDoubleToInt(). It works
fine for values above zero, but negative numbers are rounded the wrong way.
*/
inline int roundToIntAccurate (const double value) noexcept
{
#ifdef __INTEL_COMPILER
#pragma float_control (pop)
#endif
return roundToInt (value + 1.5e-8);
}
/** Fast floating-point-to-integer conversion.
This is faster than using the normal c++ cast to convert a double to an int, and
it will round the value to the nearest integer, rather than rounding it down
like the normal cast does.
Note that this routine gets its speed at the expense of some accuracy, and when
rounding values whose floating point component is exactly 0.5, odd numbers and
even numbers will be rounded up or down differently. For a more accurate conversion,
see roundDoubleToIntAccurate().
*/
inline int roundDoubleToInt (const double value) noexcept
{
return roundToInt (value);
}
/** Fast floating-point-to-integer conversion.
This is faster than using the normal c++ cast to convert a float to an int, and
it will round the value to the nearest integer, rather than rounding it down
like the normal cast does.
Note that this routine gets its speed at the expense of some accuracy, and when
rounding values whose floating point component is exactly 0.5, odd numbers and
even numbers will be rounded up or down differently.
*/
inline int roundFloatToInt (const float value) noexcept
{
return roundToInt (value);
}
//==============================================================================
/** Returns true if the specified integer is a power-of-two.
*/
template <typename IntegerType>
bool isPowerOfTwo (IntegerType value)
{
return (value & (value - 1)) == 0;
}
/** Returns the smallest power-of-two which is equal to or greater than the given integer.
*/
inline int nextPowerOfTwo (int n) noexcept
{
--n;
n |= (n >> 1);
n |= (n >> 2);
n |= (n >> 4);
n |= (n >> 8);
n |= (n >> 16);
return n + 1;
}
/** Performs a modulo operation, but can cope with the dividend being negative.
The divisor must be greater than zero.
*/
template <typename IntegerType>
IntegerType negativeAwareModulo (IntegerType dividend, const IntegerType divisor) noexcept
{
bassert (divisor > 0);
dividend %= divisor;
return (dividend < 0) ? (dividend + divisor) : dividend;
}
//==============================================================================
#if (BEAST_INTEL && BEAST_32BIT) || defined (DOXYGEN)
/** This macro can be applied to a float variable to check whether it contains a denormalised
value, and to normalise it if necessary.
On CPUs that aren't vulnerable to denormalisation problems, this will have no effect.
*/
#define BEAST_UNDENORMALISE(x) x += 1.0f; x -= 1.0f;
#else
#define BEAST_UNDENORMALISE(x)
#endif
//==============================================================================
/** This namespace contains a few template classes for helping work out class type variations.
*/
namespace TypeHelpers
{
#if BEAST_VC8_OR_EARLIER
#define PARAMETER_TYPE(type) const type&
#else
/** The ParameterType struct is used to find the best type to use when passing some kind
of object as a parameter.
Of course, this is only likely to be useful in certain esoteric template situations.
Because "typename TypeHelpers::ParameterType<SomeClass>::type" is a bit of a mouthful, there's
a PARAMETER_TYPE(SomeClass) macro that you can use to get the same effect.
E.g. "myFunction (PARAMETER_TYPE (int), PARAMETER_TYPE (MyObject))"
would evaluate to "myfunction (int, const MyObject&)", keeping any primitive types as
pass-by-value, but passing objects as a const reference, to avoid copying.
*/
template <typename Type> struct ParameterType { typedef const Type& type; };
#if ! DOXYGEN
template <typename Type> struct ParameterType <Type&> { typedef Type& type; };
template <typename Type> struct ParameterType <Type*> { typedef Type* type; };
template <> struct ParameterType <char> { typedef char type; };
template <> struct ParameterType <unsigned char> { typedef unsigned char type; };
template <> struct ParameterType <short> { typedef short type; };
template <> struct ParameterType <unsigned short> { typedef unsigned short type; };
template <> struct ParameterType <int> { typedef int type; };
template <> struct ParameterType <unsigned int> { typedef unsigned int type; };
template <> struct ParameterType <long> { typedef long type; };
template <> struct ParameterType <unsigned long> { typedef unsigned long type; };
template <> struct ParameterType <int64> { typedef int64 type; };
template <> struct ParameterType <uint64> { typedef uint64 type; };
template <> struct ParameterType <bool> { typedef bool type; };
template <> struct ParameterType <float> { typedef float type; };
template <> struct ParameterType <double> { typedef double type; };
#endif
/** A helpful macro to simplify the use of the ParameterType template.
@see ParameterType
*/
#define PARAMETER_TYPE(a) typename TypeHelpers::ParameterType<a>::type
#endif
/** These templates are designed to take a type, and if it's a double, they return a double
type; for anything else, they return a float type.
*/
template <typename Type> struct SmallestFloatType { typedef float type; };
template <> struct SmallestFloatType <double> { typedef double type; };
}
}
#endif

View File

@@ -24,9 +24,12 @@
#ifndef BEAST_ATOMIC_H_INCLUDED
#define BEAST_ATOMIC_H_INCLUDED
#include "Config.h"
#include "CStdInt.h"
#include "StaticAssert.h"
#include <beast/Config.h>
#include <beast/StaticAssert.h>
#include <beast/utility/noexcept.h>
#include <cstdint>
namespace beast {
@@ -156,10 +159,10 @@ private:
template <typename Dest, typename Source>
static inline Dest castTo (Source value) noexcept { union { Dest d; Source s; } u; u.s = value; return u.d; }
static inline Type castFrom32Bit (int32 value) noexcept { return castTo <Type, int32> (value); }
static inline Type castFrom64Bit (int64 value) noexcept { return castTo <Type, int64> (value); }
static inline int32 castTo32Bit (Type value) noexcept { return castTo <int32, Type> (value); }
static inline int64 castTo64Bit (Type value) noexcept { return castTo <int64, Type> (value); }
static inline Type castFrom32Bit (std::int32_t value) noexcept { return castTo <Type, std::int32_t> (value); }
static inline Type castFrom64Bit (std::int64_t value) noexcept { return castTo <Type, std::int64_t> (value); }
static inline std::int32_t castTo32Bit (Type value) noexcept { return castTo <std::int32_t, Type> (value); }
static inline std::int64_t castTo64Bit (Type value) noexcept { return castTo <std::int64_t, Type> (value); }
Type operator++ (int); // better to just use pre-increment with atomics..
@@ -172,14 +175,14 @@ private:
return sizeof (ValueType) == 1 ? (ValueType) -(signed char) n
: (sizeof (ValueType) == 2 ? (ValueType) -(short) n
: (sizeof (ValueType) == 4 ? (ValueType) -(int) n
: ((ValueType) -(int64) n)));
: ((ValueType) -(std::int64_t) n)));
}
/** This templated negate function will negate pointers as well as integers */
template <typename PointerType>
inline PointerType* negateValue (PointerType* n) noexcept
{
return reinterpret_cast <PointerType*> (-reinterpret_cast <pointer_sized_int> (n));
return reinterpret_cast <PointerType*> (-reinterpret_cast <std::intptr_t> (n));
}
};
@@ -207,6 +210,9 @@ private:
#define BEAST_64BIT_ATOMICS_UNAVAILABLE 1
#endif
#elif BEAST_CLANG && BEAST_LINUX
#define BEAST_ATOMICS_GCC 1
//==============================================================================
#elif BEAST_GCC
#define BEAST_ATOMICS_GCC 1 // GCC with intrinsics
@@ -269,14 +275,14 @@ template <typename Type>
inline Type Atomic<Type>::get() const noexcept
{
#if BEAST_ATOMICS_MAC
return sizeof (Type) == 4 ? castFrom32Bit ((int32) OSAtomicAdd32Barrier ((int32_t) 0, (BEAST_MAC_ATOMICS_VOLATILE int32_t*) &value))
: castFrom64Bit ((int64) OSAtomicAdd64Barrier ((int64_t) 0, (BEAST_MAC_ATOMICS_VOLATILE int64_t*) &value));
return sizeof (Type) == 4 ? castFrom32Bit ((std::int32_t) OSAtomicAdd32Barrier ((int32_t) 0, (BEAST_MAC_ATOMICS_VOLATILE int32_t*) &value))
: castFrom64Bit ((std::int64_t) OSAtomicAdd64Barrier ((int64_t) 0, (BEAST_MAC_ATOMICS_VOLATILE int64_t*) &value));
#elif BEAST_ATOMICS_WINDOWS
return sizeof (Type) == 4 ? castFrom32Bit ((int32) beast_InterlockedExchangeAdd ((volatile long*) &value, (long) 0))
: castFrom64Bit ((int64) beast_InterlockedExchangeAdd64 ((volatile __int64*) &value, (__int64) 0));
return sizeof (Type) == 4 ? castFrom32Bit ((std::int32_t) beast_InterlockedExchangeAdd ((volatile long*) &value, (long) 0))
: castFrom64Bit ((std::int64_t) beast_InterlockedExchangeAdd64 ((volatile __int64*) &value, (__int64) 0));
#elif BEAST_ATOMICS_GCC
return sizeof (Type) == 4 ? castFrom32Bit ((int32) __sync_add_and_fetch ((volatile int32*) &value, 0))
: castFrom64Bit ((int64) __sync_add_and_fetch ((volatile int64*) &value, 0));
return sizeof (Type) == 4 ? castFrom32Bit ((std::int32_t) __sync_add_and_fetch ((volatile std::int32_t*) &value, 0))
: castFrom64Bit ((std::int64_t) __sync_add_and_fetch ((volatile std::int64_t*) &value, 0));
#endif
}
@@ -288,8 +294,8 @@ inline Type Atomic<Type>::exchange (const Type newValue) noexcept
while (! compareAndSetBool (newValue, currentVal)) { currentVal = value; }
return currentVal;
#elif BEAST_ATOMICS_WINDOWS
return sizeof (Type) == 4 ? castFrom32Bit ((int32) beast_InterlockedExchange ((volatile long*) &value, (long) castTo32Bit (newValue)))
: castFrom64Bit ((int64) beast_InterlockedExchange64 ((volatile __int64*) &value, (__int64) castTo64Bit (newValue)));
return sizeof (Type) == 4 ? castFrom32Bit ((std::int32_t) beast_InterlockedExchange ((volatile long*) &value, (long) castTo32Bit (newValue)))
: castFrom64Bit ((std::int64_t) beast_InterlockedExchange64 ((volatile __int64*) &value, (__int64) castTo64Bit (newValue)));
#endif
}
@@ -297,8 +303,16 @@ template <typename Type>
inline Type Atomic<Type>::operator+= (const Type amountToAdd) noexcept
{
#if BEAST_ATOMICS_MAC
# ifdef __clang__
# pragma clang diagnostic push
# pragma clang diagnostic ignored "-Wint-to-void-pointer-cast"
# pragma clang diagnostic ignored "-Wint-to-pointer-cast"
# endif
return sizeof (Type) == 4 ? (Type) OSAtomicAdd32Barrier ((int32_t) castTo32Bit (amountToAdd), (BEAST_MAC_ATOMICS_VOLATILE int32_t*) &value)
: (Type) OSAtomicAdd64Barrier ((int64_t) amountToAdd, (BEAST_MAC_ATOMICS_VOLATILE int64_t*) &value);
# ifdef __clang__
# pragma clang diagnostic pop
# endif
#elif BEAST_ATOMICS_WINDOWS
return sizeof (Type) == 4 ? (Type) (beast_InterlockedExchangeAdd ((volatile long*) &value, (long) amountToAdd) + (long) amountToAdd)
: (Type) (beast_InterlockedExchangeAdd64 ((volatile __int64*) &value, (__int64) amountToAdd) + (__int64) amountToAdd);
@@ -317,13 +331,21 @@ template <typename Type>
inline Type Atomic<Type>::operator++() noexcept
{
#if BEAST_ATOMICS_MAC
# ifdef __clang__
# pragma clang diagnostic push
# pragma clang diagnostic ignored "-Wint-to-void-pointer-cast"
# pragma clang diagnostic ignored "-Wint-to-pointer-cast"
# endif
return sizeof (Type) == 4 ? (Type) OSAtomicIncrement32Barrier ((BEAST_MAC_ATOMICS_VOLATILE int32_t*) &value)
: (Type) OSAtomicIncrement64Barrier ((BEAST_MAC_ATOMICS_VOLATILE int64_t*) &value);
# ifdef __clang__
# pragma clang diagnostic pop
# endif
#elif BEAST_ATOMICS_WINDOWS
return sizeof (Type) == 4 ? (Type) beast_InterlockedIncrement ((volatile long*) &value)
: (Type) beast_InterlockedIncrement64 ((volatile __int64*) &value);
#elif BEAST_ATOMICS_GCC
return (Type) __sync_add_and_fetch (&value, 1);
return (Type) __sync_add_and_fetch (&value, (Type) 1);
#endif
}
@@ -331,13 +353,21 @@ template <typename Type>
inline Type Atomic<Type>::operator--() noexcept
{
#if BEAST_ATOMICS_MAC
# ifdef __clang__
# pragma clang diagnostic push
# pragma clang diagnostic ignored "-Wint-to-void-pointer-cast"
# pragma clang diagnostic ignored "-Wint-to-pointer-cast"
# endif
return sizeof (Type) == 4 ? (Type) OSAtomicDecrement32Barrier ((BEAST_MAC_ATOMICS_VOLATILE int32_t*) &value)
: (Type) OSAtomicDecrement64Barrier ((BEAST_MAC_ATOMICS_VOLATILE int64_t*) &value);
# ifdef __clang__
# pragma clang diagnostic pop
# endif
#elif BEAST_ATOMICS_WINDOWS
return sizeof (Type) == 4 ? (Type) beast_InterlockedDecrement ((volatile long*) &value)
: (Type) beast_InterlockedDecrement64 ((volatile __int64*) &value);
#elif BEAST_ATOMICS_GCC
return (Type) __sync_add_and_fetch (&value, -1);
return (Type) __sync_add_and_fetch (&value, (Type) -1);
#endif
}
@@ -350,8 +380,8 @@ inline bool Atomic<Type>::compareAndSetBool (const Type newValue, const Type val
#elif BEAST_ATOMICS_WINDOWS
return compareAndSetValue (newValue, valueToCompare) == valueToCompare;
#elif BEAST_ATOMICS_GCC
return sizeof (Type) == 4 ? __sync_bool_compare_and_swap ((volatile int32*) &value, castTo32Bit (valueToCompare), castTo32Bit (newValue))
: __sync_bool_compare_and_swap ((volatile int64*) &value, castTo64Bit (valueToCompare), castTo64Bit (newValue));
return sizeof (Type) == 4 ? __sync_bool_compare_and_swap ((volatile std::int32_t*) &value, castTo32Bit (valueToCompare), castTo32Bit (newValue))
: __sync_bool_compare_and_swap ((volatile std::int64_t*) &value, castTo64Bit (valueToCompare), castTo64Bit (newValue));
#endif
}
@@ -370,11 +400,11 @@ inline Type Atomic<Type>::compareAndSetValue (const Type newValue, const Type va
}
#elif BEAST_ATOMICS_WINDOWS
return sizeof (Type) == 4 ? castFrom32Bit ((int32) beast_InterlockedCompareExchange ((volatile long*) &value, (long) castTo32Bit (newValue), (long) castTo32Bit (valueToCompare)))
: castFrom64Bit ((int64) beast_InterlockedCompareExchange64 ((volatile __int64*) &value, (__int64) castTo64Bit (newValue), (__int64) castTo64Bit (valueToCompare)));
return sizeof (Type) == 4 ? castFrom32Bit ((std::int32_t) beast_InterlockedCompareExchange ((volatile long*) &value, (long) castTo32Bit (newValue), (long) castTo32Bit (valueToCompare)))
: castFrom64Bit ((std::int64_t) beast_InterlockedCompareExchange64 ((volatile __int64*) &value, (__int64) castTo64Bit (newValue), (__int64) castTo64Bit (valueToCompare)));
#elif BEAST_ATOMICS_GCC
return sizeof (Type) == 4 ? castFrom32Bit ((int32) __sync_val_compare_and_swap ((volatile int32*) &value, castTo32Bit (valueToCompare), castTo32Bit (newValue)))
: castFrom64Bit ((int64) __sync_val_compare_and_swap ((volatile int64*) &value, castTo64Bit (valueToCompare), castTo64Bit (newValue)));
return sizeof (Type) == 4 ? castFrom32Bit ((std::int32_t) __sync_val_compare_and_swap ((volatile std::int32_t*) &value, castTo32Bit (valueToCompare), castTo32Bit (newValue)))
: castFrom64Bit ((std::int64_t) __sync_val_compare_and_swap ((volatile std::int64_t*) &value, castTo64Bit (valueToCompare), castTo64Bit (newValue)));
#endif
}

View File

@@ -3,10 +3,6 @@
This file is part of Beast: https://github.com/vinniefalco/Beast
Copyright 2013, Vinnie Falco <vinnie.falco@gmail.com>
Portions of this file are from JUCE.
Copyright (c) 2013 - Raw Material Software Ltd.
Please visit http://www.juce.com
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
@@ -26,6 +22,6 @@
// These classes require boost in order to be used.
#include "boost/ErrorCode.h"
#include <beast/boost/ErrorCode.h>
#endif

View File

@@ -24,9 +24,10 @@
#ifndef BEAST_BYTEORDER_H_INCLUDED
#define BEAST_BYTEORDER_H_INCLUDED
#include "Config.h"
#include "CStdInt.h"
#include "Uncopyable.h"
#include <beast/Config.h>
#include <beast/Uncopyable.h>
#include <cstdint>
namespace beast {
@@ -39,51 +40,51 @@ class ByteOrder : public Uncopyable
public:
//==============================================================================
/** Swaps the upper and lower bytes of a 16-bit integer. */
static uint16 swap (uint16 value);
static std::uint16_t swap (std::uint16_t value);
/** Reverses the order of the 4 bytes in a 32-bit integer. */
static uint32 swap (uint32 value);
static std::uint32_t swap (std::uint32_t value);
/** Reverses the order of the 8 bytes in a 64-bit integer. */
static uint64 swap (uint64 value);
static std::uint64_t swap (std::uint64_t value);
//==============================================================================
/** Swaps the byte order of a 16-bit int if the CPU is big-endian */
static uint16 swapIfBigEndian (uint16 value);
static std::uint16_t swapIfBigEndian (std::uint16_t value);
/** Swaps the byte order of a 32-bit int if the CPU is big-endian */
static uint32 swapIfBigEndian (uint32 value);
static std::uint32_t swapIfBigEndian (std::uint32_t value);
/** Swaps the byte order of a 64-bit int if the CPU is big-endian */
static uint64 swapIfBigEndian (uint64 value);
static std::uint64_t swapIfBigEndian (std::uint64_t value);
/** Swaps the byte order of a 16-bit int if the CPU is little-endian */
static uint16 swapIfLittleEndian (uint16 value);
static std::uint16_t swapIfLittleEndian (std::uint16_t value);
/** Swaps the byte order of a 32-bit int if the CPU is little-endian */
static uint32 swapIfLittleEndian (uint32 value);
static std::uint32_t swapIfLittleEndian (std::uint32_t value);
/** Swaps the byte order of a 64-bit int if the CPU is little-endian */
static uint64 swapIfLittleEndian (uint64 value);
static std::uint64_t swapIfLittleEndian (std::uint64_t value);
//==============================================================================
/** Turns 2 bytes into a little-endian integer. */
static uint16 littleEndianShort (const void* bytes);
static std::uint16_t littleEndianShort (const void* bytes);
/** Turns 4 bytes into a little-endian integer. */
static uint32 littleEndianInt (const void* bytes);
static std::uint32_t littleEndianInt (const void* bytes);
/** Turns 4 bytes into a little-endian integer. */
static uint64 littleEndianInt64 (const void* bytes);
static std::uint64_t littleEndianInt64 (const void* bytes);
/** Turns 2 bytes into a big-endian integer. */
static uint16 bigEndianShort (const void* bytes);
static std::uint16_t bigEndianShort (const void* bytes);
/** Turns 4 bytes into a big-endian integer. */
static uint32 bigEndianInt (const void* bytes);
static std::uint32_t bigEndianInt (const void* bytes);
/** Turns 4 bytes into a big-endian integer. */
static uint64 bigEndianInt64 (const void* bytes);
static std::uint64_t bigEndianInt64 (const void* bytes);
//==============================================================================
/** Converts 3 little-endian bytes into a signed 24-bit value (which is sign-extended to 32 bits). */
@@ -111,16 +112,16 @@ private:
#pragma intrinsic (_byteswap_ulong)
#endif
inline uint16 ByteOrder::swap (uint16 n)
inline std::uint16_t ByteOrder::swap (std::uint16_t n)
{
#if BEAST_USE_INTRINSICSxxx // agh - the MS compiler has an internal error when you try to use this intrinsic!
return static_cast <uint16> (_byteswap_ushort (n));
return static_cast <std::uint16_t> (_byteswap_ushort (n));
#else
return static_cast <uint16> ((n << 8) | (n >> 8));
return static_cast <std::uint16_t> ((n << 8) | (n >> 8));
#endif
}
inline uint32 ByteOrder::swap (uint32 n)
inline std::uint32_t ByteOrder::swap (std::uint32_t n)
{
#if BEAST_MAC || BEAST_IOS
return OSSwapInt32 (n);
@@ -143,48 +144,48 @@ inline uint32 ByteOrder::swap (uint32 n)
#endif
}
inline uint64 ByteOrder::swap (uint64 value)
inline std::uint64_t ByteOrder::swap (std::uint64_t value)
{
#if BEAST_MAC || BEAST_IOS
return OSSwapInt64 (value);
#elif BEAST_USE_INTRINSICS
return _byteswap_uint64 (value);
#else
return (((int64) swap ((uint32) value)) << 32) | swap ((uint32) (value >> 32));
return (((std::int64_t) swap ((std::uint32_t) value)) << 32) | swap ((std::uint32_t) (value >> 32));
#endif
}
#if BEAST_LITTLE_ENDIAN
inline uint16 ByteOrder::swapIfBigEndian (const uint16 v) { return v; }
inline uint32 ByteOrder::swapIfBigEndian (const uint32 v) { return v; }
inline uint64 ByteOrder::swapIfBigEndian (const uint64 v) { return v; }
inline uint16 ByteOrder::swapIfLittleEndian (const uint16 v) { return swap (v); }
inline uint32 ByteOrder::swapIfLittleEndian (const uint32 v) { return swap (v); }
inline uint64 ByteOrder::swapIfLittleEndian (const uint64 v) { return swap (v); }
inline uint16 ByteOrder::littleEndianShort (const void* const bytes) { return *static_cast <const uint16*> (bytes); }
inline uint32 ByteOrder::littleEndianInt (const void* const bytes) { return *static_cast <const uint32*> (bytes); }
inline uint64 ByteOrder::littleEndianInt64 (const void* const bytes) { return *static_cast <const uint64*> (bytes); }
inline uint16 ByteOrder::bigEndianShort (const void* const bytes) { return swap (*static_cast <const uint16*> (bytes)); }
inline uint32 ByteOrder::bigEndianInt (const void* const bytes) { return swap (*static_cast <const uint32*> (bytes)); }
inline uint64 ByteOrder::bigEndianInt64 (const void* const bytes) { return swap (*static_cast <const uint64*> (bytes)); }
inline std::uint16_t ByteOrder::swapIfBigEndian (const std::uint16_t v) { return v; }
inline std::uint32_t ByteOrder::swapIfBigEndian (const std::uint32_t v) { return v; }
inline std::uint64_t ByteOrder::swapIfBigEndian (const std::uint64_t v) { return v; }
inline std::uint16_t ByteOrder::swapIfLittleEndian (const std::uint16_t v) { return swap (v); }
inline std::uint32_t ByteOrder::swapIfLittleEndian (const std::uint32_t v) { return swap (v); }
inline std::uint64_t ByteOrder::swapIfLittleEndian (const std::uint64_t v) { return swap (v); }
inline std::uint16_t ByteOrder::littleEndianShort (const void* const bytes) { return *static_cast <const std::uint16_t*> (bytes); }
inline std::uint32_t ByteOrder::littleEndianInt (const void* const bytes) { return *static_cast <const std::uint32_t*> (bytes); }
inline std::uint64_t ByteOrder::littleEndianInt64 (const void* const bytes) { return *static_cast <const std::uint64_t*> (bytes); }
inline std::uint16_t ByteOrder::bigEndianShort (const void* const bytes) { return swap (*static_cast <const std::uint16_t*> (bytes)); }
inline std::uint32_t ByteOrder::bigEndianInt (const void* const bytes) { return swap (*static_cast <const std::uint32_t*> (bytes)); }
inline std::uint64_t ByteOrder::bigEndianInt64 (const void* const bytes) { return swap (*static_cast <const std::uint64_t*> (bytes)); }
inline bool ByteOrder::isBigEndian() { return false; }
#else
inline uint16 ByteOrder::swapIfBigEndian (const uint16 v) { return swap (v); }
inline uint32 ByteOrder::swapIfBigEndian (const uint32 v) { return swap (v); }
inline uint64 ByteOrder::swapIfBigEndian (const uint64 v) { return swap (v); }
inline uint16 ByteOrder::swapIfLittleEndian (const uint16 v) { return v; }
inline uint32 ByteOrder::swapIfLittleEndian (const uint32 v) { return v; }
inline uint64 ByteOrder::swapIfLittleEndian (const uint64 v) { return v; }
inline uint32 ByteOrder::littleEndianInt (const void* const bytes) { return swap (*static_cast <const uint32*> (bytes)); }
inline uint16 ByteOrder::littleEndianShort (const void* const bytes) { return swap (*static_cast <const uint16*> (bytes)); }
inline uint16 ByteOrder::bigEndianShort (const void* const bytes) { return *static_cast <const uint16*> (bytes); }
inline uint32 ByteOrder::bigEndianInt (const void* const bytes) { return *static_cast <const uint32*> (bytes); }
inline uint64 ByteOrder::bigEndianInt64 (const void* const bytes) { return *static_cast <const uint64*> (bytes); }
inline std::uint16_t ByteOrder::swapIfBigEndian (const std::uint16_t v) { return swap (v); }
inline std::uint32_t ByteOrder::swapIfBigEndian (const std::uint32_t v) { return swap (v); }
inline std::uint64_t ByteOrder::swapIfBigEndian (const std::uint64_t v) { return swap (v); }
inline std::uint16_t ByteOrder::swapIfLittleEndian (const std::uint16_t v) { return v; }
inline std::uint32_t ByteOrder::swapIfLittleEndian (const std::uint32_t v) { return v; }
inline std::uint64_t ByteOrder::swapIfLittleEndian (const std::uint64_t v) { return v; }
inline std::uint32_t ByteOrder::littleEndianInt (const void* const bytes) { return swap (*static_cast <const std::uint32_t*> (bytes)); }
inline std::uint16_t ByteOrder::littleEndianShort (const void* const bytes) { return swap (*static_cast <const std::uint16_t*> (bytes)); }
inline std::uint16_t ByteOrder::bigEndianShort (const void* const bytes) { return *static_cast <const std::uint16_t*> (bytes); }
inline std::uint32_t ByteOrder::bigEndianInt (const void* const bytes) { return *static_cast <const std::uint32_t*> (bytes); }
inline std::uint64_t ByteOrder::bigEndianInt64 (const void* const bytes) { return *static_cast <const std::uint64_t*> (bytes); }
inline bool ByteOrder::isBigEndian() { return true; }
#endif
inline int ByteOrder::littleEndian24Bit (const char* const bytes) { return (((int) bytes[2]) << 16) | (((int) (uint8) bytes[1]) << 8) | ((int) (uint8) bytes[0]); }
inline int ByteOrder::bigEndian24Bit (const char* const bytes) { return (((int) bytes[0]) << 16) | (((int) (uint8) bytes[1]) << 8) | ((int) (uint8) bytes[2]); }
inline int ByteOrder::littleEndian24Bit (const char* const bytes) { return (((int) bytes[2]) << 16) | (((int) (std::uint8_t) bytes[1]) << 8) | ((int) (std::uint8_t) bytes[0]); }
inline int ByteOrder::bigEndian24Bit (const char* const bytes) { return (((int) bytes[0]) << 16) | (((int) (std::uint8_t) bytes[1]) << 8) | ((int) (std::uint8_t) bytes[2]); }
inline void ByteOrder::littleEndian24BitToChars (const int value, char* const destBytes) { destBytes[0] = (char)(value & 0xff); destBytes[1] = (char)((value >> 8) & 0xff); destBytes[2] = (char)((value >> 16) & 0xff); }
inline void ByteOrder::bigEndian24BitToChars (const int value, char* const destBytes) { destBytes[0] = (char)((value >> 16) & 0xff); destBytes[1] = (char)((value >> 8) & 0xff); destBytes[2] = (char)(value & 0xff); }
@@ -211,29 +212,29 @@ struct SwapBytes
// Specializations for signed integers
template <>
struct SwapBytes <int16>
struct SwapBytes <std::int16_t>
{
inline int16 operator() (int16 value) const noexcept
inline std::int16_t operator() (std::int16_t value) const noexcept
{
return static_cast <int16> (ByteOrder::swap (static_cast <uint16> (value)));
return static_cast <std::int16_t> (ByteOrder::swap (static_cast <std::uint16_t> (value)));
}
};
template <>
struct SwapBytes <int32>
struct SwapBytes <std::int32_t>
{
inline int32 operator() (int32 value) const noexcept
inline std::int32_t operator() (std::int32_t value) const noexcept
{
return static_cast <int32> (ByteOrder::swap (static_cast <uint32> (value)));
return static_cast <std::int32_t> (ByteOrder::swap (static_cast <std::uint32_t> (value)));
}
};
template <>
struct SwapBytes <int64>
struct SwapBytes <std::int64_t>
{
inline int64 operator() (int64 value) const noexcept
inline std::int64_t operator() (std::int64_t value) const noexcept
{
return static_cast <int64> (ByteOrder::swap (static_cast <uint64> (value)));
return static_cast <std::int64_t> (ByteOrder::swap (static_cast <std::uint64_t> (value)));
}
};

View File

@@ -1,88 +0,0 @@
//------------------------------------------------------------------------------
/*
This file is part of Beast: https://github.com/vinniefalco/Beast
Copyright 2013, Vinnie Falco <vinnie.falco@gmail.com>
Portions of this file are from JUCE.
Copyright (c) 2013 - Raw Material Software Ltd.
Please visit http://www.juce.com
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//==============================================================================
#ifndef BEAST_CSTDINT_H_INCLUDED
#define BEAST_CSTDINT_H_INCLUDED
#include "Config.h"
namespace beast {
typedef signed char int8;
typedef signed short int16;
typedef signed int int32;
typedef unsigned char uint8;
typedef unsigned short uint16;
typedef unsigned int uint32;
#if BEAST_MSVC
typedef __int64 int64;
typedef unsigned __int64 uint64;
/** A platform-independent macro for writing 64-bit literals, needed because
different compilers have different syntaxes for this.
E.g. writing literal64bit (0x1000000000) will translate to 0x1000000000LL for
GCC, or 0x1000000000 for MSVC.
*/
#define literal64bit(longLiteral) ((__int64) longLiteral)
#else
/** A platform-independent 64-bit integer type. */
typedef long long int64;
/** A platform-independent 64-bit unsigned integer type. */
typedef unsigned long long uint64;
/** A platform-independent macro for writing 64-bit literals, needed because
different compilers have different syntaxes for this.
E.g. writing literal64bit (0x1000000000) will translate to 0x1000000000LL for
GCC, or 0x1000000000 for MSVC.
*/
#define literal64bit(longLiteral) (longLiteral##LL)
#endif
#if BEAST_64BIT
/** A signed integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
typedef int64 pointer_sized_int;
/** An unsigned integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
typedef uint64 pointer_sized_uint;
#elif BEAST_MSVC
/** A signed integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
typedef _W64 int pointer_sized_int;
/** An unsigned integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
typedef _W64 unsigned int pointer_sized_uint;
#else
/** A signed integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
typedef int pointer_sized_int;
/** An unsigned integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
typedef unsigned int pointer_sized_uint;
#endif
#if BEAST_MSVC
typedef pointer_sized_int ssize_t;
#endif
}
#endif

View File

@@ -20,8 +20,13 @@
#ifndef BEAST_CHRONO_H_INCLUDED
#define BEAST_CHRONO_H_INCLUDED
#include "chrono/CPUMeter.h"
#include "chrono/RelativeTime.h"
#include "chrono/ScopedTimeInterval.h"
#include <beast/chrono/abstract_clock.h>
#include <beast/chrono/basic_seconds_clock.h>
#include <beast/chrono/chrono_io.h>
#include <beast/chrono/chrono_util.h>
#include <beast/chrono/manual_clock.h>
#include <beast/chrono/ratio_io.h>
#include <beast/chrono/RelativeTime.h>
#endif

View File

@@ -26,35 +26,38 @@
// VFALCO NOTE this is analogous to <boost/config.hpp>
// Assert to boost that we always have std::array support
#define BOOST_ASIO_HAS_STD_ARRAY 1
#if !defined(BEAST_COMPILER_CONFIG) && !defined(BEAST_NO_COMPILER_CONFIG) && !defined(BEAST_NO_CONFIG)
#include "config/SelectCompilerConfig.h"
#include <beast/config/SelectCompilerConfig.h>
#endif
#ifdef BEAST_COMPILER_CONFIG
#include BEAST_COMPILER_CONFIG
#endif
#if !defined(BEAST_STDLIB_CONFIG) && !defined(BEAST_NO_STDLIB_CONFIG) && !defined(BEAST_NO_CONFIG) && defined(__cplusplus)
#include "config/SelectStdlibConfig.h"
#include <beast/config/SelectStdlibConfig.h>
#endif
#ifdef BEAST_STDLIB_CONFIG
#include BEAST_STDLIB_CONFIG
#endif
#if !defined(BEAST_PLATFORM_CONFIG) && !defined(BEAST_NO_PLATFORM_CONFIG) && !defined(BEAST_NO_CONFIG)
#include "config/SelectCompilerConfig.h"
#include <beast/config/SelectCompilerConfig.h>
#endif
#ifdef BEAST_PLATFORM_CONFIG
#include BEAST_PLATFORM_CONFIG
#endif
// Legacy
#include "Version.h"
#include "config/PlatformConfig.h"
#include "config/CompilerConfig.h"
#include "config/StandardConfig.h"
#include "config/ConfigCheck.h"
#include <beast/Version.h>
#include <beast/config/PlatformConfig.h>
#include <beast/config/CompilerConfig.h>
#include <beast/config/StandardConfig.h>
#include <beast/config/ConfigCheck.h>
// Suffix
#include "config/Suffix.h"
#include <beast/config/Suffix.h>
#endif

View File

@@ -20,8 +20,11 @@
#ifndef BEAST_CRYPTO_H_INCLUDED
#define BEAST_CRYPTO_H_INCLUDED
#include "crypto/MurmurHash.h"
#include "crypto/Sha256.h"
#include <beast/crypto/BinaryEncoding.h>
#include <beast/crypto/MurmurHash.h>
#include <beast/crypto/Sha256.h>
#include <beast/crypto/UnsignedInteger.h>
#include <beast/crypto/UnsignedIntegerCalc.h>
#endif

View File

@@ -1,165 +0,0 @@
//------------------------------------------------------------------------------
/*
This file is part of Beast: https://github.com/vinniefalco/Beast
Copyright 2013, Vinnie Falco <vinnie.falco@gmail.com>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//==============================================================================
#ifndef BEAST_FIXEDARRAY_H_INCLUDED
#define BEAST_FIXEDARRAY_H_INCLUDED
#include "Config.h"
#include <cstddef>
#include <iterator>
#include <stdexcept>
namespace beast {
// Ideas from Boost
/** An array whose size is determined at compile-time.
The interface tries to follow std::vector as closely as possible within
the limitations of having a fixed size.
*/
template <class T, std::size_t N>
class FixedArray
{
public:
T values [N];
typedef T value_type;
typedef T* iterator;
typedef T const* const_iterator;
typedef T& reference;
typedef T const& const_reference;
typedef std::size_t size_type;
typedef std::ptrdiff_t difference_type;
// iterators
iterator begin() { return values; }
const_iterator begin() const { return values; }
const_iterator cbegin() const { return values; }
iterator end() { return values+N; }
const_iterator end() const { return values+N; }
const_iterator cend() const { return values+N; }
typedef std::reverse_iterator <iterator> reverse_iterator;
typedef std::reverse_iterator <const_iterator> const_reverse_iterator;
reverse_iterator rbegin() { return reverse_iterator(end()); }
const_reverse_iterator rbegin() const { return const_reverse_iterator(end()); }
const_reverse_iterator crbegin() const { return const_reverse_iterator(end()); }
reverse_iterator rend() { return reverse_iterator(begin()); }
const_reverse_iterator rend() const { return const_reverse_iterator(begin()); }
const_reverse_iterator crend() const { return const_reverse_iterator(begin()); }
reference operator[](size_type i)
{
bassert (i < N);
return values[i];
}
const_reference operator[](size_type i) const
{
bassert (i < N);
return values[i];
}
reference at(size_type i) { rangecheck(i); return values[i]; }
const_reference at(size_type i) const { rangecheck(i); return values[i]; }
reference front() { return values[0]; }
reference back() { return values[N-1]; }
const_reference front () const { return values[0]; }
const_reference back() const { return values[N-1]; }
static size_type size() { return N; }
static bool empty() { return false; }
static size_type max_size() { return N; }
enum { static_size = N };
T const* data() const { return values; }
T* data() { return values; }
T* c_array() { return values; }
template <typename T2>
FixedArray<T,N>& operator= (FixedArray<T2,N> const& rhs)
{
std::copy (rhs.begin(), rhs.end(), begin());
return *this;
}
void assign (T const& value) { fill (value); }
void fill (T const& value)
{
std::fill_n (begin(), size(), value);
}
void clear ()
{
fill (T ());
}
static void rangecheck (size_type i)
{
if (i >= size())
throw std::out_of_range ("FixedArray<>: index out of range");
}
};
//------------------------------------------------------------------------------
template <class T, std::size_t N>
bool operator== (FixedArray <T, N> const& lhs, FixedArray <T, N> const& rhs)
{
return std::equal (lhs.begin(), lhs.end(), rhs.begin());
}
template <class T, std::size_t N>
bool operator!= (FixedArray <T, N> const& lhs, FixedArray <T, N> const& rhs)
{
return !(lhs==rhs);
}
template <class T, std::size_t N>
bool operator< (FixedArray <T, N> const& lhs, FixedArray <T, N> const& rhs)
{
return std::lexicographical_compare (lhs.begin(), lhs.end(), rhs.begin(), rhs.end());
}
template <class T, std::size_t N>
bool operator> (FixedArray <T, N> const& lhs, FixedArray <T, N> const& rhs)
{
return rhs<lhs;
}
template <class T, std::size_t N>
bool operator<= (FixedArray <T, N> const& lhs, FixedArray <T, N> const& rhs)
{
return !(rhs<lhs);
}
template <class T, std::size_t N>
bool operator>= (FixedArray <T, N> const& lhs, FixedArray <T, N> const& rhs)
{
return !(lhs<rhs);
}
}
#endif

View File

@@ -28,8 +28,8 @@
#include <cstdlib>
#include <stdexcept>
#include "Memory.h"
#include "Uncopyable.h"
#include <beast/Memory.h>
#include <beast/Uncopyable.h>
// If the MSVC debug heap headers were included, disable
// the macros during the juce include since they conflict.
@@ -119,7 +119,7 @@ namespace HeapBlockHelper
then a failed allocation will just leave the heapblock with a null pointer (assuming
that the system's malloc() function doesn't throw).
@see Array, OwnedArray, MemoryBlock
@see Array, MemoryBlock
*/
template <class ElementType, bool throwOnFailure = false>
class HeapBlock : public Uncopyable
@@ -294,7 +294,7 @@ public:
The semantics of this method are the same as malloc() and calloc(), but it
uses realloc() to keep as much of the existing data as possible.
*/
void realloc (const size_t newNumElements, const size_t elementSize = sizeof (ElementType))
void reallocate (const size_t newNumElements, const size_t elementSize = sizeof (ElementType))
{
data = static_cast <ElementType*> (data == nullptr ? std::malloc (newNumElements * elementSize)
: std::realloc (data, newNumElements * elementSize));
@@ -304,7 +304,7 @@ public:
/** Frees any currently-allocated data.
This will free the data and reset this object to be a null pointer.
*/
void free()
void free_up()
{
std::free (data);
data = nullptr;
@@ -339,10 +339,6 @@ private:
{
HeapBlockHelper::ThrowOnFail<throwOnFailure>::check (data);
}
#if ! (defined (BEAST_DLL) || defined (BEAST_DLL_BUILD))
BEAST_PREVENT_HEAP_ALLOCATION // Creating a 'new HeapBlock' would be missing the point!
#endif
};
}

37
src/beast/beast/Insight.h Normal file
View File

@@ -0,0 +1,37 @@
//------------------------------------------------------------------------------
/*
This file is part of Beast: https://github.com/vinniefalco/Beast
Copyright 2013, Vinnie Falco <vinnie.falco@gmail.com>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//==============================================================================
#ifndef BEAST_INSIGHT_H_INCLUDED
#define BEAST_INSIGHT_H_INCLUDED
#include <beast/insight/Counter.h>
#include <beast/insight/CounterImpl.h>
#include <beast/insight/Event.h>
#include <beast/insight/EventImpl.h>
#include <beast/insight/Gauge.h>
#include <beast/insight/GaugeImpl.h>
#include <beast/insight/Group.h>
#include <beast/insight/Groups.h>
#include <beast/insight/Hook.h>
#include <beast/insight/HookImpl.h>
#include <beast/insight/Collector.h>
#include <beast/insight/NullCollector.h>
#include <beast/insight/StatsDCollector.h>
#endif

View File

@@ -20,9 +20,7 @@
#ifndef BEAST_INTRUSIVE_H_INCLUDED
#define BEAST_INTRUSIVE_H_INCLUDED
#include "intrusive/ForwardList.h"
#include "intrusive/IntrusiveArray.h"
#include "intrusive/List.h"
#include "intrusive/LockFreeStack.h"
#include <beast/intrusive/List.h>
#include <beast/intrusive/LockFreeStack.h>
#endif

View File

@@ -26,7 +26,8 @@
#include <cstring>
#include "Config.h"
#include <beast/Config.h>
#include <beast/Uncopyable.h>
namespace beast {
@@ -42,7 +43,7 @@ void zerostruct (Type& structure) noexcept
/** Delete an object pointer, and sets the pointer to null.
Remember that it's not good c++ practice to use delete directly - always try to use a ScopedPointer
Remember that it's not good c++ practice to use delete directly - always try to use a std::unique_ptr
or other automatic lifetime-management system rather than resorting to deleting raw pointers!
*/
template <typename Type>
@@ -77,7 +78,7 @@ Type* createCopyIfNotNull (const Type* pointer)
/** A handy C++ wrapper that creates and deletes an NSAutoreleasePool object using RAII.
You should use the BEAST_AUTORELEASEPOOL macro to create a local auto-release pool on the stack.
*/
class BEAST_API ScopedAutoReleasePool : public Uncopyable
class ScopedAutoReleasePool : public Uncopyable
{
public:
ScopedAutoReleasePool();

View File

@@ -1,95 +0,0 @@
//------------------------------------------------------------------------------
/*
This file is part of Beast: https://github.com/vinniefalco/Beast
Copyright 2013, Vinnie Falco <vinnie.falco@gmail.com>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//==============================================================================
#ifndef BEAST_SAFEBOOL_H_INCLUDED
#define BEAST_SAFEBOOL_H_INCLUDED
namespace beast {
namespace detail {
class SafeBoolBase
{
private:
void disallowed () const { }
public:
void allowed () const { }
protected:
typedef void (SafeBoolBase::*boolean_t) () const;
SafeBoolBase () { }
SafeBoolBase (SafeBoolBase const&) { }
SafeBoolBase& operator= (SafeBoolBase const&)
{
return *this;
}
~SafeBoolBase () { }
};
}
/** Safe evaluation of class as `bool`.
This allows a class to be safely evaluated as a bool without the usual
harmful side effects of the straightforward operator conversion approach.
To use it, derive your class from SafeBool and implement `asBoolean()` as:
@code
bool asBoolean () const;
@endcode
Ideas from http://www.artima.com/cppsource/safebool.html
@class SafeBool
*/
template <typename T = void>
class SafeBool : public detail::SafeBoolBase
{
public:
operator detail::SafeBoolBase::boolean_t () const
{
return (static_cast <T const*> (this))->asBoolean ()
? &SafeBoolBase::allowed : 0;
}
protected:
~SafeBool () { }
};
template <typename T, typename U>
void operator== (SafeBool <T> const& lhs, SafeBool <U> const& rhs)
{
lhs.disallowed ();
}
template <typename T, typename U>
void operator!= (SafeBool <T> const& lhs, SafeBool <U> const& rhs)
{
lhs.disallowed ();
}
}
#endif

View File

@@ -20,11 +20,9 @@
#ifndef BEAST_SMARTPTR_H_INCLUDED
#define BEAST_SMARTPTR_H_INCLUDED
#include "Config.h"
#include <beast/Config.h>
#include "smart_ptr/ContainerDeletePolicy.h"
#include "smart_ptr/SharedObject.h"
#include "smart_ptr/SharedPtr.h"
#include "smart_ptr/ScopedPointer.h"
#include <beast/smart_ptr/SharedObject.h>
#include <beast/smart_ptr/SharedPtr.h>
#endif

View File

@@ -20,8 +20,8 @@
#ifndef BEAST_STRINGS_H_INCLUDED
#define BEAST_STRINGS_H_INCLUDED
#include "strings/String.h"
#include "strings/NewLine.h"
#include <beast/strings/String.h>
#include <beast/strings/NewLine.h>
#endif

View File

@@ -20,18 +20,19 @@
#ifndef BEAST_THREADS_H_INCLUDED
#define BEAST_THREADS_H_INCLUDED
#include "threads/LockGuard.h"
#include "threads/UnlockGuard.h"
#include "threads/TryLockGuard.h"
#include "threads/SharedLockGuard.h"
#include "threads/SharedMutexAdapter.h"
#include "threads/SharedData.h"
#include "threads/ServiceQueue.h"
#include "threads/SpinLock.h"
#include "threads/Stoppable.h"
#include "threads/Thread.h"
#include "threads/ThreadLocalValue.h"
#include "threads/WaitableEvent.h"
#include "threads/ScopedWrapperContext.h"
#include <beast/threads/UnlockGuard.h>
#include <beast/threads/TryLockGuard.h>
#include <beast/threads/SharedLockGuard.h>
#include <beast/threads/SharedMutexAdapter.h>
#include <beast/threads/SharedData.h>
#include <beast/threads/ServiceQueue.h>
#include <beast/threads/SpinLock.h>
#include <beast/threads/Stoppable.h>
#include <beast/threads/Thread.h>
#include <beast/threads/ThreadLocalValue.h>
#include <beast/threads/WaitableEvent.h>
#include <beast/threads/ScopedWrapperContext.h>
#include <beast/threads/semaphore.h>
#endif

View File

@@ -0,0 +1,32 @@
//------------------------------------------------------------------------------
/*
This file is part of Beast: https://github.com/vinniefalco/Beast
Copyright 2013, Vinnie Falco <vinnie.falco@gmail.com>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//==============================================================================
#if BEAST_INCLUDE_BEASTCONFIG
#include <BeastConfig.h>
#endif
#include <beast/asio/impl/IPAddressConversion.cpp>
#include <beast/asio/tests/wrap_handler.test.cpp>
#include <beast/asio/tests/bind_handler.test.cpp>
#include <beast/asio/tests/enable_wait_for_async.test.cpp>
#include <beast/asio/tests/shared_handler.test.cpp>
#include <beast/asio/abstract_socket.cpp> // TEMPORARY!

View File

@@ -20,41 +20,47 @@
#ifndef BEAST_ASIO_IPADDRESSCONVERSION_H_INCLUDED
#define BEAST_ASIO_IPADDRESSCONVERSION_H_INCLUDED
#include "../net/IPAddress.h"
#include <beast/net/IPEndpoint.h>
#include <sstream>
#include <boost/asio.hpp>
namespace beast {
namespace IP {
/** Convert to Endpoint.
The port is set to zero.
*/
Endpoint from_asio (boost::asio::ip::address const& address);
/** Convert to Endpoint. */
Endpoint from_asio (boost::asio::ip::tcp::endpoint const& endpoint);
/** Convert to asio::ip::address.
The port is ignored.
*/
boost::asio::ip::address to_asio_address (Endpoint const& endpoint);
/** Convert to asio::ip::tcp::endpoint. */
boost::asio::ip::tcp::endpoint to_asio_endpoint (Endpoint const& endpoint);
}
}
namespace beast {
// DEPRECATED
struct IPAddressConversion
{
/** Convert to IPAddress.
The port is set to zero.
*/
static IPAddress from_asio (boost::asio::ip::address const& address);
/** Convert to IPAddress, including port. */
static IPAddress from_asio (boost::asio::ip::tcp::endpoint const& endpoint);
/** Convert to asio::ip::address.
The port is ignored.
*/
static boost::asio::ip::address to_asio_address (IPAddress const& address);
/** Convert to asio::ip::tcp::endpoint. */
static boost::asio::ip::tcp::endpoint to_asio_endpoint (IPAddress const& address);
/** Conversions to string. */
/** @{ */
static std::string to_string (boost::asio::ip::tcp::endpoint const& endpoint)
{
std::stringstream ss;
ss << endpoint;
return ss.str();
}
/** @} */
static IP::Endpoint from_asio (boost::asio::ip::address const& address)
{ return IP::from_asio (address); }
static IP::Endpoint from_asio (boost::asio::ip::tcp::endpoint const& endpoint)
{ return IP::from_asio (endpoint); }
static boost::asio::ip::address to_asio_address (IP::Endpoint const& address)
{ return IP::to_asio_address (address); }
static boost::asio::ip::tcp::endpoint to_asio_endpoint (IP::Endpoint const& address)
{ return IP::to_asio_endpoint (address); }
};
}

View File

@@ -0,0 +1,14 @@
# beast::asio
Wrappers and utilities to make working with boost::asio easier.
## Rules for asynchronous objects
If an object calls asynchronous initiating functions it must either:
1. Manage its lifetime by being reference counted
or
2. Wait for all pending completion handlers to be called before
allowing itself to be destroyed.

View File

@@ -0,0 +1,217 @@
//------------------------------------------------------------------------------
/*
This file is part of Beast: https://github.com/vinniefalco/Beast
Copyright 2013, Vinnie Falco <vinnie.falco@gmail.com>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//==============================================================================
#include <beast/asio/abstract_socket.h>
#include <beast/asio/bind_handler.h>
namespace beast {
namespace asio {
#if ! BEAST_COMPILER_CHECKS_SOCKET_OVERRIDES
//------------------------------------------------------------------------------
//
// Socket
//
//------------------------------------------------------------------------------
void* abstract_socket::this_layer_ptr (char const*) const
{
pure_virtual_called ();
return nullptr;
}
//------------------------------------------------------------------------------
//
// native_handle
//
//------------------------------------------------------------------------------
bool abstract_socket::native_handle (char const*, void*)
{
pure_virtual_called ();
return false;
}
//------------------------------------------------------------------------------
//
// basic_io_object
//
//------------------------------------------------------------------------------
boost::asio::io_service& abstract_socket::get_io_service ()
{
pure_virtual_called ();
return *static_cast <boost::asio::io_service*>(nullptr);
}
//------------------------------------------------------------------------------
//
// basic_socket
//
//------------------------------------------------------------------------------
void*
abstract_socket::lowest_layer_ptr (char const*) const
{
pure_virtual_called ();
return nullptr;
}
auto
abstract_socket::cancel (boost::system::error_code& ec) -> error_code
{
return pure_virtual_error (ec);
}
auto
abstract_socket::shutdown (shutdown_type, boost::system::error_code& ec) -> error_code
{
return pure_virtual_error (ec);
}
auto
abstract_socket::close (boost::system::error_code& ec) -> error_code
{
return pure_virtual_error (ec);
}
//------------------------------------------------------------------------------
//
// basic_socket_acceptor
//
//------------------------------------------------------------------------------
auto
abstract_socket::accept (abstract_socket&, error_code& ec) -> error_code
{
return pure_virtual_error (ec);
}
void
abstract_socket::async_accept (abstract_socket&, error_handler handler)
{
get_io_service ().post (bind_handler (
handler, pure_virtual_error()));
}
//------------------------------------------------------------------------------
//
// basic_stream_socket
//
//------------------------------------------------------------------------------
std::size_t
abstract_socket::read_some (mutable_buffers, error_code& ec)
{
ec = pure_virtual_error ();
return 0;
}
std::size_t
abstract_socket::write_some (const_buffers, error_code& ec)
{
ec = pure_virtual_error ();
return 0;
}
void
abstract_socket::async_read_some (mutable_buffers, transfer_handler handler)
{
get_io_service ().post (bind_handler (
handler, pure_virtual_error(), 0));
}
void
abstract_socket::async_write_some (const_buffers, transfer_handler handler)
{
get_io_service ().post (bind_handler (
handler, pure_virtual_error(), 0));
}
//------------------------------------------------------------------------------
//
// ssl::stream
//
//------------------------------------------------------------------------------
void*
abstract_socket::next_layer_ptr (char const*) const
{
pure_virtual_called ();
return nullptr;
}
bool
abstract_socket::needs_handshake ()
{
return false;
}
void
abstract_socket::set_verify_mode (int)
{
pure_virtual_called ();
}
auto
abstract_socket::handshake (handshake_type, error_code& ec) -> error_code
{
return pure_virtual_error (ec);
}
void
abstract_socket::async_handshake (handshake_type, error_handler handler)
{
get_io_service ().post (bind_handler (
handler, pure_virtual_error()));
}
auto
abstract_socket::handshake (handshake_type, const_buffers, error_code& ec) ->
error_code
{
return pure_virtual_error (ec);
}
void
abstract_socket::async_handshake (handshake_type, const_buffers,
transfer_handler handler)
{
get_io_service ().post (bind_handler (
handler, pure_virtual_error(), 0));
}
auto
abstract_socket::shutdown (error_code& ec) -> error_code
{
return pure_virtual_error (ec);
}
void
abstract_socket::async_shutdown (error_handler handler)
{
get_io_service ().post (bind_handler (
handler, pure_virtual_error()));
}
#endif
}
}

View File

@@ -17,8 +17,28 @@
*/
//==============================================================================
#ifndef BEAST_ASIO_SOCKETS_SOCKET_H_INCLUDED
#define BEAST_ASIO_SOCKETS_SOCKET_H_INCLUDED
#ifndef BEAST_ASIO_ABSTRACT_SOCKET_H_INCLUDED
#define BEAST_ASIO_ABSTRACT_SOCKET_H_INCLUDED
#include <beast/asio/buffer_sequence.h>
#include <beast/asio/shared_handler.h>
#include <boost/asio/io_service.hpp>
#include <boost/asio/socket_base.hpp>
#include <boost/asio/ssl/stream_base.hpp>
// Checking overrides replaces unimplemented stubs with pure virtuals
#ifndef BEAST_COMPILER_CHECKS_SOCKET_OVERRIDES
# define BEAST_COMPILER_CHECKS_SOCKET_OVERRIDES 1
#endif
#if BEAST_COMPILER_CHECKS_SOCKET_OVERRIDES
# define BEAST_SOCKET_VIRTUAL = 0
#else
# define BEAST_SOCKET_VIRTUAL
#endif
namespace beast {
namespace asio {
/** A high level socket abstraction.
@@ -29,18 +49,61 @@
When member functions are called and the underlying implementation does
not support the operation, a fatal error is generated.
*/
class Socket
: public SocketBase
, public boost::asio::ssl::stream_base
class abstract_socket
: public boost::asio::ssl::stream_base
, public boost::asio::socket_base
{
protected:
typedef boost::system::error_code error_code;
typedef asio::shared_handler <void (void)> post_handler;
typedef asio::shared_handler <void (error_code)> error_handler;
typedef asio::shared_handler <
void (error_code, std::size_t)> transfer_handler;
static
void
pure_virtual_called()
{
throw std::runtime_error ("pure virtual called");
}
static
error_code
pure_virtual_error ()
{
pure_virtual_called();
return boost::system::errc::make_error_code (
boost::system::errc::function_not_supported);
}
static
error_code
pure_virtual_error (error_code& ec)
{
return ec = pure_virtual_error();
}
static
void
throw_if (error_code const& ec)
{
if (ec)
throw boost::system::system_error (ec);
}
public:
virtual ~Socket ();
virtual ~abstract_socket ()
{
}
//--------------------------------------------------------------------------
//
// Socket
// abstract_socket
//
//--------------------------------------------------------------------------
/** Retrieve the underlying object.
@@ -48,32 +111,32 @@ public:
exception is thrown if trying to acquire a reference.
*/
/** @{ */
template <typename Object>
template <class Object>
Object& this_layer ()
{
Object* object (this->this_layer_ptr <Object> ());
if (object == nullptr)
Throw (std::bad_cast (), __FILE__, __LINE__);
throw std::bad_cast ();
return *object;
}
template <typename Object>
template <class Object>
Object const& this_layer () const
{
Object const* object (this->this_layer_ptr <Object> ());
if (object == nullptr)
Throw (std::bad_cast (), __FILE__, __LINE__);
throw std::bad_cast ();
return *object;
}
template <typename Object>
template <class Object>
Object* this_layer_ptr ()
{
return static_cast <Object*> (
this->this_layer_ptr (typeid (Object).name ()));
}
template <typename Object>
template <class Object>
Object const* this_layer_ptr () const
{
return static_cast <Object const*> (
@@ -88,6 +151,7 @@ public:
//
// native_handle
//
//--------------------------------------------------------------------------
/** Retrieve the native representation of the object.
@@ -101,7 +165,7 @@ public:
void native_handle (Handle* dest)
{
if (! native_handle (typeid (Handle).name (), dest))
Throw (std::bad_cast (), __FILE__, __LINE__);
throw std::bad_cast ();
}
virtual bool native_handle (char const* type_name, void* dest)
@@ -111,6 +175,7 @@ public:
//
// basic_io_object
//
//--------------------------------------------------------------------------
virtual boost::asio::io_service& get_io_service ()
BEAST_SOCKET_VIRTUAL;
@@ -119,6 +184,7 @@ public:
//
// basic_socket
//
//--------------------------------------------------------------------------
/** Retrieve the lowest layer object.
@@ -126,32 +192,32 @@ public:
exception is thrown if trying to acquire a reference.
*/
/** @{ */
template <typename Object>
template <class Object>
Object& lowest_layer ()
{
Object* object (this->lowest_layer_ptr <Object> ());
if (object == nullptr)
Throw (std::bad_cast (), __FILE__, __LINE__);
throw std::bad_cast ();
return *object;
}
template <typename Object>
template <class Object>
Object const& lowest_layer () const
{
Object const* object (this->lowest_layer_ptr <Object> ());
if (object == nullptr)
Throw (std::bad_cast (), __FILE__, __LINE__);
throw std::bad_cast ();
return *object;
}
template <typename Object>
template <class Object>
Object* lowest_layer_ptr ()
{
return static_cast <Object*> (
this->lowest_layer_ptr (typeid (Object).name ()));
}
template <typename Object>
template <class Object>
Object const* lowest_layer_ptr () const
{
return static_cast <Object const*> (
@@ -167,7 +233,8 @@ public:
void cancel ()
{
error_code ec;
throw_error (cancel (ec), __FILE__, __LINE__);
cancel (ec);
throw_if (ec);
}
virtual error_code cancel (error_code& ec)
@@ -176,7 +243,8 @@ public:
void shutdown (shutdown_type what)
{
error_code ec;
throw_error (shutdown (what, ec), __FILE__, __LINE__);
shutdown (what, ec);
throw_if (ec);
}
virtual error_code shutdown (shutdown_type what,
@@ -186,7 +254,8 @@ public:
void close ()
{
error_code ec;
throw_error (close (ec), __FILE__, __LINE__);
close (ec);
throw_if (ec);
}
virtual error_code close (error_code& ec)
@@ -196,82 +265,39 @@ public:
//
// basic_socket_acceptor
//
//--------------------------------------------------------------------------
virtual error_code accept (Socket& peer, error_code& ec)
virtual error_code accept (abstract_socket& peer, error_code& ec)
BEAST_SOCKET_VIRTUAL;
template <typename AcceptHandler>
void async_accept (Socket& peer, BOOST_ASIO_MOVE_ARG(AcceptHandler) handler)
{
return async_accept (peer,
newAcceptHandler (BOOST_ASIO_MOVE_CAST(AcceptHandler)(handler)));
}
virtual void async_accept (Socket& peer, SharedHandlerPtr handler)
virtual void async_accept (abstract_socket& peer, error_handler handler)
BEAST_SOCKET_VIRTUAL;
//--------------------------------------------------------------------------
//
// basic_stream_socket
//
//--------------------------------------------------------------------------
// SyncReadStream
// http://www.boost.org/doc/libs/1_54_0/doc/html/boost_asio/reference/SyncReadStream.html
//
template <typename MutableBufferSequence>
std::size_t read_some (MutableBufferSequence const& buffers,
error_code& ec)
{
return read_some (MutableBuffers (buffers), ec);
}
virtual std::size_t read_some (MutableBuffers const& buffers, error_code& ec)
virtual std::size_t read_some (mutable_buffers buffers, error_code& ec)
BEAST_SOCKET_VIRTUAL;
// SyncWriteStream
// http://www.boost.org/doc/libs/1_54_0/doc/html/boost_asio/reference/SyncWriteStream.html
//
template <typename ConstBufferSequence>
std::size_t write_some (ConstBufferSequence const& buffers, error_code &ec)
{
return write_some (ConstBuffers (buffers), ec);
}
virtual std::size_t write_some (ConstBuffers const& buffers, error_code& ec)
virtual std::size_t write_some (const_buffers buffers, error_code& ec)
BEAST_SOCKET_VIRTUAL;
// AsyncReadStream
// http://www.boost.org/doc/libs/1_54_0/doc/html/boost_asio/reference/AsyncReadStream.html
//
template <typename MutableBufferSequence, typename ReadHandler>
void async_read_some (MutableBufferSequence const& buffers,
BOOST_ASIO_MOVE_ARG(ReadHandler) handler)
{
return async_read_some (MutableBuffers (buffers),
newReadHandler (BOOST_ASIO_MOVE_CAST(ReadHandler)(handler)));
}
virtual void async_read_some (MutableBuffers const& buffers, SharedHandlerPtr handler)
virtual void async_read_some (mutable_buffers buffers,
transfer_handler handler)
BEAST_SOCKET_VIRTUAL;
// AsyncWriteStream
// http://www.boost.org/doc/libs/1_54_0/doc/html/boost_asio/reference/AsyncWriteStream.html
//
template <typename ConstBufferSequence, typename WriteHandler>
void async_write_some (ConstBufferSequence const& buffers,
BOOST_ASIO_MOVE_ARG(WriteHandler) handler)
{
return async_write_some (ConstBuffers (buffers),
newWriteHandler (BOOST_ASIO_MOVE_CAST(WriteHandler)(handler)));
}
virtual void async_write_some (ConstBuffers const& buffers, SharedHandlerPtr handler)
virtual void async_write_some (const_buffers buffers,
transfer_handler handler)
BEAST_SOCKET_VIRTUAL;
//--------------------------------------------------------------------------
//
// ssl::stream
//
//--------------------------------------------------------------------------
/** Retrieve the next layer object.
@@ -279,32 +305,32 @@ public:
exception is thrown if trying to acquire a reference.
*/
/** @{ */
template <typename Object>
template <class Object>
Object& next_layer ()
{
Object* object (this->next_layer_ptr <Object> ());
if (object == nullptr)
Throw (std::bad_cast (), __FILE__, __LINE__);
throw std::bad_cast ();
return *object;
}
template <typename Object>
template <class Object>
Object const& next_layer () const
{
Object const* object (this->next_layer_ptr <Object> ());
if (object == nullptr)
Throw (std::bad_cast (), __FILE__, __LINE__);
throw std::bad_cast ();
return *object;
}
template <typename Object>
template <class Object>
Object* next_layer_ptr ()
{
return static_cast <Object*> (
this->next_layer_ptr (typeid (Object).name ()));
}
template <typename Object>
template <class Object>
Object const* next_layer_ptr () const
{
return static_cast <Object const*> (
@@ -330,107 +356,49 @@ public:
virtual bool needs_handshake ()
BEAST_SOCKET_VIRTUAL;
// http://www.boost.org/doc/libs/1_54_0/doc/html/boost_asio/reference/ssl__verify_mode.html
//
virtual void set_verify_mode (int verify_mode) = 0;
virtual void set_verify_mode (int verify_mode)
BEAST_SOCKET_VIRTUAL;
// ssl::stream::handshake (1 of 4)
// http://www.boost.org/doc/libs/1_54_0/doc/html/boost_asio/reference/ssl__stream/handshake/overload1.html
//
void handshake (handshake_type type)
{
error_code ec;
throw_error (handshake (type, ec), __FILE__, __LINE__);
handshake (type, ec);
throw_if (ec);
}
// ssl::stream::handshake (2 of 4)
// http://www.boost.org/doc/libs/1_54_0/doc/html/boost_asio/reference/ssl__stream/handshake/overload2.html
//
virtual error_code handshake (handshake_type type, error_code& ec)
BEAST_SOCKET_VIRTUAL;
// ssl::stream::async_handshake (1 of 2)
// http://www.boost.org/doc/libs/1_54_0/doc/html/boost_asio/reference/ssl__stream/async_handshake/overload1.html
//
template <typename HandshakeHandler>
void async_handshake (handshake_type type, BOOST_ASIO_MOVE_ARG(HandshakeHandler) handler)
{
return async_handshake (type,
newHandshakeHandler (BOOST_ASIO_MOVE_CAST(HandshakeHandler)(handler)));
}
virtual void async_handshake (handshake_type type, SharedHandlerPtr handler)
virtual void async_handshake (handshake_type type, error_handler handler)
BEAST_SOCKET_VIRTUAL;
//--------------------------------------------------------------------------
#if BEAST_ASIO_HAS_BUFFEREDHANDSHAKE
// ssl::stream::handshake (3 of 4)
// http://www.boost.org/doc/libs/1_54_0/doc/html/boost_asio/reference/ssl__stream/handshake/overload3.html
//
template <typename ConstBufferSequence>
void handshake (handshake_type type, ConstBufferSequence const& buffers)
{
error_code ec;
throw_error (handshake (type, buffers, ec), __FILE__, __LINE__);
}
// ssl::stream::handshake (4 of 4)
// http://www.boost.org/doc/libs/1_54_0/doc/html/boost_asio/reference/ssl__stream/handshake/overload4.html
//
template <typename ConstBufferSequence>
error_code handshake (handshake_type type,
ConstBufferSequence const& buffers, error_code& ec)
{
return handshake (type, ConstBuffers (buffers), ec);
}
virtual error_code handshake (handshake_type type,
ConstBuffers const& buffers, error_code& ec)
BEAST_SOCKET_VIRTUAL;
const_buffers buffers, error_code& ec)
BEAST_SOCKET_VIRTUAL;
// ssl::stream::async_handshake (2 of 2)
// http://www.boost.org/doc/libs/1_54_0/doc/html/boost_asio/reference/ssl__stream/async_handshake/overload2.html
//
template <typename ConstBufferSequence, typename BufferedHandshakeHandler>
void async_handshake (handshake_type type, ConstBufferSequence const& buffers,
BOOST_ASIO_MOVE_ARG(BufferedHandshakeHandler) handler)
{
return async_handshake (type, ConstBuffers (buffers),
newBufferedHandshakeHandler (BOOST_ASIO_MOVE_CAST(BufferedHandshakeHandler)(handler)));
}
virtual void async_handshake (handshake_type type, ConstBuffers const& buffers,
SharedHandlerPtr handler)
BEAST_SOCKET_VIRTUAL;
#endif
virtual void async_handshake (handshake_type type,
const_buffers buffers, transfer_handler handler)
BEAST_SOCKET_VIRTUAL;
//--------------------------------------------------------------------------
// ssl::stream::shutdown
// http://www.boost.org/doc/libs/1_54_0/doc/html/boost_asio/reference/ssl__stream/shutdown.html
//
void shutdown ()
{
error_code ec;
throw_error (shutdown (ec), __FILE__, __LINE__);
shutdown (ec);
throw_if (ec);
}
virtual error_code shutdown (error_code& ec)
BEAST_SOCKET_VIRTUAL;
// ssl::stream::async_shutdown
// http://www.boost.org/doc/libs/1_54_0/doc/html/boost_asio/reference/ssl__stream/async_shutdown.html
//
template <typename ShutdownHandler>
void async_shutdown (BOOST_ASIO_MOVE_ARG(ShutdownHandler) handler)
{
return async_shutdown (
newShutdownHandler (BOOST_ASIO_MOVE_CAST(ShutdownHandler)(handler)));
}
virtual void async_shutdown (SharedHandlerPtr handler)
virtual void async_shutdown (error_handler handler)
BEAST_SOCKET_VIRTUAL;
};
}
}
#endif

View File

@@ -0,0 +1,164 @@
//------------------------------------------------------------------------------
/*
This file is part of Beast: https://github.com/vinniefalco/Beast
Copyright 2013, Vinnie Falco <vinnie.falco@gmail.com>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//==============================================================================
#ifndef BEAST_ASIO_BIND_HANDLER_H_INCLUDED
#define BEAST_ASIO_BIND_HANDLER_H_INCLUDED
#include <boost/asio/detail/handler_alloc_helpers.hpp>
#include <boost/asio/detail/handler_cont_helpers.hpp>
#include <boost/asio/detail/handler_invoke_helpers.hpp>
#include <functional>
#include <beast/cxx14/type_traits.h> // <type_traits>
#include <beast/cxx14/utility.h> // <utility>
namespace beast {
namespace asio {
namespace detail {
/** Nullary handler that calls Handler with bound arguments.
The rebound handler provides the same io_service execution
guarantees as the original handler.
*/
template <class DeducedHandler, class... Args>
class bound_handler
{
private:
typedef std::tuple <std::decay_t <Args>...> args_type;
std::decay_t <DeducedHandler> m_handler;
args_type m_args;
template <class Handler, class Tuple, std::size_t... S>
static void invoke (Handler& h, Tuple& args,
std::index_sequence <S...>)
{
h (std::get <S> (args)...);
}
public:
typedef void result_type;
explicit
bound_handler (DeducedHandler&& handler, Args&&... args)
: m_handler (std::forward <DeducedHandler> (handler))
, m_args (std::forward <Args> (args)...)
{
}
void
operator() ()
{
invoke (m_handler, m_args,
std::index_sequence_for <Args...> ());
}
void
operator() () const
{
invoke (m_handler, m_args,
std::index_sequence_for <Args...> ());
}
template <class Function>
friend
void
asio_handler_invoke (Function& f, bound_handler* h)
{
boost_asio_handler_invoke_helpers::
invoke (f, h->m_handler);
}
template <class Function>
friend
void
asio_handler_invoke (Function const& f, bound_handler* h)
{
boost_asio_handler_invoke_helpers::
invoke (f, h->m_handler);
}
friend
void*
asio_handler_allocate (std::size_t size, bound_handler* h)
{
return boost_asio_handler_alloc_helpers::
allocate (size, h->m_handler);
}
friend
void
asio_handler_deallocate (void* p, std::size_t size, bound_handler* h)
{
boost_asio_handler_alloc_helpers::
deallocate (p, size, h->m_handler);
}
friend
bool
asio_handler_is_continuation (bound_handler* h)
{
return boost_asio_handler_cont_helpers::
is_continuation (h->m_handler);
}
};
}
//------------------------------------------------------------------------------
/** Binds parameters to a handler to produce a nullary functor.
The returned handler provides the same io_service execution guarantees
as the original handler. This is designed to use as a replacement for
io_service::wrap, to ensure that the handler will not be invoked
immediately by the calling function.
*/
template <class DeducedHandler, class... Args>
detail::bound_handler <DeducedHandler, Args...>
bind_handler (DeducedHandler&& handler, Args&&... args)
{
return detail::bound_handler <DeducedHandler, Args...> (
std::forward <DeducedHandler> (handler),
std::forward <Args> (args)...);
}
}
}
//------------------------------------------------------------------------------
namespace std {
template <class Handler, class... Args>
void bind (beast::asio::detail::bound_handler <
Handler, Args...>, ...) = delete;
#if 0
template <class Handler, class... Args>
struct is_bind_expression <
beast::asio::detail::bound_handler <Handler, Args...>
> : std::true_type
{
};
#endif
}
#endif

View File

@@ -0,0 +1,126 @@
//------------------------------------------------------------------------------
/*
This file is part of Beast: https://github.com/vinniefalco/Beast
Copyright 2013, Vinnie Falco <vinnie.falco@gmail.com>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//==============================================================================
#ifndef BEAST_ASIO_BUFFER_SEQUENCE_H_INCLUDED
#define BEAST_ASIO_BUFFER_SEQUENCE_H_INCLUDED
#include <boost/asio/buffer.hpp>
#include <beast/utility/noexcept.h>
#include <algorithm>
#include <iterator>
#include <beast/cxx14/type_traits.h> // <type_traits>
#include <vector>
namespace beast {
namespace asio {
template <class Buffer>
class buffer_sequence
{
private:
typedef std::vector <Buffer> sequence_type;
public:
typedef Buffer value_type;
typedef typename sequence_type::const_iterator const_iterator;
private:
sequence_type m_buffers;
template <class FwdIter>
void assign (FwdIter first, FwdIter last)
{
m_buffers.clear();
m_buffers.reserve (std::distance (first, last));
for (;first != last; ++first)
m_buffers.push_back (*first);
}
public:
buffer_sequence ()
{
}
template <
class BufferSequence,
class = std::enable_if_t <std::is_constructible <
Buffer, typename BufferSequence::value_type>::value>
>
buffer_sequence (BufferSequence const& s)
{
assign (std::begin (s), std::end (s));
}
template <
class FwdIter,
class = std::enable_if_t <std::is_constructible <
Buffer, typename std::iterator_traits <
FwdIter>::value_type>::value>
>
buffer_sequence (FwdIter first, FwdIter last)
{
assign (first, last);
}
template <class BufferSequence>
std::enable_if_t <std::is_constructible <
Buffer, typename BufferSequence::value_type>::value,
buffer_sequence&
>
operator= (BufferSequence const& s)
{
return assign (s);
}
const_iterator
begin () const noexcept
{
return m_buffers.begin ();
}
const_iterator
end () const noexcept
{
return m_buffers.end ();
}
#if 0
template <class ConstBufferSequence>
void
assign (ConstBufferSequence const& buffers)
{
auto const n (std::distance (
std::begin (buffers), std::end (buffers)));
for (int i = 0, auto iter (std::begin (buffers));
iter != std::end (buffers); ++iter, ++i)
m_buffers[i] = Buffer (boost::asio::buffer_cast <void*> (
*iter), boost::asio::buffer_size (*iter));
}
#endif
};
typedef buffer_sequence <boost::asio::const_buffer> const_buffers;
typedef buffer_sequence <boost::asio::mutable_buffer> mutable_buffers;
}
}
#endif

View File

@@ -0,0 +1,265 @@
//------------------------------------------------------------------------------
/*
This file is part of Beast: https://github.com/vinniefalco/Beast
Copyright 2013, Vinnie Falco <vinnie.falco@gmail.com>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//==============================================================================
#ifndef BEAST_ASIO_ENABLE_WAIT_FOR_ASYNC_H_INCLUDED
#define BEAST_ASIO_ENABLE_WAIT_FOR_ASYNC_H_INCLUDED
#include <beast/asio/wrap_handler.h>
#include <beast/utility/is_call_possible.h>
#include <boost/asio/detail/handler_alloc_helpers.hpp>
#include <boost/asio/detail/handler_cont_helpers.hpp>
#include <boost/asio/detail/handler_invoke_helpers.hpp>
#include <atomic>
#include <condition_variable>
#include <mutex>
#include <beast/cxx14/type_traits.h> // <type_traits>
namespace beast {
namespace asio {
namespace detail {
template <class Owner, class Handler>
class ref_counted_wrapped_handler
{
private:
static_assert (std::is_same <std::decay_t <Owner>, Owner>::value,
"Owner cannot be a const or reference type");
Handler m_handler;
std::reference_wrapper <Owner> m_owner;
bool m_continuation;
public:
ref_counted_wrapped_handler (Owner& owner,
Handler&& handler, bool continuation)
: m_handler (std::move (handler))
, m_owner (owner)
, m_continuation (continuation ? true :
boost_asio_handler_cont_helpers::is_continuation (m_handler))
{
m_owner.get().increment();
}
ref_counted_wrapped_handler (Owner& owner,
Handler const& handler, bool continuation)
: m_handler (handler)
, m_owner (owner)
, m_continuation (continuation ? true :
boost_asio_handler_cont_helpers::is_continuation (m_handler))
{
m_owner.get().increment();
}
~ref_counted_wrapped_handler ()
{
m_owner.get().decrement();
}
ref_counted_wrapped_handler (ref_counted_wrapped_handler const& other)
: m_handler (other.m_handler)
, m_owner (other.m_owner)
, m_continuation (other.m_continuation)
{
m_owner.get().increment();
}
ref_counted_wrapped_handler (ref_counted_wrapped_handler&& other)
: m_handler (std::move (other.m_handler))
, m_owner (other.m_owner)
, m_continuation (other.m_continuation)
{
m_owner.get().increment();
}
ref_counted_wrapped_handler& operator= (
ref_counted_wrapped_handler const&) = delete;
template <class... Args>
void
operator() (Args&&... args)
{
m_handler (std::forward <Args> (args)...);
}
template <class... Args>
void
operator() (Args&&... args) const
{
m_handler (std::forward <Args> (args)...);
}
template <class Function>
friend
void
asio_handler_invoke (Function& f,
ref_counted_wrapped_handler* h)
{
boost_asio_handler_invoke_helpers::
invoke (f, h->m_handler);
}
template <class Function>
friend
void
asio_handler_invoke (Function const& f,
ref_counted_wrapped_handler* h)
{
boost_asio_handler_invoke_helpers::
invoke (f, h->m_handler);
}
friend
void*
asio_handler_allocate (std::size_t size,
ref_counted_wrapped_handler* h)
{
return boost_asio_handler_alloc_helpers::
allocate (size, h->m_handler);
}
friend
void
asio_handler_deallocate (void* p, std::size_t size,
ref_counted_wrapped_handler* h)
{
boost_asio_handler_alloc_helpers::
deallocate (p, size, h->m_handler);
}
friend
bool
asio_handler_is_continuation (ref_counted_wrapped_handler* h)
{
return h->m_continuation;
}
};
}
//------------------------------------------------------------------------------
/** Facilitates blocking until no completion handlers are remaining.
If Derived has this member function:
@code
void on_wait_for_async (void)
@endcode
Then it will be called every time the number of pending completion
handlers transitions to zero from a non-zero value. The call is made
while holding the internal mutex.
*/
template <class Derived>
class enable_wait_for_async
{
private:
BEAST_DEFINE_IS_CALL_POSSIBLE(
has_on_wait_for_async,on_wait_for_async);
void increment()
{
std::lock_guard <decltype(m_mutex)> lock (m_mutex);
++m_count;
}
void notify (std::true_type)
{
static_cast <Derived*> (this)->on_wait_for_async();
}
void notify (std::false_type)
{
}
void decrement()
{
std::lock_guard <decltype(m_mutex)> lock (m_mutex);
--m_count;
if (m_count == 0)
{
m_cond.notify_all();
notify (std::integral_constant <bool,
has_on_wait_for_async<Derived, void(void)>::value>());
}
}
template <class Owner, class Handler>
friend class detail::ref_counted_wrapped_handler;
std::mutex m_mutex;
std::condition_variable m_cond;
std::size_t m_count;
public:
/** Blocks if there are any pending completion handlers. */
void
wait_for_async()
{
std::unique_lock <decltype (m_mutex)> lock (m_mutex);
while (m_count != 0)
m_cond.wait (lock);
}
protected:
enable_wait_for_async()
: m_count (0)
{
}
~enable_wait_for_async()
{
assert (m_count == 0);
}
/** Wraps the specified handler so it can be counted. */
/** @{ */
template <class Handler>
detail::ref_counted_wrapped_handler <
enable_wait_for_async,
std::remove_reference_t <Handler>
>
wrap_with_counter (Handler&& handler, bool continuation = false)
{
return detail::ref_counted_wrapped_handler <enable_wait_for_async,
std::remove_reference_t <Handler>> (*this,
std::forward <Handler> (handler), continuation);
}
template <class Handler>
detail::ref_counted_wrapped_handler <
enable_wait_for_async,
std::remove_reference_t <Handler>
>
wrap_with_counter (continuation_t, Handler&& handler)
{
return detail::ref_counted_wrapped_handler <enable_wait_for_async,
std::remove_reference_t <Handler>> (*this,
std::forward <Handler> (handler), true);
}
/** @} */
};
}
}
#endif

View File

@@ -17,49 +17,51 @@
*/
//==============================================================================
#include "../IPAddressConversion.h"
#include <beast/asio/IPAddressConversion.h>
namespace beast {
namespace IP {
IPAddress IPAddressConversion::from_asio (boost::asio::ip::address const& address)
Endpoint from_asio (boost::asio::ip::address const& address)
{
if (address.is_v4 ())
{
boost::asio::ip::address_v4::bytes_type const bytes (
address.to_v4().to_bytes());
return IPAddress (IPAddress::V4 (
return Endpoint (AddressV4 (
bytes [0], bytes [1], bytes [2], bytes [3]));
}
// VFALCO TODO IPv6 support
bassertfalse;
return IPAddress();
assert(false);
return Endpoint();
}
IPAddress IPAddressConversion::from_asio (boost::asio::ip::tcp::endpoint const& endpoint)
Endpoint from_asio (boost::asio::ip::tcp::endpoint const& endpoint)
{
return from_asio (endpoint.address()).withPort (endpoint.port());
return from_asio (endpoint.address()).at_port (endpoint.port());
}
boost::asio::ip::address IPAddressConversion::to_asio_address (IPAddress const& address)
boost::asio::ip::address to_asio_address (Endpoint const& endpoint)
{
if (address.isV4 ())
if (endpoint.address().is_v4())
{
return boost::asio::ip::address (
boost::asio::ip::address_v4 (
address.v4().value));
endpoint.address().to_v4().value));
}
// VFALCO TODO IPv6 support
bassertfalse;
assert(false);
return boost::asio::ip::address (
boost::asio::ip::address_v6 ());
}
boost::asio::ip::tcp::endpoint IPAddressConversion::to_asio_endpoint (IPAddress const& address)
boost::asio::ip::tcp::endpoint to_asio_endpoint (Endpoint const& endpoint)
{
return boost::asio::ip::tcp::endpoint (
to_asio_address (address), address.port());
to_asio_address (endpoint), endpoint.port());
}
}
}

View File

@@ -0,0 +1,245 @@
//------------------------------------------------------------------------------
/*
This file is part of Beast: https://github.com/vinniefalco/Beast
Copyright 2013, Vinnie Falco <vinnie.falco@gmail.com>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//==============================================================================
#ifndef BEAST_ASIO_IO_LATENCY_PROBE_H_INCLUDED
#define BEAST_ASIO_IO_LATENCY_PROBE_H_INCLUDED
#include <chrono>
#include <condition_variable>
#include <mutex>
#include <stdexcept>
#include <boost/asio/deadline_timer.hpp>
#include <boost/asio/io_service.hpp>
#include <boost/config.hpp>
namespace beast {
/** Measures handler latency on an io_service queue. */
template <class Clock>
class io_latency_probe
{
private:
typedef typename Clock::duration duration;
typedef typename Clock::time_point time_point;
std::recursive_mutex m_mutex;
std::condition_variable_any m_cond;
std::size_t m_count;
duration const m_period;
boost::asio::io_service& m_ios;
boost::asio::deadline_timer m_timer;
bool m_cancel;
public:
io_latency_probe (duration const& period,
boost::asio::io_service& ios)
: m_count (1)
, m_period (period)
, m_ios (ios)
, m_timer (m_ios)
, m_cancel (false)
{
}
~io_latency_probe ()
{
std::unique_lock <decltype (m_mutex)> lock (m_mutex);
cancel (lock, true);
}
/** Return the io_service associated with the latency probe. */
/** @{ */
boost::asio::io_service& get_io_service ()
{
return m_ios;
}
boost::asio::io_service const& get_io_service () const
{
return m_ios;
}
/** @} */
/** Cancel all pending i/o.
Any handlers which have already been queued will still be called.
*/
/** @{ */
void cancel ()
{
std::unique_lock <decltype(m_mutex)> lock (m_mutex);
cancel (lock, true);
}
void cancel_async ()
{
std::unique_lock <decltype(m_mutex)> lock (m_mutex);
cancel (lock, false);
}
/** @} */
/** Measure one sample of i/o latency.
Handler will be called with this signature:
void Handler (Duration d);
*/
template <class Handler>
void sample_one (Handler&& handler)
{
std::lock_guard <decltype(m_mutex)> lock (m_mutex);
if (m_cancel)
throw std::logic_error ("io_latency_probe is canceled");
m_ios.post (sample_op <Handler> (
std::forward <Handler> (handler),
Clock::now(), false, this));
}
/** Initiate continuous i/o latency sampling.
Handler will be called with this signature:
void Handler (std::chrono::milliseconds);
*/
template <class Handler>
void sample (Handler&& handler)
{
std::lock_guard <decltype(m_mutex)> lock (m_mutex);
if (m_cancel)
throw std::logic_error ("io_latency_probe is canceled");
m_ios.post (sample_op <Handler> (
std::forward <Handler> (handler),
Clock::now(), true, this));
}
private:
void cancel (std::unique_lock <decltype (m_mutex)>& lock,
bool wait)
{
if (! m_cancel)
{
--m_count;
m_cancel = true;
}
if (wait)
#ifdef BOOST_NO_CXX11_LAMBDAS
while (m_count != 0)
m_cond.wait (lock);
#else
m_cond.wait (lock, [this] {
return this->m_count == 0; });
#endif
}
void addref ()
{
std::lock_guard <decltype(m_mutex)> lock (m_mutex);
++m_count;
}
void release ()
{
std::lock_guard <decltype(m_mutex)> lock (m_mutex);
if (--m_count == 0)
m_cond.notify_all ();
}
template <class Handler>
struct sample_op
{
Handler m_handler;
time_point m_start;
bool m_repeat;
io_latency_probe* m_probe;
sample_op (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)
{
m_probe->addref();
}
sample_op (sample_op const& other)
: m_handler (other.m_handler)
, m_start (other.m_start)
, m_probe (other.m_probe)
{
m_probe->addref();
}
~sample_op ()
{
m_probe->release();
}
void operator() () const
{
typename Clock::time_point const now (Clock::now());
typename Clock::duration const elapsed (now - m_start);
m_handler (elapsed);
{
std::lock_guard <decltype (m_probe->m_mutex)
> lock (m_probe->m_mutex);
if (m_probe->m_cancel)
return;
}
if (m_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);
if (when <= now)
{
// The latency is too high to maintain the desired
// period so don't bother with a timer.
//
m_probe->m_ios.post (sample_op <Handler> (
m_handler, now, m_repeat, m_probe));
}
else
{
boost::posix_time::microseconds mms (
std::chrono::duration_cast <
std::chrono::microseconds> (
when - now).count ());
m_probe->m_timer.expires_from_now (mms);
m_probe->m_timer.async_wait (sample_op <Handler> (
m_handler, now, m_repeat, m_probe));
}
}
}
void operator () (boost::system::error_code const& ec)
{
typename Clock::time_point const now (Clock::now());
m_probe->m_ios.post (sample_op <Handler> (
m_handler, now, m_repeat, m_probe));
}
};
};
}
#endif

View File

@@ -0,0 +1,426 @@
//------------------------------------------------------------------------------
/*
This file is part of Beast: https://github.com/vinniefalco/Beast
Copyright 2013, Vinnie Falco <vinnie.falco@gmail.com>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//==============================================================================
#ifndef BEAST_ASIO_MEMORY_BUFFER_H_INCLUDED
#define BEAST_ASIO_MEMORY_BUFFER_H_INCLUDED
#include <beast/utility/empty_base_optimization.h>
#include <boost/asio/buffer.hpp>
#include <beast/utility/noexcept.h>
#include <cstddef>
#include <memory>
#include <type_traits>
namespace beast {
namespace asio {
template <
class T,
class Alloc = std::allocator <T>
>
class memory_buffer
: private empty_base_optimization <Alloc>
{
private:
static_assert (std::is_same <char, T>::value ||
std::is_same <unsigned char, T>::value,
"memory_buffer only works with char and unsigned char");
typedef empty_base_optimization <Alloc> Base;
using AllocTraits = std::allocator_traits <Alloc>;
T* m_base;
std::size_t m_size;
public:
typedef std::size_t size_type;
typedef std::ptrdiff_t difference_type;
typedef T& reference;
typedef T const& const_reference;
typedef T* pointer;
typedef T const* const_pointer;
typedef Alloc allocator_type;
typedef T* iterator;
typedef T const* const_iterator;
typedef std::reverse_iterator <iterator> reverse_iterator;
typedef std::reverse_iterator <const_iterator> const_reverse_iterator;
memory_buffer ()
: m_base (nullptr)
, m_size (0)
{
}
memory_buffer (memory_buffer&& other)
: Base (std::move (other))
, m_base (other.m_base)
, m_size (other.m_size)
{
other.m_base = nullptr;
other.m_size = 0;
}
explicit memory_buffer (size_type n)
: m_base (AllocTraits::allocate (Base::member(), n))
, m_size (n)
{
}
explicit memory_buffer (Alloc const& alloc)
: Base (alloc)
, m_base (nullptr)
, m_size (0)
{
}
memory_buffer (size_type n, Alloc const& alloc)
: Base (alloc)
, m_base (AllocTraits::allocate (Base::member(), n))
, m_size (n)
{
}
~memory_buffer()
{
if (m_base != nullptr)
AllocTraits::deallocate (Base::member(), m_base, m_size);
}
memory_buffer& operator= (memory_buffer const&) = delete;
allocator_type
get_allocator() const
{
return Base::member;
}
//
// asio support
//
boost::asio::mutable_buffer
buffer()
{
return boost::asio::mutable_buffer (
data(), bytes());
}
boost::asio::const_buffer
buffer() const
{
return boost::asio::const_buffer (
data(), bytes());
}
boost::asio::mutable_buffers_1
buffers()
{
return boost::asio::mutable_buffers_1 (
data(), bytes());
}
boost::asio::const_buffers_1
buffers() const
{
return boost::asio::const_buffers_1 (
data(), bytes());
}
operator boost::asio::mutable_buffer()
{
return buffer();
}
operator boost::asio::const_buffer() const
{
return buffer();
}
operator boost::asio::mutable_buffers_1()
{
return buffers();
}
operator boost::asio::const_buffers_1() const
{
return buffers();
}
//
// Element access
//
reference
at (size_type pos)
{
if (! (pos < size()))
throw std::out_of_range ("bad array index");
return m_base [pos];
}
const_reference
at (size_type pos) const
{
if (! (pos < size()))
throw std::out_of_range ("bad array index");
return m_base [pos];
}
reference
operator[] (size_type pos) noexcept
{
return m_base [pos];
}
const_reference
operator[] (size_type pos) const noexcept
{
return m_base [pos];
}
reference
back() noexcept
{
return m_base [m_size - 1];
}
const_reference
back() const noexcept
{
return m_base [m_size - 1];
}
reference
front() noexcept
{
return *m_base;
}
const_reference
front() const noexcept
{
return *m_base;
}
pointer
data() noexcept
{
return m_base;
}
const_pointer
data() const noexcept
{
return m_base;
}
//
// Iterators
//
iterator
begin() noexcept
{
return m_base;
}
const_iterator
begin() const noexcept
{
return m_base;
}
const_iterator
cbegin() const noexcept
{
return m_base;
}
iterator
end() noexcept
{
return m_base + m_size;
}
const_iterator
end() const noexcept
{
return m_base + m_size;
}
const_iterator
cend() const noexcept
{
return m_base + m_size;
}
reverse_iterator
rbegin() noexcept
{
return reverse_iterator (end());
}
const_reverse_iterator
rbegin() const noexcept
{
return const_reverse_iterator (cend());
}
const_reverse_iterator
crbegin() const noexcept
{
return const_reverse_iterator (cend());
}
reverse_iterator
rend() noexcept
{
return reverse_iterator (begin());
}
const_reverse_iterator
rend() const noexcept
{
return const_reverse_iterator (cbegin());
}
const_reverse_iterator
crend() const noexcept
{
return const_reverse_iterator (cbegin());
}
//
// Capacity
//
bool
empty() const noexcept
{
return m_size == 0;
}
size_type
size() const noexcept
{
return m_size;
}
size_type
max_size() const noexcept
{
return size();
}
size_type
capacity() const noexcept
{
return size();
}
size_type bytes() const
{
return m_size * sizeof(T);
}
//
// Modifiers
//
template <class U, class A>
friend
void
swap (memory_buffer <U, A>& lhs,
memory_buffer <U, A>& rhs) noexcept;
};
//------------------------------------------------------------------------------
template <class T, class Alloc>
void
swap (memory_buffer <T, Alloc>& lhs,
memory_buffer <T, Alloc>& rhs) noexcept
{
std::swap (lhs.m_base, rhs.m_base);
std::swap (lhs.m_size, rhs.m_size);
}
template <class T, class A1, class A2>
inline
bool
operator== (memory_buffer <T, A1> const& lhs,
memory_buffer <T, A2> const& rhs)
{
return std::equal (lhs.cbegin(), lhs.cend(),
rhs.cbegin(), rhs.cend());
}
template <class T, class A1, class A2>
inline
bool
operator!= (memory_buffer <T, A1> const& lhs,
memory_buffer <T, A2> const& rhs)
{
return ! (lhs == rhs);
}
template <class T, class A1, class A2>
inline
bool
operator< (memory_buffer <T, A1> const& lhs,
memory_buffer <T, A2> const& rhs)
{
return std::lexicographical_compare (
lhs.cbegin(), lhs.cend(), rhs.cbegin(), rhs.cend());
}
template <class T, class A1, class A2>
inline
bool
operator>= (memory_buffer <T, A1> const& lhs,
memory_buffer <T, A2> const& rhs)
{
return ! (lhs < rhs);
}
template <class T, class A1, class A2>
inline
bool
operator> (memory_buffer <T, A1> const& lhs,
memory_buffer <T, A2> const& rhs)
{
return rhs < lhs;
}
template <class T, class A1, class A2>
inline
bool
operator<= (memory_buffer <T, A1> const& lhs,
memory_buffer <T, A2> const& rhs)
{
return ! (rhs < lhs);
}
}
}
#endif

View File

@@ -17,28 +17,23 @@
*/
//==============================================================================
#ifndef BEAST_MPL_COPYCONST_H_INCLUDED
#define BEAST_MPL_COPYCONST_H_INCLUDED
#ifndef BEAST_ASIO_PLACEHOLDERS_H_INCLUDED
#define BEAST_ASIO_PLACEHOLDERS_H_INCLUDED
#include "RemoveConst.h"
#include <functional>
namespace beast {
namespace mpl {
namespace asio {
/** Copy `const` attribute from T to U if present. */
/** @{ */
template <typename T, typename U>
struct CopyConst
{
typedef typename RemoveConst<U>::type type;
};
template <typename T, typename U>
struct CopyConst <T const, U>
{
typedef typename RemoveConst<U>::type const type;
};
/** @} */
namespace placeholders {
// asio placeholders that work with std::bind
namespace {
static auto const error (std::placeholders::_1);
static auto const bytes_transferred (std::placeholders::_2);
static auto const iterator (std::placeholders::_2);
static auto const signal_number (std::placeholders::_2);
}
}
}
}

View File

@@ -0,0 +1,475 @@
//------------------------------------------------------------------------------
/*
This file is part of Beast: https://github.com/vinniefalco/Beast
Copyright 2013, Vinnie Falco <vinnie.falco@gmail.com>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//==============================================================================
#ifndef BEAST_ASIO_SHARED_HANDLER_H_INCLUDED
#define BEAST_ASIO_SHARED_HANDLER_H_INCLUDED
#include <beast/Config.h>
#include <beast/utility/is_call_possible.h>
#include <boost/utility/base_from_member.hpp>
#include <boost/asio/detail/handler_alloc_helpers.hpp>
#include <boost/asio/detail/handler_cont_helpers.hpp>
#include <boost/asio/detail/handler_invoke_helpers.hpp>
#include <beast/utility/noexcept.h>
#include <functional>
#include <memory>
#include <beast/cxx14/type_traits.h> // <type_traits>
#ifndef BEAST_ASIO_NO_ALLOCATE_SHARED
#define BEAST_ASIO_NO_ALLOCATE_SHARED 0
#endif
#ifndef BEAST_ASIO_NO_HANDLER_RESULT_OF
#define BEAST_ASIO_NO_HANDLER_RESULT_OF 1
#endif
namespace beast {
namespace asio {
class shared_handler_wrapper_base
{
public:
virtual ~shared_handler_wrapper_base()
{
}
virtual void invoke (std::function <void (void)> f) = 0;
virtual void* allocate (std::size_t size) = 0;
virtual void deallocate (void* p, std::size_t size) = 0;
virtual bool is_continuation () = 0;
};
//------------------------------------------------------------------------------
template <class Signature>
class shared_handler_wrapper_func
: public shared_handler_wrapper_base
{
private:
std::function <Signature> m_func;
public:
template <class Handler>
explicit shared_handler_wrapper_func (Handler&& handler)
: m_func (std::ref (std::forward <Handler> (handler)))
{
}
template <class... Args>
#if BEAST_ASIO_NO_HANDLER_RESULT_OF
void
#else
std::result_of_t <std::function <Signature> (Args...)>
#endif
operator() (Args&&... args) const
{
return m_func (std::forward <Args> (args)...);
}
};
//------------------------------------------------------------------------------
namespace detail {
#ifdef _MSC_VER
#pragma warning (push)
#pragma warning (disable: 4512) // assignment operator could not be generated
#endif
template <class Signature, class Handler>
class shared_handler_wrapper
: private boost::base_from_member <Handler>
, public shared_handler_wrapper_func <Signature>
{
private:
typedef boost::base_from_member <Handler> Base;
BEAST_DEFINE_IS_CALL_POSSIBLE(has_is_continuation, is_continuation);
public:
shared_handler_wrapper (Handler&& handler)
: boost::base_from_member <Handler> (std::move (handler))
, shared_handler_wrapper_func <Signature> (Base::member)
{
}
shared_handler_wrapper (Handler const& handler)
: boost::base_from_member <Handler> (handler)
, shared_handler_wrapper_func <Signature> (Base::member)
{
}
private:
void
invoke (std::function <void (void)> f) override
{
return boost_asio_handler_invoke_helpers::
invoke (f, Base::member);
}
void*
allocate (std::size_t size) override
{
return boost_asio_handler_alloc_helpers::
allocate (size, Base::member);
}
void
deallocate (void* p, std::size_t size) override
{
boost_asio_handler_alloc_helpers::
deallocate (p, size, Base::member);
}
bool
is_continuation () override
{
return is_continuation (std::integral_constant <bool,
has_is_continuation <Handler, bool(void)>::value>());
}
bool
is_continuation (std::true_type)
{
return Base::member.is_continuation();
}
bool
is_continuation (std::false_type)
{
return boost_asio_handler_cont_helpers::
is_continuation (Base::member);
}
};
#ifdef _MSC_VER
#pragma warning (pop)
#endif
template <class T>
struct is_shared_handler : public std::false_type
{
};
//------------------------------------------------------------------------------
template <class T, class Handler>
class handler_allocator
{
private:
// We want a partial template specialization as a friend
// but that isn't allowed so we friend all versions. This
// should produce a compile error if Handler is not constructible
// from H.
//
template <class U, class H>
friend class handler_allocator;
Handler m_handler;
public:
typedef T value_type;
typedef T* pointer;
template <class U>
struct rebind
{
public:
typedef handler_allocator <U, Handler> other;
};
handler_allocator() = delete;
handler_allocator (Handler const& handler)
: m_handler (handler)
{
}
template <class U>
handler_allocator (
handler_allocator <U, Handler> const& other)
: m_handler (other.m_handler)
{
}
handler_allocator&
operator= (handler_allocator const&) = delete;
pointer
allocate (std::ptrdiff_t n)
{
auto const size (n * sizeof (T));
return static_cast <pointer> (
boost_asio_handler_alloc_helpers::allocate (
size, m_handler));
}
void
deallocate (pointer p, std::ptrdiff_t n)
{
auto const size (n * sizeof (T));
boost_asio_handler_alloc_helpers::deallocate (
p, size, m_handler);
}
// Work-around for MSVC not using allocator_traits
// in the implementation of shared_ptr
//
#ifdef _MSC_VER
void
destroy (T* t)
{
t->~T();
}
#endif
friend
bool
operator== (handler_allocator const& lhs, handler_allocator const& rhs)
{
return true;
}
friend
bool
operator!= (handler_allocator const& lhs, handler_allocator const& rhs)
{
return ! (lhs == rhs);
}
};
}
//------------------------------------------------------------------------------
/** Handler shared reference that provides io_service execution guarantees. */
template <class Signature>
class shared_handler
{
private:
template <class T>
friend class shared_handler_allocator;
typedef shared_handler_wrapper_func <
Signature> wrapper_type;
typedef std::shared_ptr <wrapper_type> ptr_type;
ptr_type m_ptr;
public:
shared_handler()
{
}
template <
class DeducedHandler,
class = std::enable_if_t <
! detail::is_shared_handler <
std::decay_t <DeducedHandler>>::value &&
std::is_constructible <std::function <Signature>,
std::decay_t <DeducedHandler>>::value
>
>
shared_handler (DeducedHandler&& handler)
{
typedef std::remove_reference_t <DeducedHandler> Handler;
#if BEAST_ASIO_NO_ALLOCATE_SHARED
m_ptr = std::make_shared <detail::shared_handler_wrapper <
Signature, Handler>> (std::forward <DeducedHandler> (handler));
#else
m_ptr = std::allocate_shared <detail::shared_handler_wrapper <
Signature, Handler>> (detail::handler_allocator <char, Handler> (
handler), std::forward <DeducedHandler> (handler));
#endif
}
shared_handler (shared_handler&& other)
: m_ptr (std::move (other.m_ptr))
{
}
shared_handler (shared_handler const& other)
: m_ptr (other.m_ptr)
{
}
shared_handler&
operator= (std::nullptr_t)
{
m_ptr = nullptr;
return *this;
}
shared_handler&
operator= (shared_handler const& rhs)
{
m_ptr = rhs.m_ptr;
return *this;
}
shared_handler&
operator= (shared_handler&& rhs)
{
m_ptr = std::move (rhs.m_ptr);
return *this;
}
explicit
operator bool() const noexcept
{
return m_ptr.operator bool();
}
void
reset()
{
m_ptr.reset();
}
template <class... Args>
#if BEAST_ASIO_NO_HANDLER_RESULT_OF
void
#else
std::result_of_t <std::function <Signature> (Args...)>
#endif
operator() (Args&&... args) const
{
return (*m_ptr)(std::forward <Args> (args)...);
}
template <class Function>
friend
void
asio_handler_invoke (Function&& f, shared_handler* h)
{
return h->m_ptr->invoke (f);
}
friend
void*
asio_handler_allocate (
std::size_t size, shared_handler* h)
{
return h->m_ptr->allocate (size);
}
friend
void
asio_handler_deallocate (
void* p, std::size_t size, shared_handler* h)
{
return h->m_ptr->deallocate (p, size);
}
friend
bool
asio_handler_is_continuation (
shared_handler* h)
{
return h->m_ptr->is_continuation ();
}
};
//------------------------------------------------------------------------------
namespace detail {
template <
class Signature
>
struct is_shared_handler <
shared_handler <Signature>
> : public std::true_type
{
};
}
//------------------------------------------------------------------------------
template <class T>
class shared_handler_allocator
{
private:
template <class U>
friend class shared_handler_allocator;
std::shared_ptr <shared_handler_wrapper_base> m_ptr;
public:
typedef T value_type;
typedef T* pointer;
shared_handler_allocator() = delete;
template <class Signature>
shared_handler_allocator (
shared_handler <Signature> const& handler)
: m_ptr (handler.m_ptr)
{
}
template <class U>
shared_handler_allocator (
shared_handler_allocator <U> const& other)
: m_ptr (other.m_ptr)
{
}
pointer
allocate (std::ptrdiff_t n)
{
auto const size (n * sizeof (T));
return static_cast <pointer> (
m_ptr->allocate (size));
}
void
deallocate (pointer p, std::ptrdiff_t n)
{
auto const size (n * sizeof (T));
m_ptr->deallocate (p, size);
}
friend
bool
operator== (shared_handler_allocator const& lhs,
shared_handler_allocator const& rhs)
{
return lhs.m_ptr == rhs.m_ptr;
}
friend
bool
operator!= (shared_handler_allocator const& lhs,
shared_handler_allocator const& rhs)
{
return ! (lhs == rhs);
}
};
}
}
#endif

View File

@@ -0,0 +1,55 @@
//------------------------------------------------------------------------------
/*
This file is part of Beast: https://github.com/vinniefalco/Beast
Copyright 2013, Vinnie Falco <vinnie.falco@gmail.com>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//==============================================================================
// LIBS: boost_system
#if BEAST_INCLUDE_BEASTCONFIG
#include <BeastConfig.h>
#endif
#include <beast/unit_test/suite.h>
#include <beast/asio/bind_handler.h>
#include <functional>
namespace beast {
namespace asio {
class bind_handler_test : public unit_test::suite
{
public:
static void foo (int)
{
}
void run()
{
auto f (bind_handler (
std::bind (&foo, std::placeholders::_1),
42));
f();
pass();
}
};
BEAST_DEFINE_TESTSUITE(bind_handler,asio,beast);
}
}

View File

@@ -0,0 +1,105 @@
//------------------------------------------------------------------------------
/*
This file is part of Beast: https://github.com/vinniefalco/Beast
Copyright 2013, Vinnie Falco <vinnie.falco@gmail.com>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//==============================================================================
#if BEAST_INCLUDE_BEASTCONFIG
#include <BeastConfig.h>
#endif
#include <beast/unit_test/suite.h>
#include <beast/asio/bind_handler.h>
#include <beast/asio/enable_wait_for_async.h>
#include <boost/asio/io_service.hpp>
namespace beast {
class enable_wait_for_async_test : public unit_test::suite
{
public:
typedef boost::system::error_code error_code;
void test()
{
struct handler
{
void operator()(error_code)
{
}
};
struct owner : asio::enable_wait_for_async <owner>
{
bool notified;
owner()
: notified (false)
{
}
void operator()()
{
{
boost::asio::io_service ios;
ios.post (asio::bind_handler (handler(),
error_code()));
ios.run();
ios.reset();
wait_for_async();
}
{
boost::asio::io_service ios;
ios.post (wrap_with_counter (asio::bind_handler (
handler(), error_code())));
ios.run();
wait_for_async();
}
{
boost::asio::io_service ios;
handler h;
ios.post (wrap_with_counter (std::bind (
&handler::operator(), &h,
error_code())));
ios.run();
wait_for_async();
}
}
void on_wait_for_async()
{
notified = true;
}
};
owner o;
o();
expect (o.notified);
}
void run()
{
test();
}
};
BEAST_DEFINE_TESTSUITE(enable_wait_for_async,asio,beast);
}

View File

@@ -0,0 +1,235 @@
//------------------------------------------------------------------------------
/*
This file is part of Beast: https://github.com/vinniefalco/Beast
Copyright 2013, Vinnie Falco <vinnie.falco@gmail.com>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//==============================================================================
#if BEAST_INCLUDE_BEASTCONFIG
#include <BeastConfig.h>
#endif
#include <beast/unit_test/suite.h>
#include <beast/asio/shared_handler.h>
// Disables is_constructible tests for std::function
// Visual Studio std::function fails the is_constructible tests
#ifndef BEAST_NO_STD_FUNCTION_CONSTRUCTIBLE
# ifdef _MSC_VER
# define BEAST_NO_STD_FUNCTION_CONSTRUCTIBLE 1
# else
# define BEAST_NO_STD_FUNCTION_CONSTRUCTIBLE 0
# endif
#endif
namespace beast {
class shared_handler_test : public unit_test::suite
{
public:
struct test_results
{
bool call;
bool invoke;
bool alloc;
bool dealloc;
bool cont;
test_results ()
: call (false)
, invoke (false)
, alloc (false)
, dealloc (false)
, cont (false)
{
}
};
struct test_handler
{
std::reference_wrapper <test_results> results;
explicit test_handler (test_results& results_)
: results (results_)
{
}
void operator() ()
{
results.get().call = true;
}
template <class Function>
friend void asio_handler_invoke (
Function& f, test_handler* h)
{
h->results.get().invoke = true;
f();
}
template <class Function>
friend void asio_handler_invoke (
Function const& f, test_handler* h)
{
h->results.get().invoke = true;
f();
}
friend void* asio_handler_allocate (
std::size_t size, test_handler* h)
{
h->results.get().alloc = true;
return boost::asio::asio_handler_allocate (size);
}
friend void asio_handler_deallocate (
void* p, std::size_t size, test_handler* h)
{
h->results.get().dealloc = true;
boost::asio::asio_handler_deallocate (p, size);
}
friend bool asio_handler_is_continuation (
test_handler* h)
{
h->results.get().cont = true;
return true;
}
};
struct test_invokable
{
bool call;
test_invokable ()
: call (false)
{
}
void operator() ()
{
call = true;
}
};
template <class Handler>
bool async_op (Handler&& handler)
{
void* const p (boost_asio_handler_alloc_helpers::allocate (32, handler));
handler();
boost_asio_handler_alloc_helpers::deallocate (p, 32, handler);
return boost_asio_handler_cont_helpers::is_continuation (handler);
}
void virtual_async_op (asio::shared_handler <void(void)> handler)
{
async_op (handler);
}
void run()
{
#if ! BEAST_NO_STD_FUNCTION_CONSTRUCTIBLE
static_assert (! std::is_constructible <
std::function <void(void)>, int&&>::value,
"Cannot construct std::function from int&&");
static_assert (! std::is_constructible <
std::function <void(void)>, int>::value,
"Cannot construct std::function from int");
static_assert (! std::is_constructible <
asio::shared_handler <void(void)>, int>::value,
"Cannot construct shared_handler from int");
#endif
static_assert (std::is_constructible <
asio::shared_handler <void(int)>,
asio::shared_handler <void(int)>>::value,
"Should construct <void(int)> from <void(int)>");
static_assert (! std::is_constructible <
asio::shared_handler <void(int)>,
asio::shared_handler <void(void)>>::value,
"Can't construct <void(int)> from <void(void)>");
// Hooks called when using the raw handler
{
test_results r;
test_handler h (r);
async_op (h);
expect (r.call);
expect (r.alloc);
expect (r.dealloc);
expect (r.cont);
test_invokable f;
boost_asio_handler_invoke_helpers::invoke (std::ref (f), h);
expect (r.invoke);
expect (f.call);
}
// Use of std::function shows the hooks not getting called
{
test_results r;
std::function <void(void)> fh ((test_handler) (r));
async_op (fh);
expect (r.call);
unexpected (r.alloc);
unexpected (r.dealloc);
unexpected (r.cont);
test_invokable f;
boost_asio_handler_invoke_helpers::invoke (std::ref (f), fh);
unexpected (r.invoke);
expect (f.call);
}
// Make sure shared_handler calls the hooks
{
test_results r;
asio::shared_handler <void(void)> sh ((test_handler)(r));
async_op (sh);
expect (r.call);
expect (r.alloc);
expect (r.dealloc);
expect (r.cont);
test_invokable f;
boost_asio_handler_invoke_helpers::invoke (std::ref (f), sh);
expect (r.invoke);
expect (f.call);
}
// Make sure shared_handler via implicit conversion calls hooks
{
test_results r;
test_handler h (r);
virtual_async_op ((test_handler) (r));
expect (r.call);
expect (r.alloc);
expect (r.dealloc);
expect (r.cont);
}
}
};
BEAST_DEFINE_TESTSUITE(shared_handler,asio,beast);
}

View File

@@ -0,0 +1,280 @@
//------------------------------------------------------------------------------
/*
This file is part of Beast: https://github.com/vinniefalco/Beast
Copyright 2013, Vinnie Falco <vinnie.falco@gmail.com>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//==============================================================================
#if BEAST_INCLUDE_BEASTCONFIG
#include <BeastConfig.h>
#endif
#include <beast/unit_test/suite.h>
#include <beast/asio/wrap_handler.h>
#include <boost/version.hpp>
#include <boost/bind.hpp>
#include <functional>
#include <memory>
namespace beast {
namespace asio {
//------------------------------------------------------------------------------
// Displays the order of destruction of parameters in the bind wrapper
//
class boost_bind_test : public unit_test::suite
{
public:
struct Result
{
std::string text;
void push_back (std::string const& s)
{
if (! text.empty())
text += ", ";
text += s;
}
};
struct Payload
{
std::reference_wrapper <Result> m_result;
std::string m_name;
explicit Payload (Result& result, std::string const& name)
: m_result (result)
, m_name (name)
{
}
~Payload ()
{
m_result.get().push_back (m_name);
}
};
struct Arg
{
std::shared_ptr <Payload> m_payload;
Arg (Result& result, std::string const& name)
: m_payload (std::make_shared <Payload> (result, name))
{
}
};
static void foo (Arg const&, Arg const&, Arg const&)
{
}
void run()
{
{
Result r;
{
boost::bind (&foo,
Arg (r, "one"),
Arg (r, "two"),
Arg (r, "three"));
}
log <<
std::string ("boost::bind (") + r.text + ")";
}
{
Result r;
{
std::bind (&foo,
Arg (r, "one"),
Arg (r, "two"),
Arg (r, "three"));
}
log <<
std::string ("std::bind (") + r.text + ")";
}
pass();
}
};
BEAST_DEFINE_TESTSUITE(boost_bind,asio,beast);
//------------------------------------------------------------------------------
class wrap_handler_test : public unit_test::suite
{
public:
struct test_results
{
bool call;
bool invoke;
bool alloc;
bool dealloc;
bool cont;
test_results ()
: call (false)
, invoke (false)
, alloc (false)
, dealloc (false)
, cont (false)
{
}
};
struct test_handler
{
std::reference_wrapper <test_results> results;
explicit test_handler (test_results& results_)
: results (results_)
{
}
void operator() ()
{
results.get().call = true;
}
template <class Function>
friend void asio_handler_invoke (
Function& f, test_handler* h)
{
h->results.get().invoke = true;
f();
}
template <class Function>
friend void asio_handler_invoke (
Function const& f, test_handler* h)
{
h->results.get().invoke = true;
f();
}
friend void* asio_handler_allocate (
std::size_t, test_handler* h)
{
h->results.get().alloc = true;
return nullptr;
}
friend void asio_handler_deallocate (
void*, std::size_t, test_handler* h)
{
h->results.get().dealloc = true;
}
friend bool asio_handler_is_continuation (
test_handler* h)
{
h->results.get().cont = true;
return true;
}
};
struct test_invokable
{
bool call;
test_invokable ()
: call (false)
{
}
void operator() ()
{
call = true;
}
};
template <class Handler>
bool async_op (Handler&& handler)
{
void* const p (boost_asio_handler_alloc_helpers::allocate (32, handler));
(handler)();
boost_asio_handler_alloc_helpers::deallocate (p, 32, handler);
return boost_asio_handler_cont_helpers::is_continuation (handler);
}
void run()
{
// Hooks called when using the raw handler
{
test_results r;
test_handler h (r);
async_op (h);
expect (r.call);
expect (r.alloc);
expect (r.dealloc);
expect (r.cont);
test_invokable f;
boost_asio_handler_invoke_helpers::invoke (std::ref (f), h);
expect (r.invoke);
expect (f.call);
}
// Use of boost::bind shows the hooks not getting called
{
test_results r;
test_handler h (r);
auto b (std::bind (&test_handler::operator(), &h));
async_op (b);
expect (r.call);
unexpected (r.alloc);
unexpected (r.dealloc);
unexpected (r.cont);
test_invokable f;
boost_asio_handler_invoke_helpers::invoke (std::ref (f), b);
unexpected (r.invoke);
expect (f.call);
}
// Make sure the wrapped handler calls the hooks
{
test_results r;
test_handler h (r);
auto w (wrap_handler (
std::bind (&test_handler::operator(), test_handler(r)), h));
async_op (w);
expect (r.call);
expect (r.alloc);
expect (r.dealloc);
expect (r.cont);
test_invokable f;
boost_asio_handler_invoke_helpers::invoke (std::ref (f), w);
expect (r.invoke);
expect (f.call);
}
}
};
BEAST_DEFINE_TESTSUITE(wrap_handler,asio,beast);
}
}

View File

@@ -0,0 +1,176 @@
//------------------------------------------------------------------------------
/*
This file is part of Beast: https://github.com/vinniefalco/Beast
Copyright 2013, Vinnie Falco <vinnie.falco@gmail.com>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//==============================================================================
#ifndef BEAST_ASIO_WRAP_HANDLER_H_INCLUDED
#define BEAST_ASIO_WRAP_HANDLER_H_INCLUDED
#include <boost/asio/detail/handler_alloc_helpers.hpp>
#include <boost/asio/detail/handler_cont_helpers.hpp>
#include <boost/asio/detail/handler_invoke_helpers.hpp>
#include <beast/cxx14/type_traits.h> // <type_traits>
#include <utility>
namespace beast {
namespace asio {
#ifdef _MSC_VER
#pragma warning (push)
#pragma warning (disable: 4512) // assignment operator could not be generated
#endif
namespace detail {
/** A handler which wraps another handler using a specfic context.
The handler is invoked with the same io_service execution guarantees
as the provided context.
@note A copy of Context is made.
*/
template <class Handler, class Context>
class wrapped_handler
{
private:
Handler m_handler;
Context m_context;
bool m_continuation;
// If this goes off, consider carefully what the intent is.
static_assert (! std::is_reference <Handler>::value,
"Handler should not be a reference type");
public:
wrapped_handler (bool continuation, Handler&& handler, Context context)
: m_handler (std::move (handler))
, m_context (context)
, m_continuation (continuation ? true :
boost_asio_handler_cont_helpers::is_continuation (context))
{
}
wrapped_handler (bool continuation, Handler const& handler, Context context)
: m_handler (handler)
, m_context (context)
, m_continuation (continuation ? true :
boost_asio_handler_cont_helpers::is_continuation (context))
{
}
template <class... Args>
void
operator() (Args&&... args)
{
m_handler (std::forward <Args> (args)...);
}
template <class... Args>
void
operator() (Args&&... args) const
{
m_handler (std::forward <Args> (args)...);
}
template <class Function>
friend
void
asio_handler_invoke (Function& f, wrapped_handler* h)
{
boost_asio_handler_invoke_helpers::
invoke (f, h->m_context);
}
template <class Function>
friend
void
asio_handler_invoke (Function const& f, wrapped_handler* h)
{
boost_asio_handler_invoke_helpers::
invoke (f, h->m_context);
}
friend
void*
asio_handler_allocate (std::size_t size, wrapped_handler* h)
{
return boost_asio_handler_alloc_helpers::
allocate (size, h->m_context);
}
friend
void
asio_handler_deallocate (void* p, std::size_t size, wrapped_handler* h)
{
boost_asio_handler_alloc_helpers::
deallocate (p, size, h->m_context);
}
friend
bool
asio_handler_is_continuation (wrapped_handler* h)
{
return h->m_continuation;
}
};
}
//------------------------------------------------------------------------------
// Tag for dispatching wrap_handler with is_continuation == true
enum continuation_t
{
continuation
};
/** Returns a wrapped handler so it executes within another context.
The handler is invoked with the same io_service execution guarantees
as the provided context. The handler will be copied if necessary.
@note A copy of Context is made.
*/
/** @{ */
template <class DeducedHandler, class Context>
detail::wrapped_handler <
std::remove_reference_t <DeducedHandler>,
Context
>
wrap_handler (DeducedHandler&& handler, Context const& context,
bool continuation = false)
{
typedef std::remove_reference_t <DeducedHandler> Handler;
return detail::wrapped_handler <Handler, Context> (continuation,
std::forward <DeducedHandler> (handler), context);
}
template <class DeducedHandler, class Context>
detail::wrapped_handler <
std::remove_reference_t <DeducedHandler>,
Context
>
wrap_handler (continuation_t, DeducedHandler&& handler,
Context const& context)
{
typedef std::remove_reference_t <DeducedHandler> Handler;
return detail::wrapped_handler <Handler, Context> (true,
std::forward <DeducedHandler> (handler), context);
}
/** @} */
}
}
#endif

View File

@@ -17,9 +17,11 @@
*/
//==============================================================================
#include "BeastConfig.h"
#if BEAST_INCLUDE_BEASTCONFIG
#include <BeastConfig.h>
#endif
#include "ErrorCode.h"
#include <beast/boost/ErrorCode.h>
namespace detail {

View File

@@ -0,0 +1,46 @@
//------------------------------------------------------------------------------
/*
This file is part of Beast: https://github.com/vinniefalco/Beast
Copyright 2013, Vinnie Falco <vinnie.falco@gmail.com>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//==============================================================================
#ifndef BEAST_BOOST_GET_POINTER_H_INCLUDED
#define BEAST_BOOST_GET_POINTER_H_INCLUDED
#include <boost/get_pointer.hpp>
// Boost 1.55 incorrectly defines BOOST_NO_CXX11_SMART_PTR
// when building with clang 3.4 and earlier. This workaround
// gives beast its own overloads.
#ifdef BOOST_NO_CXX11_SMART_PTR
#include <memory>
namespace beast {
template <class T>
T* get_pointer (std::unique_ptr<T> const& p)
{
return p.get();
}
template <class T>
T* get_pointer (std::shared_ptr<T> const& p)
{
return p.get();
}
}
#endif
#endif

View File

@@ -1,159 +0,0 @@
//------------------------------------------------------------------------------
/*
This file is part of Beast: https://github.com/vinniefalco/Beast
Copyright 2013, Vinnie Falco <vinnie.falco@gmail.com>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//==============================================================================
#ifndef BEAST_CHRONO_CPUMETER_H_INCLUDED
#define BEAST_CHRONO_CPUMETER_H_INCLUDED
#include "RelativeTime.h"
#include "ScopedTimeInterval.h"
#include "../threads/SharedData.h"
#include "../Atomic.h"
namespace beast {
/** Measurements of CPU utilization. */
class CPUMeter
{
private:
struct MeasureIdle
{
explicit MeasureIdle (CPUMeter& meter)
: m_meter (&meter)
{ }
void operator() (RelativeTime const& interval) const
{ m_meter->addIdleTime (interval); }
CPUMeter* m_meter;
};
struct MeasureActive
{
explicit MeasureActive (CPUMeter& meter)
: m_meter (&meter)
{ }
void operator() (RelativeTime const& interval) const
{ m_meter->addActiveTime (interval); }
CPUMeter* m_meter;
};
enum
{
// The amount of time an aggregate must accrue before a swap
secondsPerAggregate = 3
// The number of aggregates in the rolling history buffer
,numberOfAggregates = 20
};
// Aggregated sample data
struct Aggregate
{
RelativeTime idle;
RelativeTime active;
// Returns the total number of seconds in the aggregate
double seconds () const
{ return idle.inSeconds() + active.inSeconds(); }
// Reset the accumulated times
void clear ()
{ idle = RelativeTime (0); active = RelativeTime (0); }
Aggregate& operator+= (Aggregate const& other)
{ idle += other.idle; active += other.active; return *this; }
Aggregate& operator-= (Aggregate const& other)
{ idle -= other.idle; active -= other.active; return *this; }
};
struct State
{
State () : index (0)
{
}
// Returns a reference to the current aggregate
Aggregate& front ()
{
return history [index];
}
// Checks the current aggregate to see if we should advance
void update()
{
if (front().seconds() >= secondsPerAggregate)
advance();
}
// Advance the index in the rolling history
void advance ()
{
usage += history [index];
index = (index+1) % numberOfAggregates;
usage -= history [index];
history [index].clear ();
}
// Index of the current aggregate we are accumulating
int index;
// Delta summed usage over the entire history buffer
Aggregate usage;
// The rolling history buffer
Aggregate history [numberOfAggregates];
};
typedef SharedData <State> SharedState;
SharedState m_state;
void addIdleTime (RelativeTime const& interval)
{
SharedState::Access state (m_state);
state->front().idle += interval;
state->update();
}
void addActiveTime (RelativeTime const& interval)
{
SharedState::Access state (m_state);
state->front().active += interval;
state->update();
}
public:
/** The type of container that measures idle time. */
typedef ScopedTimeInterval <MeasureIdle> ScopedIdleTime;
typedef ScopedTimeInterval <MeasureActive> ScopedActiveTime;
/** Returns the fraction of time that the CPU is being used. */
double getUtilization () const
{
SharedState::ConstAccess state (m_state);
double const seconds (state->usage.seconds());
if (seconds > 0)
return (state->usage.active.inSeconds() / seconds);
return 0;
}
};
}
#endif

View File

@@ -17,16 +17,14 @@
*/
//==============================================================================
#ifndef BEAST_CORE_BOOSTINCLUDES_H_INCLUDED
#define BEAST_CORE_BOOSTINCLUDES_H_INCLUDED
#if BEAST_USE_BOOST_FEATURES
#include <boost/config.hpp>
#include <boost/function.hpp>
#include <boost/thread/tss.hpp> // for FifoFreeStoreWithTLS
#include <boost/version.hpp>
#if BEAST_INCLUDE_BEASTCONFIG
#include <BeastConfig.h>
#endif
#endif
#include <beast/Config.h>
#include <beast/chrono/impl/chrono_io.cpp>
#include <beast/chrono/impl/RelativeTime.cpp>
#include <beast/chrono/tests/abstract_clock.test.cpp>
#include <beast/chrono/tests/basic_seconds_clock.test.cpp>

View File

@@ -24,9 +24,10 @@
#ifndef BEAST_CHRONO_RELATIVETIME_H_INCLUDED
#define BEAST_CHRONO_RELATIVETIME_H_INCLUDED
#include "../Config.h"
#include "../strings/String.h"
#include <beast/Config.h>
#include <beast/strings/String.h>
#include <beast/utility/noexcept.h>
#include <string>
#include <sstream>
@@ -40,7 +41,7 @@ namespace beast {
If you need an absolute time, (i.e. a date + time), see the Time class.
*/
class BEAST_API RelativeTime
class RelativeTime
{
public:
//==============================================================================
@@ -87,7 +88,7 @@ public:
/** Creates a new RelativeTime object representing a number of milliseconds.
@see seconds, minutes, hours, days, weeks
*/
static RelativeTime milliseconds (int64 milliseconds) noexcept;
static RelativeTime milliseconds (std::int64_t milliseconds) noexcept;
/** Creates a new RelativeTime object representing a number of seconds.
@see milliseconds, minutes, hours, days, weeks
@@ -118,7 +119,7 @@ public:
/** Returns the number of milliseconds this time represents.
@see milliseconds, inSeconds, inMinutes, inHours, inDays, inWeeks
*/
int64 inMilliseconds() const noexcept;
std::int64_t inMilliseconds() const noexcept;
/** Returns the number of seconds this time represents.
@see inMilliseconds, inMinutes, inHours, inDays, inWeeks

View File

@@ -0,0 +1,169 @@
//------------------------------------------------------------------------------
/*
This file is part of Beast: https://github.com/vinniefalco/Beast
Copyright 2013, Vinnie Falco <vinnie.falco@gmail.com>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//==============================================================================
#ifndef BEAST_CHRONO_ABSTRACT_CLOCK_H_INCLUDED
#define BEAST_CHRONO_ABSTRACT_CLOCK_H_INCLUDED
#include <chrono>
#include <string>
namespace beast {
/** Abstract interface to a clock.
The abstract clock interface allows a dependency injection to take
place so that the choice of implementation can be made at run-time
instead of compile time. The trade-off is that the Duration used to
represent the clock must be chosen at compile time and cannot be
changed. This includes both the choice of representation (integers
for example) and the period in ticks corresponding to one second.
Example:
@code
struct Implementation
{
abstract_clock <std::chrono::seconds>& m_clock;
// Dependency injection
//
explicit Implementation (
abstract_clock <std::chrono::seconds>& clock)
: m_clock (clock)
{
}
};
@endcode
@tparam The length of time, in seconds, corresponding to one tick.
*/
template <class Duration>
class abstract_clock
{
public:
typedef typename Duration::rep rep;
typedef typename Duration::period period;
typedef Duration duration;
typedef std::chrono::time_point <
abstract_clock, duration> time_point;
virtual ~abstract_clock () { }
/** Returns `true` if this is a steady clock. */
virtual bool is_steady () const = 0;
/** Returns the current time. */
virtual time_point now () const = 0;
#if 0
/** Convert the specified time point to a string. */
/** @{ */
//virtual std::string to_string (time_point const& tp) const = 0;
template <class Duration2>
std::string to_string (
std::chrono::time_point <abstract_clock, Duration2> const& tp) const
{
return to_string (
std::chrono::time_point_cast <Duration> (tp));
}
/** @} */
#endif
/** Returning elapsed ticks since the epoch. */
rep elapsed () const
{
return now().time_since_epoch().count();
}
};
//------------------------------------------------------------------------------
namespace detail {
template <class TrivialClock, class Duration>
struct basic_abstract_clock_wrapper : public abstract_clock <Duration>
{
using typename abstract_clock <Duration>::duration;
using typename abstract_clock <Duration>::time_point;
bool is_steady () const
{
return TrivialClock::is_steady;
}
time_point now () const
{
return time_point (duration (
std::chrono::duration_cast <duration> (
TrivialClock::now().time_since_epoch ()).count ()));
}
};
template <class TrivialClock, class Duration>
struct abstract_clock_wrapper
: public basic_abstract_clock_wrapper <TrivialClock, Duration>
{
// generic conversion displays the duration
/*
std::string to_string (typename basic_abstract_clock_wrapper <
TrivialClock, Duration>::time_point const& tp) const
{
std::stringstream ss;
ss << tp.time_since_epoch();
return ss.str ();
}
*/
};
/*
template <class Duration>
struct abstract_clock_wrapper <std::chrono::system_clock, Duration>
: public basic_abstract_clock_wrapper <std::chrono::system_clock, Duration>
{
typedef std::chrono::system_clock clock_type;
std::string to_string (time_point const& tp)
{
std::stringstream ss;
ss << clock_type::time_point (tp.time_since_epoch ());
return ss.str ();
}
};
*/
}
//------------------------------------------------------------------------------
/** Retrieve a discrete clock for a type implementing the Clock concept.
The interface is created as an object with static storage duration.
*/
template <class TrivialClock, class Duration>
abstract_clock <Duration>& get_abstract_clock ()
{
static detail::abstract_clock_wrapper <
TrivialClock, Duration> clock;
return clock;
}
}
#endif

View File

@@ -0,0 +1,37 @@
//------------------------------------------------------------------------------
/*
This file is part of Beast: https://github.com/vinniefalco/Beast
Copyright 2013, Vinnie Falco <vinnie.falco@gmail.com>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//==============================================================================
#ifndef BEAST_CHRONO_ABSTRACT_CLOCK_IO_H_INCLUDED
#define BEAST_CHRONO_ABSTRACT_CLOCK_IO_H_INCLUDED
#include <beast/chrono/chrono_io.h>
namespace beast {
template <class CharT, class Traits, class Duration, class Resolution>
std::basic_ostream <CharT, Traits>&
operator<< (std::basic_ostream <CharT, Traits>& os,
std::chrono::time_point <abstract_clock <Resolution>, Duration> const& tp)
{
return os << tp.time_since_epoch() << " since epoch";
}
}
#endif

View File

@@ -0,0 +1,223 @@
//------------------------------------------------------------------------------
/*
This file is part of Beast: https://github.com/vinniefalco/Beast
Copyright 2013, Vinnie Falco <vinnie.falco@gmail.com>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//==============================================================================
#ifndef BEAST_CHRONO_BASIC_SECONDS_CLOCK_H_INCLUDED
#define BEAST_CHRONO_BASIC_SECONDS_CLOCK_H_INCLUDED
#include <beast/chrono/chrono_util.h>
#include <algorithm>
#include <chrono>
#include <condition_variable>
#include <mutex>
#include <thread>
#include <vector>
namespace beast {
namespace detail {
class seconds_clock_worker
{
public:
virtual void sample () = 0;
};
//------------------------------------------------------------------------------
// Updates the clocks
class seconds_clock_thread
{
public:
typedef std::mutex mutex;
typedef std::condition_variable cond_var;
typedef std::lock_guard <mutex> lock_guard;
typedef std::unique_lock <mutex> unique_lock;
typedef std::chrono::steady_clock clock_type;
typedef std::chrono::seconds seconds;
typedef std::thread thread;
typedef std::vector <seconds_clock_worker*> workers;
bool m_stop;
mutex m_mutex;
cond_var m_cond;
workers m_workers;
thread m_thread;
seconds_clock_thread ()
: m_stop (false)
{
m_thread = thread (std::bind(
&seconds_clock_thread::run, this));
}
~seconds_clock_thread ()
{
stop();
}
void add (seconds_clock_worker& w)
{
lock_guard lock (m_mutex);
m_workers.push_back (&w);
}
void remove (seconds_clock_worker& w)
{
lock_guard lock (m_mutex);
m_workers.erase (std::find (
m_workers.begin (), m_workers.end(), &w));
}
void stop()
{
if (m_thread.joinable())
{
{
lock_guard lock (m_mutex);
m_stop = true;
}
m_cond.notify_all();
m_thread.join();
}
}
void run()
{
unique_lock lock (m_mutex);;
for (;;)
{
for (auto iter : m_workers)
iter->sample();
clock_type::time_point const when (
floor <seconds> (
clock_type::now().time_since_epoch()) +
seconds (1));
if (m_cond.wait_until (lock, when, [this]{ return m_stop; }))
return;
}
}
static seconds_clock_thread& instance ()
{
static seconds_clock_thread singleton;
return singleton;
}
};
}
//------------------------------------------------------------------------------
/** Called before main exits to terminate the utility thread.
This is a workaround for Visual Studio 2013:
http://connect.microsoft.com/VisualStudio/feedback/details/786016/creating-a-global-c-object-that-used-thread-join-in-its-destructor-causes-a-lockup
http://stackoverflow.com/questions/10915233/stdthreadjoin-hangs-if-called-after-main-exits-when-using-vs2012-rc
*/
inline
void
basic_seconds_clock_main_hook()
{
#ifdef _MSC_VER
detail::seconds_clock_thread::instance().stop();
#endif
}
/** A clock whose minimum resolution is one second.
The purpose of this class is to optimize the performance of the now()
member function call. It uses a dedicated thread that wakes up at least
once per second to sample the requested trivial clock.
@tparam TrivialClock The clock to sample.
*/
template <class TrivialClock>
class basic_seconds_clock
{
public:
typedef std::chrono::seconds resolution;
typedef typename resolution::rep rep;
typedef typename resolution::period period;
typedef std::chrono::duration <rep, period> duration;
typedef std::chrono::time_point <basic_seconds_clock> time_point;
static bool const is_steady = TrivialClock::is_steady;
static time_point now ()
{
// Make sure the thread is constructed before the
// worker otherwise we will crash during destruction
// of objects with static storage duration.
struct initializer
{
initializer ()
{
detail::seconds_clock_thread::instance();
}
};
static initializer init;
struct worker : detail::seconds_clock_worker
{
typedef std::mutex mutex;
typedef std::lock_guard <mutex> lock_guard;
time_point m_now;
mutex m_mutex;
static time_point get_now ()
{
return time_point (floor <resolution> (
TrivialClock::now().time_since_epoch()));
}
worker ()
: m_now (get_now ())
{
detail::seconds_clock_thread::instance().add (*this);
}
~worker ()
{
detail::seconds_clock_thread::instance().remove (*this);
}
time_point now()
{
lock_guard lock (m_mutex);
return m_now;
}
void sample ()
{
lock_guard lock (m_mutex);
m_now = get_now ();
}
};
static worker w;
return w.now ();
}
};
}
#endif

File diff suppressed because it is too large Load Diff

View File

@@ -17,46 +17,50 @@
*/
//==============================================================================
#ifndef BEAST_CHRONO_SCOPEDTIMEINTERVAL_H_INCLUDED
#define BEAST_CHRONO_SCOPEDTIMEINTERVAL_H_INCLUDED
#ifndef BEAST_CHRONO_UTIL_H_INCLUDED
#define BEAST_CHRONO_UTIL_H_INCLUDED
#include "../Uncopyable.h"
#include "RelativeTime.h"
// From Howard Hinnant
// http://home.roadrunner.com/~hinnant/duration_io/chrono_util.html
namespace beast {
/** Time measurement using scoped RAII container.
UnaryFunction will be called with this signature:
void (RelativeTime const& interval);
*/
template <class UnaryFunction>
class ScopedTimeInterval : public Uncopyable
// round down
template <class To, class Rep, class Period>
To floor(std::chrono::duration <Rep, Period> const& d)
{
public:
/** Create the measurement with a default-constructed UnaryFunction. */
ScopedTimeInterval ()
: m_start (RelativeTime::fromStartup())
To t = std::chrono::duration_cast<To>(d);
if (t > d)
--t;
return t;
}
// round to nearest, to even on tie
template <class To, class Rep, class Period>
To round (std::chrono::duration <Rep, Period> const& d)
{
To t0 = std::chrono::duration_cast<To>(d);
To t1 = t0;
++t1;
auto diff0 = d - t0;
auto diff1 = t1 - d;
if (diff0 == diff1)
{
if (t0.count() & 1)
return t1;
return t0;
}
else if (diff0 < diff1)
return t0;
return t1;
}
/** Create the measurement with UnaryFunction constructed from one argument. */
template <typename Arg>
explicit ScopedTimeInterval (Arg& arg)
: m_func (arg)
, m_start (RelativeTime::fromStartup ())
{
}
~ScopedTimeInterval ()
{
m_func (RelativeTime::fromStartup() - m_start);
}
private:
UnaryFunction m_func;
RelativeTime m_start;
};
// round up
template <class To, class Rep, class Period>
To ceil (std::chrono::duration <Rep, Period> const& d)
{
To t = std::chrono::duration_cast<To>(d);
if (t < d)
++t;
return t;
}
#endif

View File

@@ -21,7 +21,7 @@
*/
//==============================================================================
#include "../RelativeTime.h"
#include <beast/chrono/RelativeTime.h>
// VFALCO TODO Migrate the localizable strings interfaces for this file
@@ -54,7 +54,7 @@ RelativeTime RelativeTime::milliseconds (const int milliseconds) noexcept
return RelativeTime (milliseconds * 0.001);
}
RelativeTime RelativeTime::milliseconds (const int64 milliseconds) noexcept
RelativeTime RelativeTime::milliseconds (const std::int64_t milliseconds) noexcept
{
return RelativeTime (milliseconds * 0.001);
}
@@ -86,9 +86,9 @@ RelativeTime RelativeTime::weeks (const RelativeTime::value_type numberOfWeeks)
//==============================================================================
int64 RelativeTime::inMilliseconds() const noexcept
std::int64_t RelativeTime::inMilliseconds() const noexcept
{
return (int64) (numSeconds * 1000.0);
return (std::int64_t) (numSeconds * 1000.0);
}
RelativeTime::value_type RelativeTime::inMinutes() const noexcept
@@ -256,23 +256,29 @@ std::string RelativeTime::to_string () const
}
}
namespace beast {
namespace detail {
#if BEAST_WINDOWS
#include <windows.h>
namespace beast {
namespace detail {
static double monotonicCurrentTimeInSeconds()
{
return GetTickCount64() / 1000.0;
}
}
}
#elif BEAST_MAC || BEAST_IOS
#include <time.h>
#include <mach/mach_time.h>
#include <mach/mach.h>
namespace beast {
namespace detail {
static double monotonicCurrentTimeInSeconds()
{
@@ -295,7 +301,7 @@ static double monotonicCurrentTimeInSeconds()
{
numerator = timebase.numer;
// VFALCO NOTE I don't understand this code
//denominator = timebase.denom * (uint64) 1000000 * 1000.0;
//denominator = timebase.denom * (std::uint64_t) 1000000 * 1000.0;
denominator = timebase.denom * 1000000000.0;
}
@@ -309,20 +315,31 @@ static double monotonicCurrentTimeInSeconds()
return mach_absolute_time() * data.ratio;
}
}
}
#else
#include <time.h>
namespace beast {
namespace detail {
static double monotonicCurrentTimeInSeconds()
{
timespec t;
clock_gettime (CLOCK_MONOTONIC, &t);
return t.tv_sec + t.tv_nsec / 1000000000.0;
}
}
}
#endif
namespace beast {
namespace detail {
// Records and returns the time from process startup
static double getStartupTime()
{

View File

@@ -0,0 +1,41 @@
//------------------------------------------------------------------------------
/*
This file is part of Beast: https://github.com/vinniefalco/Beast
Copyright 2013, Vinnie Falco <vinnie.falco@gmail.com>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//==============================================================================
// chrono_io
//
// (C) Copyright Howard Hinnant
// Use, modification and distribution are subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt).
#include <beast/chrono/chrono_io.h>
//_LIBCPP_BEGIN_NAMESPACE_STD
namespace std {
namespace chrono
{
locale::id
durationpunct::id;
} // chrono
//_LIBCPP_END_NAMESPACE_STD
}

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