From c76170a9db232e4ebe169d502f44e0be2756c2f5 Mon Sep 17 00:00:00 2001 From: Marko Budiselic Date: Sun, 22 Apr 2018 08:31:09 +0200 Subject: [PATCH] Clean utils folder (namespaces, function names) Reviewers: teon.banek Reviewed By: teon.banek Subscribers: pullbot Differential Revision: https://phabricator.memgraph.io/D1359 --- poc/rh_hashmap.hpp | 2 +- src/communication/bolt/v1/decoder/decoder.hpp | 12 +- .../bolt/v1/encoder/primitive_encoder.hpp | 4 +- .../concurrent/concurrent_map.hpp | 6 +- src/data_structures/concurrent/skiplist.hpp | 8 +- .../concurrent/skiplist_gc.hpp | 4 +- src/database/graph_db.cpp | 2 +- src/database/graph_db.hpp | 4 +- src/database/indexes/key_index.hpp | 2 +- src/database/indexes/label_property_index.hpp | 4 +- src/database/storage_gc.hpp | 5 +- src/distributed/durability_rpc_clients.cpp | 7 +- .../transactional_cache_cleaner.hpp | 5 +- src/durability/hashed_file_reader.hpp | 2 +- src/durability/hashed_file_writer.hpp | 2 +- src/durability/paths.cpp | 6 +- src/durability/snapshooter.cpp | 1 - src/durability/wal.hpp | 2 +- src/memgraph_bolt.cpp | 6 +- src/query/plan/operator.cpp | 78 +++---- src/query/plan/operator.hpp | 6 +- src/query/plan/vertex_count_cache.hpp | 6 +- src/query/typed_value.cpp | 7 +- src/query/typed_value.hpp | 5 +- src/stats/stats_rpc_messages.hpp | 6 +- src/storage/record_accessor.hpp | 2 +- src/storage/types.hpp | 2 +- src/utils/bswap.hpp | 18 +- src/utils/crtp.hpp | 8 +- src/utils/datetime/datetime.hpp | 27 --- src/utils/datetime/datetime_error.hpp | 8 - src/utils/executor.hpp | 4 + src/utils/fswatcher.hpp | 11 +- src/utils/future.hpp | 5 +- src/utils/hashing/fnv.hpp | 4 + src/utils/log_destructor.hpp | 13 -- src/utils/memory_literals.hpp | 20 -- src/utils/network.hpp | 3 +- src/utils/on_scope_exit.hpp | 1 + src/utils/option.hpp | 197 ------------------ src/utils/placeholder.hpp | 4 + src/utils/random/fast_binomial.hpp | 4 + src/utils/random/random_generator.hpp | 11 +- src/utils/random/xorshift128plus.hpp | 4 + src/utils/scheduler.hpp | 4 + src/utils/stacktrace.hpp | 4 + src/utils/sysinfo/memory.hpp | 5 +- src/utils/terminate_handler.hpp | 25 ++- src/utils/timer.hpp | 3 +- src/utils/{datetime => }/timestamp.hpp | 25 ++- src/utils/total_ordering.hpp | 28 +-- src/utils/type_discovery.hpp | 92 -------- src/utils/watchdog.cpp | 7 +- src/utils/watchdog.hpp | 4 + tests/distributed/raft/example_server.cpp | 2 +- tests/distributed/raft/messages.hpp | 2 +- tests/manual/antlr_sigsegv.cpp | 5 +- tests/manual/binomial.cpp | 2 +- tests/manual/card_fraud_generate_snapshot.cpp | 1 - tests/manual/query_hash.cpp | 1 - tests/manual/xorshift.cpp | 12 +- tests/unit/bolt_common.hpp | 3 +- tests/unit/bolt_session.cpp | 2 +- tests/unit/executor.cpp | 4 +- tests/unit/scheduler.cpp | 2 +- tests/unit/signals.cpp | 2 +- tests/unit/timestamp.cpp | 16 +- tests/unit/watchdog.cpp | 4 +- 68 files changed, 248 insertions(+), 545 deletions(-) delete mode 100644 src/utils/datetime/datetime.hpp delete mode 100644 src/utils/datetime/datetime_error.hpp delete mode 100644 src/utils/log_destructor.hpp delete mode 100644 src/utils/memory_literals.hpp delete mode 100644 src/utils/option.hpp rename src/utils/{datetime => }/timestamp.hpp (73%) delete mode 100644 src/utils/type_discovery.hpp diff --git a/poc/rh_hashmap.hpp b/poc/rh_hashmap.hpp index 152d87ec9..05f3b8ef6 100644 --- a/poc/rh_hashmap.hpp +++ b/poc/rh_hashmap.hpp @@ -64,7 +64,7 @@ class RhBase { // Base for all iterators. It can start from any point in map. template - class IteratorBase : public Crtp { + class IteratorBase : public utils::Crtp { protected: IteratorBase() : map(nullptr) { advanced = index = ~((size_t)0); } IteratorBase(const RhBase *map) { diff --git a/src/communication/bolt/v1/decoder/decoder.hpp b/src/communication/bolt/v1/decoder/decoder.hpp index fe7f51740..0abc03fe8 100644 --- a/src/communication/bolt/v1/decoder/decoder.hpp +++ b/src/communication/bolt/v1/decoder/decoder.hpp @@ -209,7 +209,7 @@ class Decoder { DLOG(WARNING) << "[ReadInt] Int16 missing data!"; return false; } - ret = bswap(tmp); + ret = utils::Bswap(tmp); } else if (marker == Marker::Int32) { VLOG(20) << "[ReadInt] Found an Int32"; int32_t tmp; @@ -217,14 +217,14 @@ class Decoder { DLOG(WARNING) << "[ReadInt] Int32 missing data!"; return false; } - ret = bswap(tmp); + ret = utils::Bswap(tmp); } else if (marker == Marker::Int64) { VLOG(20) << "[ReadInt] Found an Int64"; if (!buffer_.Read(reinterpret_cast(&ret), sizeof(ret))) { DLOG(WARNING) << "[ReadInt] Int64 missing data!"; return false; } - ret = bswap(ret); + ret = utils::Bswap(ret); } else { DLOG(WARNING) << "[ReadInt] Received invalid marker " << utils::UnderlyingCast(marker); @@ -244,7 +244,7 @@ class Decoder { DLOG(WARNING) << "[ReadDouble] Missing data!"; return false; } - value = bswap(value); + value = utils::Bswap(value); // cppcheck-suppress invalidPointerCast ret = *reinterpret_cast(&value); *data = DecodedValue(ret); @@ -272,7 +272,7 @@ class Decoder { DLOG(WARNING) << "[ReadTypeSize] Type16 missing data!"; return -1; } - tmp = bswap(tmp); + tmp = utils::Bswap(tmp); return tmp; } else if (marker == Marker32[type]) { VLOG(20) << "[ReadTypeSize] Found a Type32"; @@ -281,7 +281,7 @@ class Decoder { DLOG(WARNING) << "[ReadTypeSize] Type32 missing data!"; return -1; } - tmp = bswap(tmp); + tmp = utils::Bswap(tmp); return tmp; } else { DLOG(WARNING) << "[ReadTypeSize] Received invalid marker " diff --git a/src/communication/bolt/v1/encoder/primitive_encoder.hpp b/src/communication/bolt/v1/encoder/primitive_encoder.hpp index 2e9f129c7..329c139b0 100644 --- a/src/communication/bolt/v1/encoder/primitive_encoder.hpp +++ b/src/communication/bolt/v1/encoder/primitive_encoder.hpp @@ -20,7 +20,7 @@ namespace communication::bolt { template class PrimitiveEncoder { public: - PrimitiveEncoder(Buffer &buffer) : buffer_(buffer) {} + explicit PrimitiveEncoder(Buffer &buffer) : buffer_(buffer) {} void WriteRAW(const uint8_t *data, uint64_t len) { buffer_.Write(data, len); } @@ -32,7 +32,7 @@ class PrimitiveEncoder { template void WriteValue(T value) { - value = bswap(value); + value = utils::Bswap(value); WriteRAW(reinterpret_cast(&value), sizeof(value)); } diff --git a/src/data_structures/concurrent/concurrent_map.hpp b/src/data_structures/concurrent/concurrent_map.hpp index db7084124..fc9b21834 100644 --- a/src/data_structures/concurrent/concurrent_map.hpp +++ b/src/data_structures/concurrent/concurrent_map.hpp @@ -11,9 +11,9 @@ template class ConcurrentMap { /// At item in the concurrent map. A pair of that compares on /// the first value (key). Comparable to another Item, or only to the TKey. - class Item : public TotalOrdering, - public TotalOrdering, - public TotalOrdering, + class Item : public utils::TotalOrdering, + public utils::TotalOrdering, + public utils::TotalOrdering, public std::pair { public: using std::pair::pair; diff --git a/src/data_structures/concurrent/skiplist.hpp b/src/data_structures/concurrent/skiplist.hpp index ffa59b609..f4609090a 100644 --- a/src/data_structures/concurrent/skiplist.hpp +++ b/src/data_structures/concurrent/skiplist.hpp @@ -19,7 +19,7 @@ * computes the height for the new node from the interval [1...H] * with p(k) = (1/2)^k for all k from the interval */ -static thread_local FastBinomial<> rnd; +static thread_local utils::random::FastBinomial<> rnd; /** @brief Concurrent lock-based skiplist with fine grained locking * @@ -230,7 +230,7 @@ class SkipList : private Lockable { return node; } - Placeholder data; + utils::Placeholder data; /** * this creates an array of the size zero. we can't put any sensible @@ -245,7 +245,7 @@ class SkipList : private Lockable { public: template - class IteratorBase : public Crtp { + class IteratorBase : public utils::Crtp { protected: explicit IteratorBase(Node *node) : node(node) {} @@ -344,7 +344,7 @@ class SkipList : private Lockable { @todo Research possible better and faster more optimized traversals. */ - class ReverseIterator : public Crtp { + class ReverseIterator : public utils::Crtp { friend class SkipList; explicit ReverseIterator(Node *node) : node_(node) {} diff --git a/src/data_structures/concurrent/skiplist_gc.hpp b/src/data_structures/concurrent/skiplist_gc.hpp index f6c547d21..f72f063d6 100644 --- a/src/data_structures/concurrent/skiplist_gc.hpp +++ b/src/data_structures/concurrent/skiplist_gc.hpp @@ -160,9 +160,9 @@ class SkipListGC { /// Constructs executor depending on flag - has to be done this way because of /// C++14 auto ConstructExecutor() { - std::unique_ptr executor; + std::unique_ptr executor; if (FLAGS_skiplist_gc_interval != -1) { - executor = std::make_unique( + executor = std::make_unique( std::chrono::seconds(FLAGS_skiplist_gc_interval)); } return executor; diff --git a/src/database/graph_db.cpp b/src/database/graph_db.cpp index 479f5b7be..324dfbca2 100644 --- a/src/database/graph_db.cpp +++ b/src/database/graph_db.cpp @@ -443,7 +443,7 @@ MasterBase::MasterBase(std::unique_ptr impl) : PublicBase(std::move(impl)) { if (impl_->config_.durability_enabled) { impl_->wal().Enable(); - snapshot_creator_ = std::make_unique(); + snapshot_creator_ = std::make_unique(); snapshot_creator_->Run( "Snapshot", std::chrono::seconds(impl_->config_.snapshot_cycle_sec), [this] { diff --git a/src/database/graph_db.hpp b/src/database/graph_db.hpp index 2fd1d45a0..ac1704089 100644 --- a/src/database/graph_db.hpp +++ b/src/database/graph_db.hpp @@ -171,7 +171,7 @@ class PublicBase : public GraphDb { private: /** When this is false, no new transactions should be created. */ std::atomic is_accepting_transactions_{true}; - Scheduler transaction_killer_; + utils::Scheduler transaction_killer_; }; } // namespace impl @@ -181,7 +181,7 @@ class MasterBase : public impl::PublicBase { ~MasterBase(); private: - std::unique_ptr snapshot_creator_; + std::unique_ptr snapshot_creator_; }; class SingleNode : public MasterBase { diff --git a/src/database/indexes/key_index.hpp b/src/database/indexes/key_index.hpp index 0819db5ee..b0da1927b 100644 --- a/src/database/indexes/key_index.hpp +++ b/src/database/indexes/key_index.hpp @@ -104,7 +104,7 @@ class KeyIndex { /** * @brief - Contains vlist and record pointers. */ - class IndexEntry : public TotalOrdering { + class IndexEntry : public utils::TotalOrdering { public: IndexEntry(const IndexEntry &entry, const TRecord *const new_record) : IndexEntry(entry.vlist_, new_record) {} diff --git a/src/database/indexes/label_property_index.hpp b/src/database/indexes/label_property_index.hpp index 6412b9121..680d021bd 100644 --- a/src/database/indexes/label_property_index.hpp +++ b/src/database/indexes/label_property_index.hpp @@ -34,7 +34,7 @@ class LabelPropertyIndex { /** * @brief - Contain Label + property, to be used as an index key. */ - class Key : public TotalOrdering { + class Key : public utils::TotalOrdering { public: const storage::Label label_; const storage::Property property_; @@ -381,7 +381,7 @@ class LabelPropertyIndex { * @brief - Contains value, vlist and vertex record to distinguish between * index entries. */ - class IndexEntry : public TotalOrdering { + class IndexEntry : public utils::TotalOrdering { public: IndexEntry(const IndexEntry &entry, const Vertex *new_record) : IndexEntry(entry.value_, entry.vlist_, new_record) {} diff --git a/src/database/storage_gc.hpp b/src/database/storage_gc.hpp index 1fc697514..241849224 100644 --- a/src/database/storage_gc.hpp +++ b/src/database/storage_gc.hpp @@ -141,7 +141,7 @@ class StorageGc { } tx::Engine &tx_engine_; - Scheduler scheduler_; + utils::Scheduler scheduler_; private: Storage &storage_; @@ -150,7 +150,6 @@ class StorageGc { // History of ranges // that gc operated on at some previous time - used to clear commit log - std::queue> - gc_txid_ranges_; + std::queue> gc_txid_ranges_; }; } // namespace database diff --git a/src/distributed/durability_rpc_clients.cpp b/src/distributed/durability_rpc_clients.cpp index ba085edc0..528650db2 100644 --- a/src/distributed/durability_rpc_clients.cpp +++ b/src/distributed/durability_rpc_clients.cpp @@ -5,9 +5,8 @@ #include "utils/future.hpp" namespace distributed { -utils::Future DurabilityRpcClients::MakeSnapshot( - tx::TransactionId tx) { - return std::async(std::launch::async, [this, tx] { +utils::Future DurabilityRpcClients::MakeSnapshot(tx::TransactionId tx) { + return utils::make_future(std::async(std::launch::async, [this, tx] { auto futures = clients_.ExecuteOnWorkers( 0, [tx](communication::rpc::ClientPool &client_pool) { auto res = client_pool.Call(tx); @@ -21,6 +20,6 @@ utils::Future DurabilityRpcClients::MakeSnapshot( } return created; - }); + })); } } // namespace distributed diff --git a/src/distributed/transactional_cache_cleaner.hpp b/src/distributed/transactional_cache_cleaner.hpp index 3e1faebba..4644023a1 100644 --- a/src/distributed/transactional_cache_cleaner.hpp +++ b/src/distributed/transactional_cache_cleaner.hpp @@ -54,9 +54,8 @@ class TransactionalCacheCleaner { } tx::Engine &tx_engine_; - std::vector> - functions_; - Scheduler cache_clearing_scheduler_; + std::vector> functions_; + utils::Scheduler cache_clearing_scheduler_; }; /// Registers a RPC server that listens for `WaitOnTransactionEnd` requests diff --git a/src/durability/hashed_file_reader.hpp b/src/durability/hashed_file_reader.hpp index d1b00ad50..9cc03cd50 100644 --- a/src/durability/hashed_file_reader.hpp +++ b/src/durability/hashed_file_reader.hpp @@ -51,7 +51,7 @@ class HashedFileReader { if (!Read(reinterpret_cast(&val), sizeof(TValue), hash)) return false; // TODO: must be platform specific in the future - val = bswap(val); + val = utils::Bswap(val); return true; } diff --git a/src/durability/hashed_file_writer.hpp b/src/durability/hashed_file_writer.hpp index 93f988c45..58d8eadea 100644 --- a/src/durability/hashed_file_writer.hpp +++ b/src/durability/hashed_file_writer.hpp @@ -54,7 +54,7 @@ class HashedFileWriter { */ template void WriteValue(const TValue &val, bool hash = true) { - TValue val_bswapped = bswap(val); + TValue val_bswapped = utils::Bswap(val); Write(reinterpret_cast(&val_bswapped), sizeof(TValue), hash); } diff --git a/src/durability/paths.cpp b/src/durability/paths.cpp index bf61cd350..93f29d8c8 100644 --- a/src/durability/paths.cpp +++ b/src/durability/paths.cpp @@ -7,8 +7,8 @@ #include "glog/logging.h" #include "transactions/type.hpp" -#include "utils/datetime/timestamp.hpp" #include "utils/string.hpp" +#include "utils/timestamp.hpp" namespace durability { namespace fs = std::experimental::filesystem; @@ -66,7 +66,7 @@ std::experimental::optional TransactionIdFromWalFilename( fs::path MakeSnapshotPath(const fs::path &durability_dir, const int worker_id, tx::TransactionId tx_id) { std::string date_str = - Timestamp(Timestamp::Now()) + utils::Timestamp(utils::Timestamp::Now()) .ToString("{:04d}_{:02d}_{:02d}__{:02d}_{:02d}_{:02d}_{:05d}"); auto file_name = date_str + "_worker_" + std::to_string(worker_id) + "_tx_" + std::to_string(tx_id); @@ -79,7 +79,7 @@ fs::path MakeSnapshotPath(const fs::path &durability_dir, const int worker_id, fs::path WalFilenameForTransactionId( const std::experimental::filesystem::path &wal_dir, int worker_id, std::experimental::optional tx_id) { - auto file_name = Timestamp::Now().ToIso8601(); + auto file_name = utils::Timestamp::Now().ToIso8601(); if (tx_id) { file_name += "__max_transaction_" + std::to_string(*tx_id); } else { diff --git a/src/durability/snapshooter.cpp b/src/durability/snapshooter.cpp index c6233bf4a..74d50af54 100644 --- a/src/durability/snapshooter.cpp +++ b/src/durability/snapshooter.cpp @@ -9,7 +9,6 @@ #include "durability/paths.hpp" #include "durability/snapshot_encoder.hpp" #include "durability/version.hpp" -#include "utils/datetime/timestamp.hpp" namespace fs = std::experimental::filesystem; diff --git a/src/durability/wal.hpp b/src/durability/wal.hpp index 1bdd1afb1..4dabfdfe4 100644 --- a/src/durability/wal.hpp +++ b/src/durability/wal.hpp @@ -81,7 +81,7 @@ class WriteAheadLog { }; RingBuffer deltas_; - Scheduler scheduler_; + utils::Scheduler scheduler_; WalFile wal_file_; // Used for disabling the WAL during DB recovery. bool enabled_{false}; diff --git a/src/memgraph_bolt.cpp b/src/memgraph_bolt.cpp index dc4c36ef4..9fd03af44 100644 --- a/src/memgraph_bolt.cpp +++ b/src/memgraph_bolt.cpp @@ -152,7 +152,7 @@ int main(int argc, char **argv) { google::SetLogSymlink(google::INFO, FLAGS_log_link_basename.c_str()); // Unhandled exception handler init. - std::set_terminate(&terminate_handler); + std::set_terminate(&utils::TerminateHandler); std::string stats_prefix; if (FLAGS_master) { @@ -166,10 +166,10 @@ int main(int argc, char **argv) { utils::OnScopeExit stop_stats([] { stats::StopStatsLogging(); }); // Start memory warning logger. - Scheduler mem_log_scheduler; + utils::Scheduler mem_log_scheduler; if (FLAGS_memory_warning_threshold > 0) { mem_log_scheduler.Run("Memory warning", std::chrono::seconds(3), [] { - auto free_ram_mb = utils::AvailableMem() / 1024; + auto free_ram_mb = utils::sysinfo::AvailableMem() / 1024; if (free_ram_mb < FLAGS_memory_warning_threshold) LOG(WARNING) << "Running out of available RAM, only " << free_ram_mb << " MB left."; diff --git a/src/query/plan/operator.cpp b/src/query/plan/operator.cpp index d92b1264c..b25894277 100644 --- a/src/query/plan/operator.cpp +++ b/src/query/plan/operator.cpp @@ -414,32 +414,32 @@ std::unique_ptr ScanAllByLabelPropertyRange::MakeCursor( -> std::experimental::optional { - ExpressionEvaluator evaluator(frame, context.parameters_, - context.symbol_table_, db, graph_view_); - auto convert = [&evaluator](const auto &bound) - -> std::experimental::optional> { - if (!bound) return std::experimental::nullopt; - auto value = bound->value()->Accept(evaluator); - try { + ExpressionEvaluator evaluator(frame, context.parameters_, + context.symbol_table_, db, graph_view_); + auto convert = [&evaluator](const auto &bound) + -> std::experimental::optional> { + if (!bound) return std::experimental::nullopt; + auto value = bound->value()->Accept(evaluator); + try { + return std::experimental::make_optional( + utils::Bound(value, bound->type())); + } catch (const TypedValueException &) { + throw QueryRuntimeException( + "'{}' cannot be used as a property value.", value.type()); + } + }; + auto maybe_lower = convert(lower_bound()); + auto maybe_upper = convert(upper_bound()); + // If any bound is null, then the comparison would result in nulls. This + // is treated as not satisfying the filter, so return no vertices. + if (maybe_lower && maybe_lower->value().IsNull()) + return std::experimental::nullopt; + if (maybe_upper && maybe_upper->value().IsNull()) + return std::experimental::nullopt; return std::experimental::make_optional( - utils::Bound(value, bound->type())); - } catch (const TypedValueException &) { - throw QueryRuntimeException("'{}' cannot be used as a property value.", - value.type()); - } - }; - auto maybe_lower = convert(lower_bound()); - auto maybe_upper = convert(upper_bound()); - // If any bound is null, then the comparison would result in nulls. This is - // treated as not satisfying the filter, so return no vertices. - if (maybe_lower && maybe_lower->value().IsNull()) - return std::experimental::nullopt; - if (maybe_upper && maybe_upper->value().IsNull()) - return std::experimental::nullopt; - return std::experimental::make_optional( - db.Vertices(label_, property_, maybe_lower, maybe_upper, - graph_view_ == GraphView::NEW)); - }; + db.Vertices(label_, property_, maybe_lower, maybe_upper, + graph_view_ == GraphView::NEW)); + }; return std::make_unique>( output_symbol_, input_->MakeCursor(db), std::move(vertices), db); } @@ -462,18 +462,18 @@ std::unique_ptr ScanAllByLabelPropertyValue::MakeCursor( auto vertices = [this, &db](Frame &frame, Context &context) -> std::experimental::optional { - ExpressionEvaluator evaluator(frame, context.parameters_, - context.symbol_table_, db, graph_view_); - auto value = expression_->Accept(evaluator); - if (value.IsNull()) return std::experimental::nullopt; - try { - return std::experimental::make_optional( - db.Vertices(label_, property_, value, graph_view_ == GraphView::NEW)); - } catch (const TypedValueException &) { - throw QueryRuntimeException("'{}' cannot be used as a property value.", - value.type()); - } - }; + ExpressionEvaluator evaluator(frame, context.parameters_, + context.symbol_table_, db, graph_view_); + auto value = expression_->Accept(evaluator); + if (value.IsNull()) return std::experimental::nullopt; + try { + return std::experimental::make_optional(db.Vertices( + label_, property_, value, graph_view_ == GraphView::NEW)); + } catch (const TypedValueException &) { + throw QueryRuntimeException( + "'{}' cannot be used as a property value.", value.type()); + } + }; return std::make_unique>( output_symbol_, input_->MakeCursor(db), std::move(vertices), db); } @@ -551,7 +551,7 @@ bool Expand::ExpandCursor::Pull(Frame &frame, Context &context) { LOG(FATAL) << "Must indicate exact expansion direction here"; }); future_expands_.emplace_back( - FutureExpand{std::move(edge_to), frame.elems()}); + FutureExpand{utils::make_future(std::move(edge_to)), frame.elems()}); }; auto find_ready_future = [this]() { @@ -1402,7 +1402,7 @@ class ExpandWeightedShortestPathCursor : public query::plan::Cursor { struct WspStateHash { size_t operator()(const std::pair &key) const { - return HashCombine{}(key.first, key.second); + return utils::HashCombine{}(key.first, key.second); } }; diff --git a/src/query/plan/operator.hpp b/src/query/plan/operator.hpp index 6f51a795a..12bb7cae9 100644 --- a/src/query/plan/operator.hpp +++ b/src/query/plan/operator.hpp @@ -1812,7 +1812,8 @@ class Aggregate : public LogicalOperator { std::unordered_map< std::vector, AggregationValue, // use FNV collection hashing specialized for a vector of TypedValues - FnvCollection, TypedValue, TypedValue::Hash>, + utils::FnvCollection, TypedValue, + TypedValue::Hash>, // custom equality TypedValueVectorEqual> aggregation_; @@ -2352,7 +2353,8 @@ class Distinct : public LogicalOperator { std::unordered_set< std::vector, // use FNV collection hashing specialized for a vector of TypedValues - FnvCollection, TypedValue, TypedValue::Hash>, + utils::FnvCollection, TypedValue, + TypedValue::Hash>, TypedValueVectorEqual> seen_rows_; }; diff --git a/src/query/plan/vertex_count_cache.hpp b/src/query/plan/vertex_count_cache.hpp index 60f335d94..dd698f3b3 100644 --- a/src/query/plan/vertex_count_cache.hpp +++ b/src/query/plan/vertex_count_cache.hpp @@ -70,8 +70,8 @@ class VertexCountCache { struct LabelPropertyHash { size_t operator()(const LabelPropertyKey &key) const { - return HashCombine{}(key.first, - key.second); + return utils::HashCombine{}( + key.first, key.second); } }; @@ -88,7 +88,7 @@ class VertexCountCache { if (maybe_lower) lower = maybe_lower->value(); if (maybe_upper) upper = maybe_upper->value(); query::TypedValue::Hash hash; - return HashCombine{}(hash(lower), hash(upper)); + return utils::HashCombine{}(hash(lower), hash(upper)); } }; diff --git a/src/query/typed_value.cpp b/src/query/typed_value.cpp index 886dedc81..8d7e90f5e 100644 --- a/src/query/typed_value.cpp +++ b/src/query/typed_value.cpp @@ -671,7 +671,7 @@ size_t TypedValue::Hash::operator()(const TypedValue &value) const { case TypedValue::Type::String: return std::hash{}(value.Value()); case TypedValue::Type::List: { - return FnvCollection, TypedValue, Hash>{}( + return utils::FnvCollection, TypedValue, Hash>{}( value.Value>()); } case TypedValue::Type::Map: { @@ -687,9 +687,10 @@ size_t TypedValue::Hash::operator()(const TypedValue &value) const { case TypedValue::Type::Edge: return value.Value().gid(); case TypedValue::Type::Path: - return FnvCollection, VertexAccessor>{}( + return utils::FnvCollection, + VertexAccessor>{}( value.ValuePath().vertices()) ^ - FnvCollection, EdgeAccessor>{}( + utils::FnvCollection, EdgeAccessor>{}( value.ValuePath().edges()); } LOG(FATAL) << "Unhandled TypedValue.type() in hash function"; diff --git a/src/query/typed_value.hpp b/src/query/typed_value.hpp index 15ea87078..0eb21161e 100644 --- a/src/query/typed_value.hpp +++ b/src/query/typed_value.hpp @@ -25,7 +25,8 @@ namespace query { * Values can be of a number of predefined types that are enumerated in * TypedValue::Type. Each such type corresponds to exactly one C++ type. */ -class TypedValue : public TotalOrdering { +class TypedValue + : public utils::TotalOrdering { public: /** Custom TypedValue equality function that returns a bool * (as opposed to returning TypedValue as the default equality does). @@ -152,7 +153,7 @@ class TypedValue : public TotalOrdering { template const T &Value() const; - // TODO consider adding getters for primitives by value (and not by ref) +// TODO consider adding getters for primitives by value (and not by ref) #define DECLARE_VALUE_AND_TYPE_GETTERS(type_param, field) \ /** Gets the value of type field. Throws if value is not field*/ \ diff --git a/src/stats/stats_rpc_messages.hpp b/src/stats/stats_rpc_messages.hpp index 88ee578b3..b5106097c 100644 --- a/src/stats/stats_rpc_messages.hpp +++ b/src/stats/stats_rpc_messages.hpp @@ -7,7 +7,7 @@ #include "boost/serialization/vector.hpp" #include "communication/rpc/messages.hpp" -#include "utils/datetime/timestamp.hpp" +#include "utils/timestamp.hpp" namespace stats { @@ -18,7 +18,7 @@ struct StatsReq : public communication::rpc::Message { : metric_path(metric_path), tags(tags), value(value), - timestamp(Timestamp::Now().SecSinceTheEpoch()) {} + timestamp(utils::Timestamp::Now().SecSinceTheEpoch()) {} std::string metric_path; std::vector> tags; @@ -39,7 +39,7 @@ RPC_NO_MEMBER_MESSAGE(StatsRes); struct BatchStatsReq : public communication::rpc::Message { BatchStatsReq() {} - BatchStatsReq(std::vector requests) : requests(requests) {} + explicit BatchStatsReq(std::vector requests) : requests(requests) {} std::vector requests; diff --git a/src/storage/record_accessor.hpp b/src/storage/record_accessor.hpp index 5b298ab16..017074db4 100644 --- a/src/storage/record_accessor.hpp +++ b/src/storage/record_accessor.hpp @@ -25,7 +25,7 @@ struct StateDelta; * @tparam TRecord Type of record (MVCC Version) of the accessor. */ template -class RecordAccessor : public TotalOrdering> { +class RecordAccessor : public utils::TotalOrdering> { protected: using AddressT = storage::Address>; diff --git a/src/storage/types.hpp b/src/storage/types.hpp index 912e0842f..f97f93d09 100644 --- a/src/storage/types.hpp +++ b/src/storage/types.hpp @@ -10,7 +10,7 @@ namespace storage { template -class Common : public TotalOrdering { +class Common : public utils::TotalOrdering { public: using StorageT = uint16_t; diff --git a/src/utils/bswap.hpp b/src/utils/bswap.hpp index b26eb9528..2efe4e4da 100644 --- a/src/utils/bswap.hpp +++ b/src/utils/bswap.hpp @@ -5,35 +5,39 @@ #include +namespace utils { + template -inline T bswap(T value); +inline T Bswap(T value); template <> -inline int16_t bswap(int16_t value) { +inline int16_t Bswap(int16_t value) { return __bswap_16(value); } template <> -inline uint16_t bswap(uint16_t value) { +inline uint16_t Bswap(uint16_t value) { return __bswap_16(value); } template <> -inline int32_t bswap(int32_t value) { +inline int32_t Bswap(int32_t value) { return __bswap_32(value); } template <> -inline uint32_t bswap(uint32_t value) { +inline uint32_t Bswap(uint32_t value) { return __bswap_32(value); } template <> -inline int64_t bswap(int64_t value) { +inline int64_t Bswap(int64_t value) { return __bswap_64(value); } template <> -inline uint64_t bswap(uint64_t value) { +inline uint64_t Bswap(uint64_t value) { return __bswap_64(value); } + +} // namespace utils diff --git a/src/utils/crtp.hpp b/src/utils/crtp.hpp index dd60907ad..cd4cc2bb8 100644 --- a/src/utils/crtp.hpp +++ b/src/utils/crtp.hpp @@ -3,9 +3,13 @@ // a helper class for implementing static casting to a derived class using the // curiously recurring template pattern +namespace utils { + template struct Crtp { - Derived& derived() { return *static_cast(this); } + Derived &derived() { return *static_cast(this); } - const Derived& derived() const { return *static_cast(this); } + const Derived &derived() const { return *static_cast(this); } }; + +} // namespace utils diff --git a/src/utils/datetime/datetime.hpp b/src/utils/datetime/datetime.hpp deleted file mode 100644 index 7ef8c1616..000000000 --- a/src/utils/datetime/datetime.hpp +++ /dev/null @@ -1,27 +0,0 @@ -#pragma once - -#include "utils/datetime/datetime_error.hpp" - -class Datetime { - public: - Datetime() {} - - Datetime(std::time_t time_point) { - auto result = gmtime_r(&time_point, &time); - - if (result == nullptr) - throw DatetimeError("Unable to construct from {}", time_point); - } - - Datetime(const Datetime&) = default; - Datetime(Datetime&&) = default; - - static Datetime now() { - timespec - - return Datetime(); - } - - private: - std::tm time; -}; diff --git a/src/utils/datetime/datetime_error.hpp b/src/utils/datetime/datetime_error.hpp deleted file mode 100644 index 1d6a7f450..000000000 --- a/src/utils/datetime/datetime_error.hpp +++ /dev/null @@ -1,8 +0,0 @@ -#pragma once - -#include "utils/exceptions.hpp" - -class DatetimeError : public utils::StacktraceException { - public: - using utils::StacktraceException::StacktraceException; -}; diff --git a/src/utils/executor.hpp b/src/utils/executor.hpp index cc7d55443..baa4da20e 100644 --- a/src/utils/executor.hpp +++ b/src/utils/executor.hpp @@ -6,6 +6,8 @@ #include "utils/scheduler.hpp" +namespace utils { + /** * @brief - Provides execution of jobs in job queue on one thread with 'pause' * time between two consecutives starts. @@ -93,3 +95,5 @@ class Executor { Scheduler scheduler_; std::vector>> id_job_pairs_; }; + +} // namespace utils diff --git a/src/utils/fswatcher.hpp b/src/utils/fswatcher.hpp index 3b03f77eb..8423fe715 100644 --- a/src/utils/fswatcher.hpp +++ b/src/utils/fswatcher.hpp @@ -29,8 +29,8 @@ namespace fs = std::experimental::filesystem; #include "utils/likely.hpp" #include "utils/underlying_cast.hpp" -namespace utils { -namespace linux_os { +namespace utils::linux_os { + void set_non_blocking(int fd) { auto flags = fcntl(fd, F_GETFL, 0); @@ -44,7 +44,6 @@ void set_non_blocking(int fd) { if (UNLIKELY(status == -1)) throw BasicException("Can't set NON_BLOCK flag to file descriptor"); } -} // namespace linux_os /** * Goes from first to last item in a container, if an element satisfying the @@ -194,7 +193,8 @@ class FSWatcher { /** * Initialize underlying notification system. */ - FSWatcher(ms check_interval = ms(100)) : check_interval_(check_interval) { + explicit FSWatcher(ms check_interval = ms(100)) + : check_interval_(check_interval) { DLOG(INFO) << fmt::format("Inotify header length: {}", IN_HEADER_SIZE); DLOG(INFO) << fmt::format("Inotify buffer length: {}", IN_BUFF_LEN); inotify_fd_ = inotify_init(); @@ -469,4 +469,5 @@ class FSWatcher { */ char *buffer_[IN_BUFF_LEN]; }; -} // namespace utils + +} // namespace utils::linux_os diff --git a/src/utils/future.hpp b/src/utils/future.hpp index 03105ba8b..c8075491a 100644 --- a/src/utils/future.hpp +++ b/src/utils/future.hpp @@ -11,7 +11,7 @@ template class Future { public: Future() {} - Future(std::future future) : future_(std::move(future)) {} + explicit Future(std::future future) : future_(std::move(future)) {} Future(const Future &) = delete; Future(Future &&) = default; @@ -42,4 +42,5 @@ template Future make_future(std::future future) { return Future(std::move(future)); } -} + +} // namespace utils diff --git a/src/utils/hashing/fnv.hpp b/src/utils/hashing/fnv.hpp index 39bb60117..ce36ebd02 100644 --- a/src/utils/hashing/fnv.hpp +++ b/src/utils/hashing/fnv.hpp @@ -32,6 +32,8 @@ using HashType = uint32_t; #endif } +namespace utils { + /** * Does FNV-like hashing on a collection. Not truly FNV * because it operates on 8-bit elements, while this @@ -83,3 +85,5 @@ struct HashCombine { return ret; } }; + +} // namespace utils diff --git a/src/utils/log_destructor.hpp b/src/utils/log_destructor.hpp deleted file mode 100644 index 8a7c69eb3..000000000 --- a/src/utils/log_destructor.hpp +++ /dev/null @@ -1,13 +0,0 @@ -#pragma once - -#include - -#include "utils/stacktrace.hpp" - -class LogDestructor { - protected: - ~LogDestructor() { - Stacktrace st; - DLOG(INFO) << st.dump(); - } -}; diff --git a/src/utils/memory_literals.hpp b/src/utils/memory_literals.hpp deleted file mode 100644 index 5d802ec6c..000000000 --- a/src/utils/memory_literals.hpp +++ /dev/null @@ -1,20 +0,0 @@ -#pragma once - -#include - -namespace memory { -namespace literals { - -constexpr unsigned long long operator"" _GB(unsigned long long gb) { - return 1024 * 1024 * 1024 * gb; -} - -constexpr unsigned long long operator"" _MB(unsigned long long mb) { - return 1024 * 1024 * mb; -} - -constexpr unsigned long long operator"" _kB(unsigned long long kb) { - return 1024 * kb; -} -} -} diff --git a/src/utils/network.hpp b/src/utils/network.hpp index 5346713ad..7d41dcdf7 100644 --- a/src/utils/network.hpp +++ b/src/utils/network.hpp @@ -15,4 +15,5 @@ std::experimental::optional GetHostname(); // Try to establish a connection to a remote host bool CanEstablishConnection(const io::network::Endpoint &endpoint); -}; // namespace utils + +} // namespace utils diff --git a/src/utils/on_scope_exit.hpp b/src/utils/on_scope_exit.hpp index 10584bf39..372241596 100644 --- a/src/utils/on_scope_exit.hpp +++ b/src/utils/on_scope_exit.hpp @@ -32,4 +32,5 @@ class OnScopeExit { private: std::function function_; }; + } // namespace utils diff --git a/src/utils/option.hpp b/src/utils/option.hpp deleted file mode 100644 index bb6bb051f..000000000 --- a/src/utils/option.hpp +++ /dev/null @@ -1,197 +0,0 @@ -#pragma once - -#include -#include "glog/logging.h" - -#include -#include - -// Optional object storage. It maybe has and maybe -// dosent have objet of type T. -template -class Option { - public: - Option() { std::memset(data._M_addr(), 0, sizeof(T)); } - - Option(T const &item) { - new (data._M_addr()) T(item); - initialized = true; - } - - Option(T &&item) { - new (data._M_addr()) T(std::move(item)); - initialized = true; - } - - Option(const Option &other) { - if (other.initialized) { - new (data._M_addr()) T(other.get()); - initialized = true; - } else { - std::memset(data._M_addr(), 0, sizeof(T)); - } - } - - // Containers from std which have strong exception - // guarantees wont use move constructors and operators - // wihtout noexcept. "Optimized C++,2016 , Kurt - // Guntheroth, page: 142, title: Moving instances into - // std::vector" - Option(Option &&other) noexcept { - if (other.initialized) { - new (data._M_addr()) T(std::move(other.get())); - other.initialized = false; - initialized = true; - } else { - std::memset(data._M_addr(), 0, sizeof(T)); - } - } - - ~Option() { - if (initialized) { - get().~T(); - initialized = false; - } - } - - Option &operator=(const Option &other) { - if (initialized) { - get().~T(); - initialized = false; - } - if (other.initialized) { - new (data._M_addr()) T(other.get()); - initialized = true; - } - - return *this; - } - - Option &operator=(Option &&other) { - if (initialized) { - get().~T(); - initialized = false; - } - - if (other.initialized) { - new (data._M_addr()) T(std::move(other.get())); - other.initialized = false; - initialized = true; - } - - return *this; - } - - // True if object i present. - bool is_present() const { return initialized; } - - T &get() noexcept { - DCHECK(initialized) << "Not initialized."; - return *data._M_ptr(); - } - - T &get_or(T &other) { - if (is_present()) { - return get(); - } else { - return other; - } - } - - // Returns ref to object if present else other. - T const &get_or(T const &other) const { - if (is_present()) { - return get(); - } else { - return other; - } - } - - const T &get() const noexcept { - DCHECK(initialized) << "Not initialized."; - return *data._M_ptr(); - } - - template - Option map() { - if (is_present()) { - return Option(U(take())); - } else { - return Option(); - } - } - - template - Option map(F f) { - if (is_present()) { - return Option(f(take())); - } else { - return Option(); - } - } - - template - U map_or(F f, U &&def) { - if (is_present()) { - return f(take()); - } else { - return std::move(def); - } - } - - template - U call_or(F f, U &&def) { - if (is_present()) { - return f(get()); - } else { - return std::move(def); - } - } - - T take() { - DCHECK(initialized) << "Not initialized."; - initialized = false; - return std::move(*data._M_ptr()); - } - - // Takes if it exists otherwise returns given value. - T take_or(T &&value) { - if (initialized) { - initialized = false; - return std::move(*data._M_ptr()); - } else { - return std::move(value); - } - } - - explicit operator bool() const { return initialized; } - - private: - // Aligned buffer is here to ensure aligment for - // data of type T. It isn't applicable to just put T - // field because the field has to be able to be - // uninitialized to fulfill the semantics of Option class. - __gnu_cxx::__aligned_buffer data; - bool initialized = false; -}; - -template -auto make_option() { - return Option(); -} - -template -auto make_option(T &&data) { - return Option(std::move(data)); -} - -template -auto make_option_const(const T &&data) { - return Option(std::move(data)); -} - -// HELPER FUNCTIONS -template -bool option_fill(Option &o) { - return o.is_present() && o.get().fill(); -} diff --git a/src/utils/placeholder.hpp b/src/utils/placeholder.hpp index b996840d0..ee5ce7cb4 100644 --- a/src/utils/placeholder.hpp +++ b/src/utils/placeholder.hpp @@ -6,6 +6,8 @@ #include +namespace utils { + /** * @class Placeholder * @@ -91,3 +93,5 @@ class Placeholder { __gnu_cxx::__aligned_buffer data; bool initialized = false; }; + +} // namespace utils diff --git a/src/utils/random/fast_binomial.hpp b/src/utils/random/fast_binomial.hpp index 079395690..4c23644e2 100644 --- a/src/utils/random/fast_binomial.hpp +++ b/src/utils/random/fast_binomial.hpp @@ -3,6 +3,8 @@ #include "utils/likely.hpp" #include "utils/random/xorshift128plus.hpp" +namespace utils::random { + template class FastBinomial { // fast binomial draws coin tosses from a single generated random number @@ -55,3 +57,5 @@ class FastBinomial { uint64_t mask(const int n) { return (1ULL << n) - 1; } R random; }; + +} // namespace utils::random diff --git a/src/utils/random/random_generator.hpp b/src/utils/random/random_generator.hpp index dd3432330..a00b9241c 100644 --- a/src/utils/random/random_generator.hpp +++ b/src/utils/random/random_generator.hpp @@ -2,11 +2,7 @@ #include #include -// namespace ::utils -namespace utils { - -// namespace utils::random -namespace random { +namespace utils::random { template class RandomGenerator { @@ -28,7 +24,7 @@ class StringGenerator int size_; public: - StringGenerator(int size) + explicit StringGenerator(int size) : RandomGenerator(std::uniform_int_distribution(32, 126)), size_(size) {} @@ -82,5 +78,4 @@ auto generate_set(RandomGenerator &gen, int size) { return elements; } -}; // namespace utils::random -}; // namespace ::utils +} // namespace utils::random diff --git a/src/utils/random/xorshift128plus.hpp b/src/utils/random/xorshift128plus.hpp index bcc78f1ba..b869b43b7 100644 --- a/src/utils/random/xorshift128plus.hpp +++ b/src/utils/random/xorshift128plus.hpp @@ -3,6 +3,8 @@ #include #include +namespace utils::random { + /* Xorshift algorithm (plus variant) * * This is the fastest generator passing BigCrush without systematic failures, @@ -54,3 +56,5 @@ struct Xorshift128plus { return s; } }; + +} // namespace utils::random diff --git a/src/utils/scheduler.hpp b/src/utils/scheduler.hpp index 362400804..90cbd4997 100644 --- a/src/utils/scheduler.hpp +++ b/src/utils/scheduler.hpp @@ -11,6 +11,8 @@ #include "utils/thread.hpp" +namespace utils { + /** * Class used to run scheduled function execution. */ @@ -99,3 +101,5 @@ class Scheduler { */ std::thread thread_; }; + +} // namespace utils diff --git a/src/utils/stacktrace.hpp b/src/utils/stacktrace.hpp index 5062913ba..515abe7d3 100644 --- a/src/utils/stacktrace.hpp +++ b/src/utils/stacktrace.hpp @@ -7,6 +7,8 @@ #include "utils/on_scope_exit.hpp" +namespace utils { + class Stacktrace { public: class Line { @@ -92,3 +94,5 @@ class Stacktrace { return {original, function, location}; } }; + +} // namespace utils diff --git a/src/utils/sysinfo/memory.hpp b/src/utils/sysinfo/memory.hpp index e7977691e..738c5154c 100644 --- a/src/utils/sysinfo/memory.hpp +++ b/src/utils/sysinfo/memory.hpp @@ -4,7 +4,7 @@ #include "glog/logging.h" -namespace utils { +namespace utils::sysinfo { /** * Gets the amount of available RAM in kilobytes. If the information is @@ -27,4 +27,5 @@ inline auto AvailableMem() { LOG(ERROR) << "Failed to read amount of available memory from /proc/meminfo"; return 0UL; } -} // namespace utils + +} // namespace utils::sysinfo diff --git a/src/utils/terminate_handler.hpp b/src/utils/terminate_handler.hpp index e818e61dd..5f61976c7 100644 --- a/src/utils/terminate_handler.hpp +++ b/src/utils/terminate_handler.hpp @@ -1,27 +1,30 @@ #pragma once -#include "utils/stacktrace.hpp" - #include #include -// TODO: log to local file or remote database -void stacktrace(std::ostream &stream) noexcept { - Stacktrace stacktrace; - stacktrace.dump(stream); -} +#include "utils/stacktrace.hpp" -// TODO: log to local file or remote database -void terminate_handler(std::ostream &stream) noexcept { +namespace utils { + +/** + * Dump stacktrace to the stream and abort the probram. For more details + * about the abort please take a look at + * http://en.cppreference.com/w/cpp/utility/program/abort. + */ +void TerminateHandler(std::ostream &stream) noexcept { if (auto exc = std::current_exception()) { try { std::rethrow_exception(exc); } catch (std::exception &ex) { stream << ex.what() << std::endl << std::endl; - stacktrace(stream); + utils::Stacktrace stacktrace; + stacktrace.dump(stream); } } std::abort(); } -void terminate_handler() noexcept { terminate_handler(std::cout); } +void TerminateHandler() noexcept { TerminateHandler(std::cout); } + +} // namespace utils diff --git a/src/utils/timer.hpp b/src/utils/timer.hpp index 165c2b9bf..65d8240ba 100644 --- a/src/utils/timer.hpp +++ b/src/utils/timer.hpp @@ -16,4 +16,5 @@ class Timer { std::chrono::time_point start_time_ = std::chrono::steady_clock::now(); }; -}; + +} // namespace utils diff --git a/src/utils/datetime/timestamp.hpp b/src/utils/timestamp.hpp similarity index 73% rename from src/utils/datetime/timestamp.hpp rename to src/utils/timestamp.hpp index 72283940c..5a355b737 100644 --- a/src/utils/datetime/timestamp.hpp +++ b/src/utils/timestamp.hpp @@ -7,9 +7,16 @@ #include -#include "utils/datetime/datetime_error.hpp" +#include "utils/exceptions.hpp" #include "utils/total_ordering.hpp" +namespace utils { + +class TimestampError : public StacktraceException { + public: + using StacktraceException::StacktraceException; +}; + class Timestamp : public TotalOrdering { public: Timestamp() : Timestamp(0, 0) {} @@ -18,11 +25,11 @@ class Timestamp : public TotalOrdering { auto result = gmtime_r(&time, &this->time); if (result == nullptr) - throw DatetimeError("Unable to construct from {}", time); + throw TimestampError("Unable to construct from {}", time); } - Timestamp(const Timestamp&) = default; - Timestamp(Timestamp&&) = default; + Timestamp(const Timestamp &) = default; + Timestamp(Timestamp &&) = default; static Timestamp Now() { timespec time; @@ -54,22 +61,22 @@ class Timestamp : public TotalOrdering { Subsec()); } - const std::string ToString(const std::string& format = fiso8601) const { + const std::string ToString(const std::string &format = fiso8601) const { return fmt::format(format, Year(), Month(), Day(), Hour(), Min(), Sec(), Subsec()); } - friend std::ostream& operator<<(std::ostream& stream, const Timestamp& ts) { + friend std::ostream &operator<<(std::ostream &stream, const Timestamp &ts) { return stream << ts.ToIso8601(); } operator std::string() const { return ToString(); } - constexpr friend bool operator==(const Timestamp& a, const Timestamp& b) { + constexpr friend bool operator==(const Timestamp &a, const Timestamp &b) { return a.unix_time == b.unix_time && a.nsec == b.nsec; } - constexpr friend bool operator<(const Timestamp& a, const Timestamp& b) { + constexpr friend bool operator<(const Timestamp &a, const Timestamp &b) { return a.unix_time < b.unix_time || (a.unix_time == b.unix_time && a.nsec < b.nsec); } @@ -84,3 +91,5 @@ class Timestamp : public TotalOrdering { static constexpr auto fiso8601 = "{:04d}-{:02d}-{:02d}T{:02d}:{:02d}:{:02d}.{:05d}Z"; }; + +} // namespace utils diff --git a/src/utils/total_ordering.hpp b/src/utils/total_ordering.hpp index b31136291..b71e054bf 100644 --- a/src/utils/total_ordering.hpp +++ b/src/utils/total_ordering.hpp @@ -1,5 +1,7 @@ #pragma once +namespace utils { + /** * Implements all the logical comparison operators based on '==' * and '<' operators. @@ -13,19 +15,19 @@ template struct TotalOrdering { virtual ~TotalOrdering() {} - friend constexpr TReturn operator!=(const TLhs& a, const TRhs& b) { + friend constexpr TReturn operator!=(const TLhs &a, const TRhs &b) { return !(a == b); } - friend constexpr TReturn operator<=(const TLhs& a, const TRhs& b) { + friend constexpr TReturn operator<=(const TLhs &a, const TRhs &b) { return a < b || a == b; } - friend constexpr TReturn operator>(const TLhs& a, const TRhs& b) { + friend constexpr TReturn operator>(const TLhs &a, const TRhs &b) { return !(a <= b); } - friend constexpr TReturn operator>=(const TLhs& a, const TRhs& b) { + friend constexpr TReturn operator>=(const TLhs &a, const TRhs &b) { return !(a < b); } }; @@ -34,35 +36,37 @@ template struct TotalOrderingWith { virtual ~TotalOrderingWith() {} - friend constexpr bool operator!=(const Derived& a, const T& b) { + friend constexpr bool operator!=(const Derived &a, const T &b) { return !(a == b); } - friend constexpr bool operator<=(const Derived& a, const T& b) { + friend constexpr bool operator<=(const Derived &a, const T &b) { return a < b || a == b; } - friend constexpr bool operator>(const Derived& a, const T& b) { + friend constexpr bool operator>(const Derived &a, const T &b) { return !(a <= b); } - friend constexpr bool operator>=(const Derived& a, const T& b) { + friend constexpr bool operator>=(const Derived &a, const T &b) { return !(a < b); } - friend constexpr bool operator!=(const T& a, const Derived& b) { + friend constexpr bool operator!=(const T &a, const Derived &b) { return !(a == b); } - friend constexpr bool operator<=(const T& a, const Derived& b) { + friend constexpr bool operator<=(const T &a, const Derived &b) { return a < b || a == b; } - friend constexpr bool operator>(const T& a, const Derived& b) { + friend constexpr bool operator>(const T &a, const Derived &b) { return !(a <= b); } - friend constexpr bool operator>=(const T& a, const Derived& b) { + friend constexpr bool operator>=(const T &a, const Derived &b) { return !(a < b); } }; + +} // namespace utils diff --git a/src/utils/type_discovery.hpp b/src/utils/type_discovery.hpp deleted file mode 100644 index cba671473..000000000 --- a/src/utils/type_discovery.hpp +++ /dev/null @@ -1,92 +0,0 @@ -#pragma once - -// USAGE: -// type_name(); -// current solution has been taken from -// http://stackoverflow.com/questions/81870/is-it-possible-to-print-a-variables-type-in-standard-c -// TODO: create more appropriate solution - -#include -#include -#include -#include - -#ifndef _MSC_VER -#if __cplusplus < 201103 -#define CONSTEXPR11_TN -#define CONSTEXPR14_TN -#define NOEXCEPT_TN -#elif __cplusplus < 201402 -#define CONSTEXPR11_TN constexpr -#define CONSTEXPR14_TN -#define NOEXCEPT_TN noexcept -#else -#define CONSTEXPR11_TN constexpr -#define CONSTEXPR14_TN constexpr -#define NOEXCEPT_TN noexcept -#endif -#else // _MSC_VER -#if _MSC_VER < 1900 -#define CONSTEXPR11_TN -#define CONSTEXPR14_TN -#define NOEXCEPT_TN -#elif _MSC_VER < 2000 -#define CONSTEXPR11_TN constexpr -#define CONSTEXPR14_TN -#define NOEXCEPT_TN noexcept -#else -#define CONSTEXPR11_TN constexpr -#define CONSTEXPR14_TN constexpr -#define NOEXCEPT_TN noexcept -#endif -#endif // _MSC_VER - -class static_string { - const char* const p_; - const std::size_t sz_; - - public: - typedef const char* const_iterator; - - template - CONSTEXPR11_TN static_string(const char (&a)[N]) NOEXCEPT_TN : p_(a), - sz_(N - 1) {} - - CONSTEXPR11_TN static_string(const char *p, std::size_t N) NOEXCEPT_TN - : p_(p), - sz_(N) {} - - CONSTEXPR11_TN const char* data() const NOEXCEPT_TN { return p_; } - CONSTEXPR11_TN std::size_t size() const NOEXCEPT_TN { return sz_; } - - CONSTEXPR11_TN const_iterator begin() const NOEXCEPT_TN { return p_; } - CONSTEXPR11_TN const_iterator end() const NOEXCEPT_TN { return p_ + sz_; } - - CONSTEXPR11_TN char operator[](std::size_t n) const { - return n < sz_ ? p_[n] : throw std::out_of_range("static_string"); - } - - std::string to_string() { return std::string(p_, sz_); } -}; - -inline std::ostream& operator<<(std::ostream& os, static_string const& s) { - return os.write(s.data(), s.size()); -} - -template -CONSTEXPR14_TN static_string type_name() { -#ifdef __clang__ - static_string p = __PRETTY_FUNCTION__; - return static_string(p.data() + 31, p.size() - 31 - 1); -#elif defined(__GNUC__) - static_string p = __PRETTY_FUNCTION__; -#if __cplusplus < 201402 - return static_string(p.data() + 36, p.size() - 36 - 1); -#else - return static_string(p.data() + 46, p.size() - 46 - 1); -#endif -#elif defined(_MSC_VER) - static_string p = __FUNCSIG__; - return static_string(p.data() + 38, p.size() - 38 - 7); -#endif -} diff --git a/src/utils/watchdog.cpp b/src/utils/watchdog.cpp index 9d7c0790c..aec1590d7 100644 --- a/src/utils/watchdog.cpp +++ b/src/utils/watchdog.cpp @@ -11,10 +11,11 @@ using std::chrono::milliseconds; using std::chrono::steady_clock; +namespace utils { + Watchdog::Watchdog(const milliseconds &min_timeout, const milliseconds &max_timeout, - const std::function &callback, - bool blocked) + const std::function &callback, bool blocked) : min_timeout_(min_timeout), max_timeout_(max_timeout), generator_(std::random_device{}()), @@ -66,3 +67,5 @@ void Watchdog::Run() { std::this_thread::sleep_until(t); } } + +} // namespace utils diff --git a/src/utils/watchdog.hpp b/src/utils/watchdog.hpp index 99fada704..1c62585a4 100644 --- a/src/utils/watchdog.hpp +++ b/src/utils/watchdog.hpp @@ -8,6 +8,8 @@ #include #include +namespace utils { + /** * @brief - Keeps track of how long it's been since `Notify` method was called. * If it wasn't called for a sufficiently long time interval (randomly chosen @@ -54,3 +56,5 @@ class Watchdog { std::atomic blocked_; std::thread thread_; }; + +} // namespace utils diff --git a/tests/distributed/raft/example_server.cpp b/tests/distributed/raft/example_server.cpp index 656ee4f52..72c4b18c6 100644 --- a/tests/distributed/raft/example_server.cpp +++ b/tests/distributed/raft/example_server.cpp @@ -27,7 +27,7 @@ int main(int argc, char **argv) { google::InitGoogleLogging(argv[0]); // Unhandled exception handler init. - std::set_terminate(&terminate_handler); + std::set_terminate(&utils::TerminateHandler); Server server(io::network::Endpoint(FLAGS_interface, stoul(FLAGS_port))); std::ofstream log(FLAGS_log, std::ios_base::app); diff --git a/tests/distributed/raft/messages.hpp b/tests/distributed/raft/messages.hpp index 506c791da..5cb33f3f3 100644 --- a/tests/distributed/raft/messages.hpp +++ b/tests/distributed/raft/messages.hpp @@ -11,7 +11,7 @@ using namespace communication::rpc; struct AppendEntryReq : public Message { AppendEntryReq() {} - AppendEntryReq(int val) : val(val) {} + explicit AppendEntryReq(int val) : val(val) {} int val; private: diff --git a/tests/manual/antlr_sigsegv.cpp b/tests/manual/antlr_sigsegv.cpp index 637ea03eb..81e434df9 100644 --- a/tests/manual/antlr_sigsegv.cpp +++ b/tests/manual/antlr_sigsegv.cpp @@ -21,7 +21,8 @@ TEST(Antlr, Sigsegv) { for (int i = 0; i < N; ++i) { threads.push_back(std::thread([&run]() { - while (!run); + while (!run) + ; while (run) { query::frontend::opencypher::Parser parser( "CREATE (:Label_T7 {x: 903}) CREATE (:Label_T7 {x: 720}) CREATE " @@ -97,7 +98,7 @@ int main(int argc, char **argv) { }); utils::SignalHandler::RegisterHandler(utils::Signal::Abort, []() { // Log the stacktrace and let the abort continue. - Stacktrace stacktrace; + utils::Stacktrace stacktrace; std::cerr << "Abort signal raised" << std::endl << stacktrace.dump() << std::endl; }); diff --git a/tests/manual/binomial.cpp b/tests/manual/binomial.cpp index efbe4d0e7..dc1518ba5 100644 --- a/tests/manual/binomial.cpp +++ b/tests/manual/binomial.cpp @@ -13,7 +13,7 @@ #include "utils/random/fast_binomial.hpp" static constexpr unsigned B = 24; -static thread_local FastBinomial<> rnd; +static thread_local utils::random::FastBinomial<> rnd; static constexpr unsigned M = 4; static constexpr size_t N = 1ULL << 34; diff --git a/tests/manual/card_fraud_generate_snapshot.cpp b/tests/manual/card_fraud_generate_snapshot.cpp index ff78b6fe5..a01e6c4e1 100644 --- a/tests/manual/card_fraud_generate_snapshot.cpp +++ b/tests/manual/card_fraud_generate_snapshot.cpp @@ -14,7 +14,6 @@ #include "durability/snapshot_encoder.hpp" #include "durability/version.hpp" #include "storage/address_types.hpp" -#include "utils/datetime/timestamp.hpp" #include "utils/string.hpp" #include "utils/timer.hpp" diff --git a/tests/manual/query_hash.cpp b/tests/manual/query_hash.cpp index ed77a9afa..7e26fd72f 100644 --- a/tests/manual/query_hash.cpp +++ b/tests/manual/query_hash.cpp @@ -4,7 +4,6 @@ #include #include "query/frontend/stripped.hpp" -#include "utils/type_discovery.hpp" DEFINE_string(q, "CREATE (n) RETURN n", "Query"); diff --git a/tests/manual/xorshift.cpp b/tests/manual/xorshift.cpp index 7b333a292..ce4efd591 100644 --- a/tests/manual/xorshift.cpp +++ b/tests/manual/xorshift.cpp @@ -13,7 +13,7 @@ #include "utils/random/xorshift128plus.hpp" -static thread_local Xorshift128plus rnd; +static thread_local utils::random::Xorshift128plus rnd; static constexpr unsigned B = 1 << 10; static constexpr uint64_t K = (uint64_t)(-1) / B; @@ -35,20 +35,20 @@ int main(void) { std::array threads; - for (auto& bucket : buckets) bucket.store(0); + for (auto &bucket : buckets) bucket.store(0); - for (auto& t : threads) t = std::thread([]() { generate(); }); + for (auto &t : threads) t = std::thread([]() { generate(); }); - for (auto& t : threads) t.join(); + for (auto &t : threads) t.join(); auto max = std::accumulate( buckets.begin(), buckets.end(), 0u, - [](auto& acc, auto& x) { return std::max(acc, x.load()); }); + [](auto &acc, auto &x) { return std::max(acc, x.load()); }); DCHECK(max != 0u) << "max is 0."; std::cout << std::fixed; - for (auto& bucket : buckets) { + for (auto &bucket : buckets) { auto x = bucket.load(); auto rel = bar_len * x / max; diff --git a/tests/unit/bolt_common.hpp b/tests/unit/bolt_common.hpp index c405badf1..199c5b1f0 100644 --- a/tests/unit/bolt_common.hpp +++ b/tests/unit/bolt_common.hpp @@ -63,7 +63,8 @@ class TestOutputStream { */ class TestBuffer { public: - TestBuffer(TestOutputStream &output_stream) : output_stream_(output_stream) {} + explicit TestBuffer(TestOutputStream &output_stream) + : output_stream_(output_stream) {} void Write(const uint8_t *data, size_t n) { output_stream_.Write(data, n); } void Chunk() {} diff --git a/tests/unit/bolt_session.cpp b/tests/unit/bolt_session.cpp index 8c6695202..5cbb8dea5 100644 --- a/tests/unit/bolt_session.cpp +++ b/tests/unit/bolt_session.cpp @@ -46,7 +46,7 @@ const uint8_t ignored_resp[] = {0x00, 0x02, 0xb0, 0x7e, 0x00, 0x00}; // Write bolt chunk header (length) void WriteChunkHeader(TestInputStream &input_stream, uint16_t len) { - len = bswap(len); + len = utils::Bswap(len); input_stream.Write(reinterpret_cast(&len), sizeof(len)); } diff --git a/tests/unit/executor.cpp b/tests/unit/executor.cpp index 12fb1ff73..a2a0ab8cd 100644 --- a/tests/unit/executor.cpp +++ b/tests/unit/executor.cpp @@ -8,7 +8,7 @@ TEST(Executor, Run) { std::atomic count{0}; { - Executor exec(std::chrono::milliseconds(500)); + utils::Executor exec(std::chrono::milliseconds(500)); // Be sure executor is sleeping. std::this_thread::sleep_for(std::chrono::milliseconds(100)); @@ -26,7 +26,7 @@ TEST(Executor, RunUnregister) { std::atomic count1{0}; std::atomic count2{0}; { - Executor exec(std::chrono::milliseconds(500)); + utils::Executor exec(std::chrono::milliseconds(500)); // Be sure executor is sleeping. std::this_thread::sleep_for(std::chrono::milliseconds(100)); auto job = exec.RegisterJob([&count1]() { ++count1; }); diff --git a/tests/unit/scheduler.cpp b/tests/unit/scheduler.cpp index d435ff0c9..6e4d032bc 100644 --- a/tests/unit/scheduler.cpp +++ b/tests/unit/scheduler.cpp @@ -12,7 +12,7 @@ TEST(Scheduler, TestFunctionExecuting) { std::atomic x{0}; std::function func{[&x]() { ++x; }}; - Scheduler scheduler; + utils::Scheduler scheduler; scheduler.Run("Test", std::chrono::seconds(1), func); EXPECT_EQ(x, 0); diff --git a/tests/unit/signals.cpp b/tests/unit/signals.cpp index d64894be4..d386a6754 100644 --- a/tests/unit/signals.cpp +++ b/tests/unit/signals.cpp @@ -18,7 +18,7 @@ TEST(Signals, Handler) { ASSERT_TRUE(utils::SignalHandler::RegisterHandler( utils::Signal::SegmentationFault, []() { std::cout << "Segmentation Fault" << std::endl; - Stacktrace stacktrace; + utils::Stacktrace stacktrace; std::cout << stacktrace.dump() << std::endl; })); diff --git a/tests/unit/timestamp.cpp b/tests/unit/timestamp.cpp index 91bf14a95..f7ec6d833 100644 --- a/tests/unit/timestamp.cpp +++ b/tests/unit/timestamp.cpp @@ -3,28 +3,28 @@ #include #include "gtest/gtest.h" -#include "utils/datetime/timestamp.hpp" +#include "utils/timestamp.hpp" TEST(TimestampTest, BasicUsage) { - auto timestamp = Timestamp::Now(); + auto timestamp = utils::Timestamp::Now(); std::cout << timestamp << std::endl; - std::cout << Timestamp::Now() << std::endl; + std::cout << utils::Timestamp::Now() << std::endl; std::this_thread::sleep_for(std::chrono::milliseconds(250)); - std::cout << Timestamp::Now().ToIso8601() << std::endl; + std::cout << utils::Timestamp::Now().ToIso8601() << std::endl; - ASSERT_GT(Timestamp::Now(), timestamp); + ASSERT_GT(utils::Timestamp::Now(), timestamp); std::cout << std::boolalpha; - std::cout << (timestamp == Timestamp::Now()) << std::endl; + std::cout << (timestamp == utils::Timestamp::Now()) << std::endl; - ASSERT_NE(timestamp, Timestamp::Now()); + ASSERT_NE(timestamp, utils::Timestamp::Now()); } -int main(int argc, char** argv) { +int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } diff --git a/tests/unit/watchdog.cpp b/tests/unit/watchdog.cpp index 0704a317e..803929079 100644 --- a/tests/unit/watchdog.cpp +++ b/tests/unit/watchdog.cpp @@ -8,7 +8,7 @@ using namespace std::chrono_literals; TEST(Watchdog, Run) { std::atomic count(0); - Watchdog dog(200ms, 200ms, [&count]() { ++count; }); + utils::Watchdog dog(200ms, 200ms, [&count]() { ++count; }); std::this_thread::sleep_for(250ms); EXPECT_EQ(count, 1); @@ -29,7 +29,7 @@ TEST(Watchdog, Run) { TEST(Watchdog, Blocker) { std::atomic count(0); - Watchdog dog(200ms, 200ms, [&count]() { ++count; }); + utils::Watchdog dog(200ms, 200ms, [&count]() { ++count; }); std::this_thread::sleep_for(250ms); EXPECT_EQ(count, 1);